body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is a code I wrote for solving the famous nqueens problem. It returns only the first solution. I would like your reviews and comments and ways to convert it to a solution which will return a set of all solutions are welcome.
So, here I go:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int isSafe(int** matrix, long long row, long long col, long long matrixDim) {
//check col
for (long long i = 0; i < row; i++) {
if (matrix[i][col] == 1) {
return 0;
}
}
//check upper left diagonal
for (long long i = row, j = col;;) {
i--; j--;
if (i < 0 || j < 0) {
break;
}
if (matrix[i][j] == 1) {
return 0;
}
}
//check upper right diagonal
for (long long i = row, j = col;;) {
i--; j++;
if (i < 0 || j == matrixDim) {
break;
}
if (matrix[i][j] == 1) {
return 0;
}
}
//check lower left diagonal
for (long long i = row, j = col;;) {
i++; j--;
if (i == matrixDim || j < 0) {
break;
}
if (matrix[i][j] == 1) {
return 0;
}
}
//check lower right diagonal
for (long long i = row, j = col;;) {
i++; j++;
if (i == matrixDim || j == matrixDim) {
break;
}
if (matrix[i][j] == 1) {
return 0;
}
}
return 1;
}
void printSqMatrix(int** matrix, long long Dim) {
for (int i = 0; i < Dim; i++) {
for (int j = 0; j < Dim; j++) {
printf("%d ", matrix[i][j]);
}
puts("");
}
}
int solve(int** chessBoard, long long row_index, long long boardSize) {
if (row_index == boardSize) {
return 1;
}
long long j;
for (j = 0; j < boardSize; j++) {
if (isSafe(chessBoard, row_index, j, boardSize)) {
chessBoard[row_index][j] = 1;
int retVal = solve(chessBoard, row_index + 1, boardSize);
if (retVal == 1) {
return 1;
}
else if (retVal == -1) {
puts("Something seriously wrong with execution");
exit(1);
}
chessBoard[row_index][j] = 0;
}
}
if (j == boardSize) {
return 0;
}
return 1; //never reaches here (written to solve a warning saying not all codepaths return a value
}
int main(void) {
int** board = NULL;
long long sizeOfBoard = 0;
printf("Enter the size of the board: ");
scanf("%lld", &sizeOfBoard);
board = malloc(sizeof(int*) * sizeOfBoard);
for (long long i = 0; i < sizeOfBoard; i++) {
board[i] = malloc(sizeof(int) * sizeOfBoard);
for (long long k = 0; k < sizeOfBoard; k++) { //if I don't write this loop, the 0s get printed as 3452816845....Why???
board[i][k] = 0;
}
}
solve(board, 0, sizeOfBoard);
printSqMatrix(board, sizeOfBoard);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T16:47:28.140",
"Id": "474570",
"Score": "0",
"body": "Please take a look at https://chat.stackoverflow.com/rooms/54304/c#_=_"
}
] |
[
{
"body": "<ul>\n<li><blockquote>\n<pre><code>//if I don't write this loop, the 0s get printed as 3452816845....Why???\n</code></pre>\n</blockquote>\n\n<p>Because <code>malloc</code> doesn't initialize an allocated memory. It contains garbage. You may avoid the explicit loop by using <code>calloc</code>.</p>\n\n<p>As a side note, prefer <code>sizeof(variable)</code> to <code>sizeof(type)</code>, e.g.</p>\n\n<pre><code>board[i] = malloc(sizeof(*board[i]) * sizeOfBoard);\n</code></pre>\n\n<p>This way, if you ever change the type of board squares, this line wouldn't change. No double maintenance.</p></li>\n<li><p>The code adds queens into the rows sequentially. There is no need to test lower diagonals: there are no queens there yet.</p></li>\n<li><p>Working with the entire 2-dimensional board is an overkill. A one-dimensional array of queen files suffices. Besides, testing for placement safety becomes much simpler:</p>\n\n<pre><code>bool is_safe(int * queens, long long row, long long col, long long dim) {\n for (long long rank = 0; rank < row; rank++) {\n if (queens[rank] == col) {\n // Another queen is at this column already\n return false;\n if ((row - rank) == abs(queens[rank] - col)) {\n // A square is under diagonal attack\n return false;\n }\n return true;\n}\n</code></pre></li>\n<li><p>A for having all the solutions, do not break the loop when <code>retVal == 1</code>, and</p>\n\n<pre><code>if (row_index == boardSize) {\n do_something();\n return 1;\n}\n</code></pre>\n\n<p>where <code>do_something()</code> may print the board, or save the board in a global state, or whatever suites your needs.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:21:40.570",
"Id": "474460",
"Score": "2",
"body": "@chux-ReinstateMonica Oops indeed. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T18:17:48.160",
"Id": "241771",
"ParentId": "241769",
"Score": "9"
}
},
{
"body": "<p>There is no benefit in using <code>long long</code> for the <code>row, col</code>.</p>\n\n<p>For practical uses, <code>int</code> would be sufficient.</p>\n\n<p>For pedantically large cases, use <code>size_t</code>. It is some <em>unsigned</em> integer type.</p>\n\n<p>[edit] Concerning the holy wars of using <code>size_t</code> vs. some signed type: Code to your group's coding standard. For personal use, I model code to the C standard library which favors <code>size_t</code> for size concerns.</p>\n\n<hr>\n\n<p><strong>Allocating</strong></p>\n\n<p>Getting the right size is prone to failure when code use the type for sizing. Note the 2 below (from OP's code and a discussion comment)</p>\n\n<pre><code>board[i] = malloc(sizeof(int) * sizeOfBoard);\nsolutionSet = realloc(solutionSet, sizeof(solutionSet) + sizeof(chessBoard));\n</code></pre>\n\n<p>The first obliges a check: \"Is <code>int</code> correct?\" I can search around and later find <code>int** board</code> and conclude yes, it matches. Yet if code was below, no search needed. Consider using <code>ptr = malloc(sizeof *ptr * n);</code> it is easy to code right, review and maintain.</p>\n\n<pre><code>board[i] = malloc(sizeof *(board[i]) * sizeOfBoard);\n</code></pre>\n\n<p>With the idiom <code>ptr = malloc(sizeof *ptr * n);</code>, the below looks wrong. The size calculation is using the size of a pointer and not the size of of its referenced type.</p>\n\n<pre><code>solutionSet = realloc(solutionSet, sizeof(solutionSet) + sizeof(chessBoard));\n// ^^^^^^^^^^^^^\n// maybe sizeof *solutionSet\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T06:57:22.150",
"Id": "474489",
"Score": "0",
"body": "size_t in my PC is simply a typedef of unsigned long long. As a result the check <0 fails."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:24:12.780",
"Id": "474517",
"Score": "1",
"body": "@d4rk4ng31 Easy enough to code the check before the decrement: `i--; j--;\n if (i < 0 || j < 0) {\n break;\n }` --> `if (i == 0 || j == 0) {\n break;\n } i--; j--;`. Even though `size_t` is `unsigned long long` on your machine, good code adapts well to many platforms. In the cases of sizing and array indexing, `size_t` is the type to use. Yes `size_t` is some unsigned type, yet that is not difficult to account for in coding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:30:59.757",
"Id": "474519",
"Score": "0",
"body": "Will you please take a look at https://github.com/fish-shell/fish-shell/issues/3493#issue-185297171 ? And also will you correct me if I'm wrong? I really could use some help 'bout this size_t thing :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:32:40.563",
"Id": "474520",
"Score": "0",
"body": "Oh, and what should size_t actually be? I mean I've heard that some machines define it as a `struct`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:43:19.957",
"Id": "474524",
"Score": "1",
"body": "The link is more of a rant than a thoughtful discussion yet one quote I do find some agreement: \"Which means those statements are alligators waiting to bite someone in the ass if they change the code without understanding the subtleties of those statements.\". If coding with an unsigned is done by someone without understanding the subtleties, there are issues. Yet the C standard library if rife with `size_t` usages. So size_t is fundamentally not avoidable. If coding with unsigned poses too much troubles, perhaps the coder should be using a different language?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:44:54.863",
"Id": "474525",
"Score": "0",
"body": "RE: \"If coding with unsigned poses too much troubles, perhaps the coder should be using a different language?\". Well no-one's ever put it that way. Thanks a lot for clarifying :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:45:24.820",
"Id": "474526",
"Score": "0",
"body": "@d4rk4ng31 Re: \"what should size_t actually be?\" --> The code should use `size_t` as it is defined in <stddef.h> (and other headers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:48:08.317",
"Id": "474528",
"Score": "1",
"body": "@d4rk4ng31 Usage of `size_t` or not steps into a holy war. You can readily find many strong opinions on it either way - and unfortunate little constructive discussion. I find it useful useful. YMMV."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:22:17.620",
"Id": "241778",
"ParentId": "241769",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241771",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T17:30:25.377",
"Id": "241769",
"Score": "4",
"Tags": [
"c",
"n-queens"
],
"Title": "A solution for n-queens in C"
}
|
241769
|
<p>I'm a relatively new programmer. I've made a simple Vigenere cipher program. It takes three arguments and acts on a file. I have made some of the steps more "explict" for myself by using more lists than I need to, rather than applying multiple "transformations" at a time. I would appreciate feedback on how this code would be written differently by people who know more than I do.</p>
<pre><code>#!/usr/bin/env python3
# vigenere.py - This program has two modes, encrypt and decrypt. It takes
# three arguments: the mode('encrypt' or 'decrypt'), a keyword, and a
# filename to act upon. It is designed to work with lowercase letters.
from sys import argv
from itertools import cycle
# User specifies a mode, a key, and a file with argv arguments
def start():
if len(argv) > 1:
mode = argv[1]
key = argv[2]
plaintextFilename = argv[3]
else:
print('Please supply mode, key, and file as arguments.')
exit()
# Start the mode selected
if mode == 'encrypt':
encryptMode()
elif mode == 'decrypt':
decryptMode()
else:
print('Please supply \'encrypt\' or \'decrypt\' mode.')
exit()
# Encryption Mode
def encryptMode():
# Open the alpha plaintext file as an object
alphaPlaintextFileObj = open(argv[3])
# Create the ordinal plaintext data structure
ordinalPlaintext = []
# Populate the ordinal plaintext data structure
for c in alphaPlaintextFileObj.read():
if c == ' ':
ordinalPlaintext.append(' ')
else:
o = ord(c) - 65
ordinalPlaintext.append(o)
# Create an ordinal ciphertext data structure
ordinalCiphertext = []
# Turn the key into an ordinal key where a = 1, etc.
ordinalKey = []
key = argv[2]
for c in key:
n = ord(c) - 96
ordinalKey.append(n)
# Populate the ordinalCiphertext structure with numbers shifted using the
# ordinal key.
for k, p in zip(cycle(ordinalKey), ordinalPlaintext):
if p == ' ':
ordinalCiphertext.append(' ')
else:
c = (k + p) % 25
ordinalCiphertext.append(c)
# Create the alpha ciphertext file
alphaCiphertextFilename = argv[3] + '_encrypted'
alphaCiphertextFileObj = open(alphaCiphertextFilename, 'w')
# Populate the alpha ciphertext file
for c in ordinalCiphertext:
if c == ' ':
alphaCiphertextFileObj.write(' ')
else:
l = chr(int(c) + 65)
alphaCiphertextFileObj.write(l)
# Save and close the plaintext and ciphertext files.
alphaPlaintextFileObj.close()
alphaCiphertextFileObj.close()
# Print a message telling the user the operation is complete.
print(f'{argv[3]} encrypted as {alphaCiphertextFilename}')
# Decryption Mode
def decryptMode():
# Open the alpha ciphertext file as an object
alphaCiphertextFileObj = open(argv[3])
# Create the ordinal ciphertext data structure
ordinalCiphertext = []
# Populate the ordinal ciphertext data structure
for c in alphaCiphertextFileObj.read():
if c == ' ':
ordinalCiphertext.append(' ')
else:
o = ord(c) - 97
ordinalCiphertext.append(o)
# Create the ordinal key
ordinalKey = []
key = argv[2]
for c in key:
n = ord(c) - 96
ordinalKey.append(n)
#Create the ordinal plaintext data structure
ordinalPlaintext = []
# Populate the ordinal plaintext data structure with the modular
# difference of the ordinal ciphertext and the ordinal key
for k, c in zip(cycle(ordinalKey), ordinalCiphertext):
if c == ' ':
ordinalPlaintext.append(' ')
else:
p = (c - k) % 25
ordinalPlaintext.append(p)
# Create the alpha plaintext file
alphaPlaintextFilename = argv[3] + '_decrypted'
alphaPlaintextFileObj = open(alphaPlaintextFilename, 'w')
# Convert the ordinal plaintext to an alpha plaintext file,
# 'filename_decrypted'
for p in ordinalPlaintext:
if p == ' ':
alphaPlaintextFileObj.write(' ')
else:
l = chr(int(p) + 97)
alphaPlaintextFileObj.write(l)
# Save and close the ciphertext and plaintext files
alphaCiphertextFileObj.close()
alphaPlaintextFileObj.close()
# Print a message telling the user the operation is complete
print(f'{argv[3]} decrypted as {alphaPlaintextFilename}')
start()
</code></pre>
|
[] |
[
{
"body": "<pre><code>def start():\n</code></pre>\n\n<p>I'd call this function <code>main</code> as that's what it is generally called.</p>\n\n<pre><code>if mode == 'encrypt':\n encryptMode()\nelif mode == 'decrypt':\n decryptMode()\n</code></pre>\n\n<p>Why not call this <code>encrypt</code> and <code>decrypt</code>? The methods to actually perform the encryption / decryption after all; you're not <em>setting</em> a mode.</p>\n\n<pre><code>alphaPlaintextFileObj = open(argv[3])\n</code></pre>\n\n<p>It seems to me that file handling can be perfectly split from the <code>encrypt</code> function, <em>especially</em> if you read in all the data before encryption happens anyway.</p>\n\n<pre><code>ordinalPlaintext = []\n</code></pre>\n\n<p>Why would you first convert the entire plaintext / ciphertext to ordinals? This can be done on a per-character base, preferably using a separate method. Then it also becomes easier to skip space and such, which you now have to handle twice. </p>\n\n<p>Conversion to ordinals - or more precisely, indices within the Vigenere alphabet - is of course exactly what is needed, so that's OK.</p>\n\n<pre><code>o = ord(c) - 65\n</code></pre>\n\n<p>65 is an unexplained magic number, why not use <code>ord('a')</code> instead or use a constant with that value?</p>\n\n<pre><code>n = ord(c) - 96\n</code></pre>\n\n<p>Why is <code>A</code> a 1? What about <code>Z</code> in that case? And why do we suddenly use the uppercase character set?</p>\n\n<pre><code>for k, p in zip(cycle(ordinalKey), ordinalPlaintext):\n</code></pre>\n\n<p>Now this I like, it is very clear what is done here, and it is good use of Python specific functionality.</p>\n\n<pre><code>c = (k + p) % 25\n</code></pre>\n\n<p>Wrong! You always perform a modular calculation with the same size as the alphabet. This might work as well (if you forget about the <code>Z</code>) but it's not Vigenere as it was written down a long time ago.</p>\n\n<pre><code>alphaPlaintextFileObj.close()\n</code></pre>\n\n<p>Always close files as soon as they are not necessary any more. You already read all of the plaintext, no need to keep that file handle around.</p>\n\n<hr>\n\n<p>What I'm missing is validation that the contents of the plaintext consist of characters that are out of range, and a way of handling those. The same thing goes for the key, which should consist of all uppercase characters, but lowercase characters are used without issue.</p>\n\n<hr>\n\n<p>Furthermore, if you take a good look, then decryption is the same as encryption, except for <code>p = (c - k) % 25</code> and - of course - the file handling. Now the file reading and writing should not be in either method, so let's exclude that. That leaves us with that single assignment / expression. Of that, only the <code>-</code> sign is really different.</p>\n\n<p>This is why most people will write a single \"private\" <code>_crypt</code> method that simply takes an integer of <code>1</code> for encryption and <code>-1</code> for decryption. Then the expression becomes <code>(charIndex + direction * keyIndex) % alphabetSize</code>.</p>\n\n<p>Currently you are violating the \"DRY principle\": don't repeat yourself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T19:29:40.740",
"Id": "241774",
"ParentId": "241770",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T17:38:56.863",
"Id": "241770",
"Score": "3",
"Tags": [
"python",
"vigenere-cipher"
],
"Title": "Simple Vigenere Cipher In Python"
}
|
241770
|
<p>As part of an utilities "library" I'm putting together I've worked to make a multi-threaded for-each that splits a job of applying a function to each element of an index-accessible container in multiple threads.</p>
<p>The first version used to spawn new threads, run them, and join them after one call.
This versions never stops the threads (well, it does upon destruction of course), but instead keeps them waiting. This should remove the overhead of starting new threads each time the "foreach" is called.</p>
<p>I'm not experienced, especially in multi-threaded workloads. I think thread safety is taken care of. It works as expected, but I'm not sure if I overcomplicated my life and if there was some more straightforward solution. In particular if i really need one condition_variable/mutex for each running thread.</p>
<p>Enough said, this is the code:</p>
<pre><code>#include <thread>
#include <condition_variable>
namespace utils
{
template <typename Container, typename Function>
class async_foreach
{
//std::mutex out;
public:
//this is the constant size of all the dynamically allocated arrays
const size_t threads_count;
//holds all the threads
std::unique_ptr<std::thread[]> threads;
//condition variables and mutexes to wait-notify individual threads
std::unique_ptr<std::condition_variable[]> conditionals;
std::unique_ptr<std::mutex[]> mutexes;
//conditional and mutex to wait-notify caller thread
std::condition_variable main_conditional;
std::mutex main_mutex;
//make sure all threads completed their job
size_t returned_count = 0;
//first and last index of the container an individual thread has to take care of
std::unique_ptr<std::pair<size_t, size_t>[]> indexes;
//handle destruction
bool running = true;
Function* function;
Container* container;
//constructor only cares about allocating the arrays
async_foreach(size_t threads_count = std::thread::hardware_concurrency()) :
threads_count(threads_count),
threads(std::make_unique<std::thread[]>(threads_count)),
conditionals(std::make_unique<std::condition_variable[]>(threads_count)),
mutexes(std::make_unique<std::mutex[]>(threads_count)),
indexes(std::make_unique<std::pair<size_t, size_t>[]>(threads_count))
{
//{ std::unique_lock<std::mutex> lock(out); std::cout << "spawning threads" << std::endl; }
for (size_t i = 0; i < threads_count; i++)
{
threads.get()[i] = std::thread(&async_foreach::thread_method<Container, Function>, this, i);
}
}
~async_foreach()
{
running = false;
//wake up all threads with running set to false
for (size_t i = 0; i < threads_count; i++)
{
std::unique_lock<std::mutex> lock(mutexes.get()[i]);
conditionals.get()[i].notify_one();
}
//wait all threads to complete
for (size_t i = 0; i < threads_count; i++)
{
threads.get()[i].join();
}
}
//call operator for foreach
//container must be an index-accessible data structure (vector, array...)
void operator()(Container& container, Function function)
{
//populate members so they can be accessed by each thread
this->function = function;
this->container = &container;
//{ std::unique_lock<std::mutex> lock(out); std::cout << "waking threads" << std::endl; }
//prepare to split the jobs
size_t size = container.size();
size_t thread_jobs = size / threads_count;
size_t leftover = size % threads_count;
size_t current_index = 0;
for (size_t i = 0; i < threads_count; i++)
{
size_t from = current_index;
size_t to = from + thread_jobs;
if (leftover) { to++; leftover--; }
current_index = to;
//assign sectors
indexes.get()[i].first = from;
indexes.get()[i].second = to;
//wake up threads
conditionals.get()[i].notify_one();
}
//{ std::unique_lock<std::mutex> lock(out); std::cout << "waiting threads" << std::endl; }
//wait for each thread to complete
if (true)
{
std::unique_lock<std::mutex> lock(main_mutex);
main_conditional.wait(lock, [&]()
{
//{ std::unique_lock<std::mutex> lock(out); std::cout << returned_count << " threads returned" << std::endl; }
return returned_count == threads_count;
});
}
//{ std::unique_lock<std::mutex> lock(out); std::cout << "all threads returned (possibly, maybe)(?)" << std::endl; }
//reset the counter for next call
returned_count = 0;
}
//main method of each thread
template <typename Container, typename Function>
void thread_method(size_t index)
{
std::mutex& mutex = mutexes.get()[index];
std::condition_variable& conditional = conditionals.get()[index];
size_t& from = indexes[index].first;
size_t& to = indexes[index].second;
//{ std::unique_lock<std::mutex> lock(out); std::cout << " thread " << index << " awaiting your orders" << std::endl; }
while (true)
{
if (true) //just to get the ide to indent the block
{
std::unique_lock<std::mutex> lock(mutex);
//go sleep until there's something to actually do
conditional.wait(lock);
}
//{ std::unique_lock<std::mutex> lock(out); std::cout << " thread " << index << " waking up" << std::endl; }
//happens upon destruction of the class instance
if (!running) { break; }
//call the function for each element of the part of the container this thread has to take care about
for (size_t i = from; i < to; i++)
{
function((*container)[i]);
}
//signal this thread completed its job and eventually wake up the main thread
if (true)
{
std::unique_lock<std::mutex> lock(main_mutex);
//{ std::unique_lock<std::mutex> lock(out); std::cout << " thread " << index << " signaling completion" << std::endl; }
returned_count++;
if (returned_count == threads_count) { main_conditional.notify_one(); }
}
}
}
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:06:03.833",
"Id": "474455",
"Score": "2",
"body": "for_each has some built in tricks: https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t in case you don't know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:24:25.283",
"Id": "474461",
"Score": "0",
"body": "@sudorm-rfslash nevermind, there was an error making it faster but incorrect, just solved it; now its around 15% slower than std::for_each; i'd still apreciate some criticism to improve. It was all about making experience, not making the ultimate foreach. Thanks"
}
] |
[
{
"body": "<p>1) Basics:</p>\n\n<p>Use some naming pattern for member variables of classes.</p>\n\n<p>E.g., <code>bool m_running;</code> instead of <code>bool running;</code> this helps reader to understand that one works with class members and not something else unrelated. Also it might be helpful to have a character or two to identify the type the variable in the name. So that <code>Function* function;</code> and <code>Container* container;</code> become <code>Function* m_ptr_function = nullptr;</code> and <code>Container* m_ptr_container = nullptr;</code>. This way you could've easily spotted a silly error:</p>\n\n<pre><code>void operator()(Container& container, Function function)\n{\n //populate members so they can be accessed by each thread\n this->function = function;\n this->container = &container;\n\n size_t size = container.size();\n ...\n}\n</code></pre>\n\n<p>Unlike, the former which might look fine (at least in per-line scan), following is clearly wrong:</p>\n\n<pre><code>void operator()(Container& container, Function function)\n{\n //populate members so they can be accessed by each thread\n m_ptr_function = function; // wait... isn't it a pointer?\n m_ptr_container = &container;\n\n size_t size = m_ptr_container.size(); // wait what?\n ...\n}\n</code></pre>\n\n<p>2) Multi-theading policies:</p>\n\n<p>Creating a thread takes a certain amount of resources. So it might be counter productive to generate a new thread pool for each <code>async_foreach</code>. Utilize a separate generally used thread pool class and make <code>async_foreach</code> into a class that utilizes this said thread pool.</p>\n\n<p>3) API for <code>async_foreach</code>:</p>\n\n<p>From the looks of it you just want a function that runs over a sequence of elements.\nInstead, you have a class that requires several steps to execute.\nWhy not wrap everything inside a single template function call instead of asking user to write the same wrapping each time?</p>\n\n<p>4) Bugs and Issues: (aside from various typos)</p>\n\n<p><code>conditional.wait(lock);</code> doesn't necessarily wait till it gets a notify. According to standard the wait might end unexpectedly. You must have a condition for the wait.</p>\n\n<p>I don't think that you need so many conditional variables and mutexes. It isn't a task that requires a bunch of a bunch of unrelated mutexes. In your case you create a thread in the constructor, enable it to perform a single task in the execution block, and close it. It makes little sense to have so much mutexes - or rather it is senseless to have any at all. All of this should've been inside a single function call - this would make the whole process much easier.</p>\n\n<p>If your class performed a sequence of tasks that require synchronization then having a single or a few of mutex+condition variable would make some sense.</p>\n\n<hr>\n\n<p>Currently, it will surely perform worse than <code>std::for_each(...)</code> and it has a more complex API.</p>\n\n<p>Conclusion: use/make an executor class (i.e., a thread pool) instead and this whole <code>async_foreach</code> would become a simple routine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:33:04.587",
"Id": "474645",
"Score": "0",
"body": "\"All of this should've been inside a single function call - this would make the whole process much easier.\"\nNo, i want a separate class to NOT spawn new threads every time it's used.\n\"I don't think that you need so many conditional variables and mutexes\"\nHow would i keep each thread waiting without one conditional variable each? \n\"Conclusion: use/make an executor class (i.e., a thread pool) instead and this whole async_foreach would become a simple routine.\" i'll go that route ty"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:34:49.417",
"Id": "474648",
"Score": "0",
"body": "\"Currently, it will surely perform worse than std::for_each(...)\" it's around 15% slower"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T13:19:58.313",
"Id": "474656",
"Score": "0",
"body": "@Barnack you generated a class that can be used only for a single sequence call, for only a single type of container, and single type of function. The only reason `std::for_each(...)` could've performed worse is if you either utilized it improperly or you have a crappy `std` library. Or you measured the execution time incorrectly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T13:26:24.590",
"Id": "474657",
"Score": "0",
"body": "@Barnack The only issue with `std::for_each(...)` is that it counts the number of calls instead of using size. There is something wrong if it slows the runtime by 15% percent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T13:28:06.760",
"Id": "474658",
"Score": "0",
"body": "nono, i mean mine is slower than std::for_each, i didn't expect to match std anyways, although with both yours and indi's suggestions i'll try to get as close as possible. @ALX23z"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T01:22:15.037",
"Id": "474725",
"Score": "1",
"body": "@Barnack - \"How would i keep each thread waiting without one conditional variable each?\" You keep em` all waiting on a single mutex and single condition variable. Not one for each, one for all. `notify_one` awakens only a single one of them."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T22:29:46.927",
"Id": "241840",
"ParentId": "241776",
"Score": "2"
}
},
{
"body": "<h1>General design</h1>\n\n<p>Before digging into the nitty-gritty, I like to take a moment to consider the overall design. The main difference between a beginner and a pro (or between a <em>competent</em> pro and an incompetent one), is that a good pro knows that 80–90% of the <em>real</em> work of programming is done before you even tap a single key. Every second you spend <em>thinking</em> about how you’re going to tackle your problem saves you an hour—if not a day, or even a <em>week</em>—of work later.</p>\n\n<p>And this is <em>especially</em> true if what you’re working on is a library. Application code and business logic code can be clunky (but shouldn’t be, obvs), because you’re only using it once. <em>Library</em> code is meant to be used over and over, so if it’s clunky, it <em>really</em> hurts.</p>\n\n<p>You provided the code for your utility… but you didn’t provide any <em>examples</em> of how that utility is meant to be <em>used</em>. That, to me, is a red flag. It tells me you probably didn’t give all that much thought to the ergonomics of how this utility is going to be used. (It also makes me wonder if you even <em>tried</em> to use it. Does this code even compile? I see some things in there that tell me it might not. But more on that later.)</p>\n\n<p>So let’s look at what your utility might look like when in use:</p>\n\n<pre><code>auto data = std::vector<int>{};\n// fill data with data...\n\nauto func = [](auto val)\n{\n // do something with val...\n};\n\nauto f1 = utils::async_for_each<decltype(data), decltype(func)>{};\n\nf1(data, func);\n</code></pre>\n\n<p>So I have to give the type of both the data and the function when constructing the object… well that’s clunky.</p>\n\n<p>Worse, because those types are now embedded in the object, I can't do this:</p>\n\n<pre><code>auto other_data = std::array<int>{};\nauto more_other_data = std::vector<long>{};\n\nf1(other_data, func); // nope, won't compile\nf1(more_other_data, func); // nope\n</code></pre>\n\n<p>I need to create whole new objects, with whole new thread pools. Which, really, kinda defeats the whole purpose, if your goal was to eliminate the overhead of thread creation each time the “foreach” is used.</p>\n\n<p>Is that really the interface you want your <code>async_for_each()</code> to have?</p>\n\n<p>In my opinion, the underlying problem here is you’re making the classic mistake of creating a “god object”: a single “thing” that just does too much stuff. Your <code>async_for_each</code> class does <em>at least</em> three different jobs that I might very reasonably want to customize differently:</p>\n\n<ol>\n<li>it’s a thread pool</li>\n<li>it’s a task scheduler</li>\n<li>it’s an algorithm</li>\n</ol>\n\n<p>Any one of those things is useful independently, and I might want to be able to do something differently from what you have done:</p>\n\n<ol>\n<li>I might want to create my own threads with specific affinities, or maybe use special thread types like GPU threads.</li>\n<li>I might want to use priority scheduling or a job queue or some other kind of scheduling rather than round-robin scheduling by chunks, because the jobs might not all take the same amount of time.</li>\n<li>I might want to stop at the first “success” or “fail” result rather than barrelling through the whole data set.</li>\n</ol>\n\n<p>If these things were all separate, rather than all baked together into one object, not only would that allow me more control and flexibility, it would actually make the interface simpler. For example:</p>\n\n<pre><code>auto tp = thread_pool();\n\nauto scheduler = basic_scheduler{tp};\n\nasync_for_each(scheduler, data, func);\n\n// but also, these would reuse the thread pool and scheduler:\nasync_for_each(scheduler, other_data, func);\nasync_for_each(scheduler, more_other_data, func);\n</code></pre>\n\n<p>And as others have pointed out, if you make these things standard-library-compatible, you get all the benefits of the standard library (such as tons of different algorithms, and not just a limited form of <code>for_each</code>) for free.</p>\n\n<p>So let’s dive into the code…</p>\n\n<h1>Code review</h1>\n\n<pre><code>#include <thread>\n#include <condition_variable>\n</code></pre>\n\n<p>These seem like a rather limited set of headers to include. I see in the class itself that it uses <code>unique_ptr</code> and <code>mutex</code>… does the code even compile with just these headers?</p>\n\n<pre><code>template <typename Container, typename Function>\nclass async_foreach\n</code></pre>\n\n<p>So you’ve templated the class on <code>Container</code> and <code>Function</code> because you want to store a pointer to the container and a pointer to the function. Okay, but… is that necessary?</p>\n\n<p>Step back and rethink the problem. Does the thread function really, actually need to call <code>function(container[index])</code>?</p>\n\n<p>Let me show you what I mean. Right now, your code is doing something like this:</p>\n\n<pre><code>operator()(container, function)\n{\n // Set up data for the thread to use:\n _p_container = &container;\n _p_function = &function;\n _p_indices[i] = {from, to}; // for each thread[i]\n\n // Signal the threads there's data to use,\n // then wait for them to finish.\n}\n\nthread_method(index)\n{\n // ... looping, waiting for signal, then gets the signal to start...\n\n for (i = (*_p_indices)[i].from ... (*_p_indices)[i].to)\n (*_p_function)((*_p_container)[i]);\n\n // ... and so on (ie, signal completion, etc.)\n}\n</code></pre>\n\n<p>What if, instead, it did something like this:</p>\n\n<pre><code>operator()(container, function)\n{\n // Set up data for the thread to use:\n auto lambda = [&container, &function, from, to]()\n {\n for (i = from ... to)\n function(container[i]);\n };\n\n // For each thread:\n _function[index] = lambda; // _function is a vector<function<void()>>\n\n // Signal the threads there's data to use,\n // then wait for them to finish.\n}\n\nthread_method(index)\n{\n // ... looping, waiting for signal, then gets the signal to start...\n\n _function[index]();\n\n // ... and so on (ie, signal completion, etc.)\n}\n</code></pre>\n\n<p>Note that <code>thread_method()</code> now doesn’t need to know the container or function type—it’s just calling a type-erased void function. By extension, the constructor and class also don’t need to know these things, so the class doesn’t need to be a template anymore. The only part of the interface that needs to know the container and function type is <code>operator()()</code>… and that’s cool because it can deduce those types directly from the function arguments. Which means my original example code could become:</p>\n\n<pre><code>auto data = std::vector<int>{};\n// fill data with data...\n\nauto func = [](auto val)\n{\n // do something with val...\n};\n\n// Note: no template types necessary...\nauto f = utils::async_for_each{};\n\n// ... because they're deduced here\nf(data, func);\n\n// And now these will work, too:\nauto other_data = std::array<int>{};\nf(other_data, func);\n\nauto more_other_data = std::vector<long>{};\nf(more_other_data, func);\n</code></pre>\n\n<p>I think that’s much easier to work with.</p>\n\n<pre><code>//this is the constant size of all the dynamically allocated arrays\nconst size_t threads_count;\n//holds all the threads\nstd::unique_ptr<std::thread[]> threads;\n//condition variables and mutexes to wait-notify individual threads\nstd::unique_ptr<std::condition_variable[]> conditionals;\nstd::unique_ptr<std::mutex[]> mutexes;\n</code></pre>\n\n<p>(I assume all these data members are meant to be private, and are only left public because you’re fiddling. I see no reason why they can or should be accessible outside of the class.)</p>\n\n<p>This is the part of your class that irks my C++ bones the most. Why all the <code>unique_ptr</code> arrays? Why not vectors? I see no rational reason why one might prefer manually allocating arrays here… I mean, okay, granted, the size will be duplicated across all the vectors (except maybe not! but I’ll get to that), but compared to all the overhead of the context switches, does that really matter?</p>\n\n<p>Also, when I see a bunch of arrays side-by-side, all of which are the same size because a single iota of data is spread out across <code>array_1[i]</code>, <code>array_2[i]</code>, <code>array_3[i]</code>, … etc, I immediately wonder why you don’t create a struct to package everything together, and avoid the complexity of maintaining the invariant that <code>array_1.size == array_2.size == array_3.size…</code>. (I mean, sure, there <em>are</em> very rare cases where a struct-of-arrays is better than an array-of-structs, but I can’t see that being the case here.)</p>\n\n<p>In other words, why not this:</p>\n\n<pre><code>// private inner class:\nstruct pool_thread_t\n{\n std::thread thread;\n std::condition_variable cv;\n std::mutex m;\n std::size_t from;\n std::size_t to;\n};\n\nstd::vector<pool_thread_t> threads;\n</code></pre>\n\n<p>(I mean, maybe you might have to wrap the condition variable and mutex—or the whole struct—in a <code>unique_ptr</code> to make them easier to work with, because they’re not movable or copyable, but that’s hardly a major problem. Of course, you don’t really need a cv and mutex for each thread anyway, but I’ll get to that.)</p>\n\n<pre><code>bool running = true;\n</code></pre>\n\n<p>This should be an <code>atomic<bool></code>. Why? Because it is both read and set without any mutexes guarding it. It will probably “work” on most real-world platforms without a problem… but who knows what might happen on some exotic hardware with false sharing or something else weird going on. Plus, if anyone makes any changes (like reusing the flag for other purposes, for example, as I coincidentally suggest next), things could break very easily.</p>\n\n<pre><code>async_foreach(size_t threads_count = std::thread::hardware_concurrency()) :\n// ... [snip] ...\n {\n for (size_t i = 0; i < threads_count; i++)\n {\n threads.get()[i] = std::thread(&async_foreach::thread_method<Container, Function>, this, i);\n }\n }\n</code></pre>\n\n<p>There is a major bug lurking here.</p>\n\n<p>Imagine <code>threads_count</code> is 8. Your loop starts, 6 threads get constructed just fine… but thread 7 fails and throws an exception. Now what happens?</p>\n\n<p>Well, to start with, you’ve got 6 deadlocked threads, waiting on a condition variable that will never be signalled.</p>\n\n<p>But then it gets <em>really</em> bad. Because the stack will unwind, and all those <code>unique_ptr</code> arrays will be freed, and now those 6 threads are locking/unlocking mutexes that don’t even exist anymore, checking zombie condition variables and <code>bool</code>s. Anything could happen now; nasal demons, et al.</p>\n\n<p>You need to re-engineer how this is going to work. In your constructor, you could wrap that <code>for</code> loop in a <code>try</code> block, while keeping track of how far along you got in the construction. If an exception is thrown, then set <code>running</code> to <code>false</code> and for all the threads that have already been successfully constructed, notify them, and wait for them to join. Then and only then let the exception thrown propagate.</p>\n\n<pre><code>void operator()(Container& container, Function function)\n</code></pre>\n\n<p>Is there a reason <code>Function</code> takes the function by value here, rather than by reference? It doesn’t take ownership of the function or anything. You might need to worry about <code>const</code> correctness here, but if you refactor the class so that it’s no longer a template—and only this function is a template—then you can use forwarding references to solve all that.</p>\n\n<pre><code>void operator()(Container& container, Function function)\n {\n // ... [snip] ...\n\n //{ std::unique_lock<std::mutex> lock(out); std::cout << \"waiting threads\" << std::endl; }\n //wait for each thread to complete\n if (true)\n {\n std::unique_lock<std::mutex> lock(main_mutex);\n main_conditional.wait(lock, [&]()\n {\n //{ std::unique_lock<std::mutex> lock(out); std::cout << returned_count << \" threads returned\" << std::endl; }\n return returned_count == threads_count;\n });\n }\n //{ std::unique_lock<std::mutex> lock(out); std::cout << \"all threads returned (possibly, maybe)(?)\" << std::endl; }\n //reset the counter for next call\n returned_count = 0;\n }\n</code></pre>\n\n<p>This seems like a brittle and dangerous way to keep track of which threads are done. Consider what would happen if one thread failed to increment <code>returned_count</code>. For example, what if <code>function</code> threw an exception in one of the threads? Boom. Deadlock. <code>main_conditional</code> never gets its notification, and even if it does spuriously wake up, your wait condition will never succeed.</p>\n\n<p>A first step to improving this could be to use a RAII object in <code>thread_method()</code> to <em>ensure</em> the count gets incremented even in the face of an exception (and then either ignore or propagate the exception somehow).</p>\n\n<p>But if that’s starting to sound a little over-engineered… well, yeah. You have a bunch of worker threads all acquiring a lock on that main mutex and <em>then</em> the main thread being notified, waking up, having to wait for that notifying worker to release the mutex before it can lock the mutex itself to check the variable and make sure it wasn’t spuriously woken. The only reason you need all that mutex locking is to protect <code>returned_count</code>.</p>\n\n<p>Instead, consider making <code>returned_count</code> an <code>atomic<size_t></code>.</p>\n\n<p>That won’t make much difference in <code>operator()()</code> (or will it! more on that in a moment!), but it will make a <em>huge</em> difference in <code>thread_method()</code>. That entire final <code>if</code> block just… goes away. It gets replaced with <code>++returned_count;</code>. Yes. Just that.</p>\n\n<p>Or even better, it gets replaced with… nothing. Because you would have that RAII object that automatically increments <code>returned_count</code> at the end of the loop.</p>\n\n<p>But this still isn’t great, for the next reason:</p>\n\n<pre><code>void thread_method(size_t index)\n {\n // ... [snip] ...\n\n while (true)\n {\n if (true) //just to get the ide to indent the block\n {\n std::unique_lock<std::mutex> lock(mutex);\n //go sleep until there's something to actually do\n conditional.wait(lock); \n }\n</code></pre>\n\n<p>This is the second major bug in this code.</p>\n\n<p>The problem here is that condition variables might spuriously wake up without being notified. Your code currently has no way to protect against this. <code>thread_func()</code> has no way to tell whether that condition variable was legitimately notified because there’s work to do or not. So the cv triggers, sees <code>running</code> is <code>true</code> (because the destructor hasn’t been called yet), and cheerfully charges into that loop to run <code>function</code> over <code>container</code>… except those are both null pointers. Or maybe they’re not; maybe they’re left over from the last call. Either way, boom.</p>\n\n<p>So the first thing you might think to do to fix this is add a ”theres_work_to_do” flag for every thread. Now your <code>thread_method()</code> might look something like this:</p>\n\n<pre><code>void thread_method(size_t index)\n {\n // ... [snip] ...\n\n while (true)\n {\n if (true)\n {\n std::unique_lock<std::mutex> lock(mutex);\n conditional.wait(lock, [&] { return !running or theres_work_to_do; });\n }\n</code></pre>\n\n<p>But now ask yourself… is it really necessary for every thread to have its own “there’s work to do” flag? That requires the main thread locking each worker thread’s mutex to set the flag. (Yes, that’s only if the flag isn’t atomic, but we’ll get to that.) Seems like all the threads are always going to be started in lockstep anyway, so you only need a single flag for them all. And if they’re all sharing a single flag, they don’t need individual mutexes (and indeed, can’t work that way, because you’d have different mutexes guarding the setting and reading of the flag). You’d only need a single mutex—the main mutex, for example—to guard that one flag… and not even that if the flag is atomic.</p>\n\n<p>Except now there’s another bug. What if the worker thread wakes up, sees “there’s work to do”, does the work, then goes back to sleep… then wakes up again and sees “there’s work to do”. Now, here’s the riddle: is this new work to do, or is this flag still set from the last job, and the main thread just hasn’t had a chance to unset it yet?</p>\n\n<p>So you <em>do</em> need per-thread flags. But perhaps there’s a way to eat our cake and have it, too.</p>\n\n<p>What if each worker thread had a single associated atomic <code>bool</code>, set to <code>false</code> by default. When the main thread has set up work for it to do, it sets that <code>bool</code> to <code>true</code>. Then it waits for the flag to change. The worker thread, meanwhile, sees the flag is <code>true</code>, so it does its task, then sets the flag to <code>false</code> again. The next time it sees the flag is <code>true</code> it knows for sure there’s new work to do.</p>\n\n<p>So you can use a single flag to signal when there is work to do, and when that work is done. That solves the problem of how the worker thread knows it hasn’t been spuriously woken, and you no longer need <code>returned_count</code>.</p>\n\n<p>And also, now you no longer need a mutex and cv for each worker thread. Nor do you need the main mutex and cv.</p>\n\n<p>It might look something like this:</p>\n\n<pre><code>// private inner class:\nstruct pool_thread_t\n{\n std::thread thread;\n std::atomic<bool> flag;\n // ...\n};\n\nstd::vector<pool_thread_t> threads;\n\nvoid operator()(Container&& container, Function&& function)\n {\n // Set up the data for the worker threads, then:\n for (auto&& thread : threads)\n thread.flag = true;\n\n // Now just wait for all the flags to go false again:\n for (auto&& thread : threads)\n {\n if (thread.flag)\n std::this_thread::yield();\n }\n\n // That's it.\n }\n\nvoid thread_method(std::size_t index)\n {\n // Set up this thread's data.\n\n while (running)\n {\n if (flag)\n {\n // Use whatever RAII method you like for this\n on_scope_exit([&flag] { flag = false; });\n\n // do the work\n\n // And that's it.\n }\n else\n std::this_thread::yield();\n }\n }\n</code></pre>\n\n<p>And to make this even better, there are a few tools you can use.</p>\n\n<p>First, you can explicitly specify the memory sync ordering. Won’t make much difference on x64… might make a huge difference on ARM.</p>\n\n<p>Second, starting in C++20, you can actually use <code>atomic_flag</code> for this, and you can wait on the flag just like a condition variable:</p>\n\n<pre><code>// private inner class:\nstruct pool_thread_t\n{\n std::thread thread;\n std::atomic_flag flag;\n // ...\n};\n\nstd::vector<pool_thread_t> threads;\n\nvoid operator()(Container&& container, Function&& function)\n {\n // Set up the data for the worker threads, then:\n for (auto&& thread : threads)\n thread.flag.test_and_set(memory_order::release);\n\n // Now just wait for all the flags to go false again:\n for (auto&& thread : threads)\n thread.flag.wait(true, memory_order::acquire);\n\n // That's it.\n }\n\nvoid thread_method(std::size_t index)\n {\n // Set up this thread's data.\n\n while (true)\n {\n flag.wait(false, memory_order::acquire);\n if (!running) // this could also be an atomic flag, with memory ordering\n break;\n\n // Use whatever RAII method you like for this\n on_scope_exit([&flag] { flag.clear(memory_order::release); });\n\n // do the work\n\n // And that's it.\n }\n }\n</code></pre>\n\n<p>Not a single mutex in sight, let alone condition variables.</p>\n\n<h1>Summary</h1>\n\n<p>You have two-and-a-half major bugs in the current code that I can see:</p>\n\n<ol>\n<li>If an exception is thrown while constructing the worker threads, all hell can break loose.</li>\n<li>You don’t take into account that condition variables can awaken spuriously in your worker thread function, which means it may go ahead and try to do work when there isn’t any. This could either result in dereferencing null pointers, or absolute chaos.</li>\n</ol>\n\n<p>The “half” bug is because you don’t account for an exception being thrown <em>in</em> a worker thread, which would result in your completed count being off, and a deadlock. This is only a half-bug, because it probably doesn’t matter because <code>std::terminate()</code> is going to be called anyway… assuming the program isn’t deadlocked in a way that prevents that, of course.</p>\n\n<p>You also have a lot of performance issues due to the overuse of mutexes and condition variables. Atomics can really save your bacon here. <em>Especially</em> C++20 atomics, which can wait like condition variables for even better performance. (But even a lazy spinlock in userspace would probably be a <em>LOT</em> more efficient than all those mutexes locking and unlocking.)</p>\n\n<p>The biggest problem here is the design, which is clunky and difficult to use because the container and function types are baked into the class itself. By using type-erased function pointers—like <code>std::function<void()></code>—you can eliminate the need to template on the container/function except in <code>operator()</code>… where they can be deduced from the function arguments.</p>\n\n<p>It would also probably be wise to break up this class into smaller components. It does too much. It manages a thread pool <em>and</em> handles task scheduling. These are things that could probably better be handled by more specialized classes.</p>\n\n<p>Also, I should point out that there’s really no technical reason to limit yourself to only handling containers that have a subscript operator. In the example I gave with the lambda <code>lambda</code>, it uses a <code>for</code> loop of indices from <code>from</code> to <code>to</code>… but it could just as easily use a pair of iterators.</p>\n\n<p>You could even support containers or ranges that don’t know their size by switching to a task queue design. For example, rather than breaking the job up into chunks then sending those chunks out to each worker thread, instead you could do something roughly like:</p>\n\n<pre><code>void operator()(Container&& container, Function&& function)\n {\n using std::begin;\n using std::end;\n\n auto first = begin(container);\n auto const last = end(container);\n\n while (first != last)\n {\n auto available_thread = std::find_if(begin(threads), end(threads), [](auto&& thread) { return thread.flag == false; });\n if (available_thread != end(threads))\n {\n auto task = [&function, first] { function(*first); };\n\n available_thread->task = task;\n available_thread->flag = true;\n\n ++first;\n }\n else\n {\n // All worker threads busy, so wait.\n std::this_thread::yield();\n }\n }\n\n for (auto&& thread : threads)\n thread.flag.wait(true);\n}\n</code></pre>\n\n<p>Perhaps you could even use <code>if constexpr</code> to get the best of <em>both</em> worlds, by switching on the container’s iterator type. For random-access iterators, chunk up the tasks; otherwise, send them one-by-one.</p>\n\n<p>Hope this helps!</p>\n\n<h1>Extension: Questions and answers</h1>\n\n<blockquote>\n <p>i didn't want the vector to eventually reserve more space then required, since i already know beforehand that it will never ever grow.</p>\n</blockquote>\n\n<p>Rather than just <em>using</em> your standard library, you’re trying to outsmart it. That’s not a productive way to program. The standard library should be your friend and partner, not an antagonist you have to work around and undermine. Oh, for sure, always <em>verify</em> that your standard library is working the way you want it to… but the rule is trust then verify, which starts with ”trust”.</p>\n\n<p>Consider: Why would the developer of your standard library write their vector class to waste memory? What would be the point? If you specify that the vector holds N elements… why would the vector allocate for N+X elements? Why wouldn’t it just allocate what you told it you wanted?</p>\n\n<p>I am not aware of any standard vector implementation that won’t just allocate what you ask for. (Granted, I haven’t used <em>ALL</em> the stdlib implementations out there, but I’ve used libstdc++, libc++, Rogue Wave’s libs, Dinkumware’s, STLPort, the original HP STL, and a couple others.) But, heck, don’t take my word for it. Verify. Rather than assuming your standard library won’t work for you and trying to hack around it… check it to see if it works:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n\nauto main() -> int\n{\n // Let's try just constructing with the size we want.\n auto v1 = std::vector<int>(17);\n\n // Now let's try just reserving the size we want.\n auto v2 = std::vector<int>{};\n v2.reserve(27);\n\n // Now let's try reserving the size we want, then filling it.\n auto v3 = std::vector<int>{};\n v3.reserve(13);\n for (auto i = 0; i < 13; ++i)\n v3.push_back(i);\n\n // Now let's try neither constructing at size or reserving,\n // and instead expanding the vector as we fill it.\n auto v4 = std::vector<int>{};\n for (auto i = 0; i < 23; ++i)\n v4.push_back(i);\n\n std::cout << \"v1.size = \" << v1.size() << '\\n';\n std::cout << \"v1.capacity = \" << v1.capacity() << '\\n';\n std::cout << \"v2.size = \" << v2.size() << '\\n';\n std::cout << \"v2.capacity = \" << v2.capacity() << '\\n';\n std::cout << \"v3.size = \" << v3.size() << '\\n';\n std::cout << \"v3.capacity = \" << v3.capacity() << '\\n';\n std::cout << \"v4.size = \" << v4.size() << '\\n';\n std::cout << \"v4.capacity = \" << v4.capacity() << '\\n';\n}\n</code></pre>\n\n<p>I just tried that myself, and for bother libstdc++ and libc++, I got the same results:</p>\n\n<pre><code>v1.size = 17\nv1.capacity = 17\nv2.size = 0\nv2.capacity = 27\nv3.size = 13\nv3.capacity = 13\nv4.size = 23\nv4.capacity = 32\n</code></pre>\n\n<p>As you can see, the capacity is always exactly what you ask for… <em>except</em> in the case where the vector has to <em>grow</em>. (Bonus: try adding another element to either <code>v1</code> or <code>v3</code>. Betcha the capacity is now double the original capacity. This is from memory, but I’m pretty sure that for both libstdc++ and libc++, the growth factor is 2—the vector doubles in size when it has to grow. For Dinkumware, I think it’s 1.5.)</p>\n\n<p>And, really, if you think about it, if a stdlib implementation’s vector <em>didn’t</em> just allocate the size you asked for, it probably has a damn good reason for that. Otherwise, why not just use the information you gave it? For example, maybe the allocator simply <em>can’t</em> allocate your exact size, and thus gives you the next size up. (In which case, the exact same thing would be happening for your manually allocated arrays… you just wouldn’t know it.)</p>\n\n<p>The moral of the story here is that you jumped through a lot of hoops and wrote a lot of code to avoid a problem that doesn’t exist. For every one of those <code>unique_ptr</code> arrays, you know the size at construction time… which means a vector could just as easily be used, and it would have exactly the same size. And of course, the more code you write, the more the chance of error, the more the maintenance burden, and the more testing you have to do.</p>\n\n<blockquote>\n <p>i made multiple arrays of a single data rather than structs because i'm mostly iterating on each array individually, so having all contiguous data should improve caching compared to having to skip over data i don't care in a specific loop for each step.</p>\n \n <p>At least it makes sense to me to split threads, from-to, and condition_variable-mutex (i agree these two make sense toghether since they're used in the same loops consecutively). But i don't agree in putting from-to in the same contiguous memory as cv-mutex and threads.</p>\n</blockquote>\n\n<p>“Should improve caching” hm? Have you actually measured? Because this sure sounds like premature optimization to me.</p>\n\n<p>Let’s get some numeric perspective. Let’s start with size. The type I suggested is 112 bytes using libc++ (and probably libstdc++ too, since most of the types are pretty much dictated by the kernel (or userspace analogues like <code>futex</code>)):</p>\n\n<ul>\n<li><code>std::thread</code>: 8 bytes (1 <code>pthread_t</code>, which is a <code>unsigned long</code>)</li>\n<li><code>std::condition_variable</code>: 48 bytes (set by kernel)</li>\n<li><code>std::mutex</code>: 40 bytes (set by kernel)</li>\n<li><code>std::size_t</code>: 8 bytes</li>\n</ul>\n\n<p>Sound pretty big, right? And sure, it’s a hell of a lot bigger than the usual size of a cache line these days, which is 64 bytes. But here’s where perspective comes into play. When people fret over packing data into cache lines, they’re usually talking about arrays of <em>thousands</em> or <em>tens of thousands</em> of values. What exactly are we talking about here?</p>\n\n<p>Well, realistically, it doesn’t really make a lot of sense to have more threads in the pool than there are hardware threads… anymore than that, and you’ve pretty much lost any gains you get from concurrency. Okay, so let’s assume you have an 8 kiB L1 cache (which is tiny these days; I’d expect at least 32 kiB). How many of those structs can fit in L1 cache? <em>Over 72</em>. So even with a tiny 8 kiB cache you can have 72 freakin’ threads in your pool, and still not have to worry about a cache miss. With a more average 32 kiB L1 cache, you can have <em>290</em>.</p>\n\n<p>I don’t think cache misses are going to be a problem.</p>\n\n<p>But let’s approach this from another angle. Let’s pretend cache misses are going to happen every single access. Is this actually a problem?</p>\n\n<p>Well, let’s look at all the places you iterate through the various arrays:</p>\n\n<ol>\n<li>In the constructor:\n\n<ul>\n<li>every one of the init list constructors has to iterate through each of the arrays, so that’s 4 different iterations</li>\n<li>in the body itself, a second iteration over the threads to construct them</li>\n</ul></li>\n<li>In the destructor:\n\n<ul>\n<li>once over <em>both</em> the cv and mutex arrays, locking and notifying</li>\n<li>once over the thread array to join</li>\n</ul></li>\n<li>In <code>operator()</code>:\n\n<ul>\n<li>once over <em>both</em> the indices <em>and</em> the cv array, setting the former and notifying the latter</li>\n</ul></li>\n</ol>\n\n<p>And that’s it.</p>\n\n<p>Now, we can pretty much ignore the constructor and destructor, because you don’t really need to worry about optimizing those. (Though, if you insist on considering them, let me point out that you’re not gaining anything in the constructor by iterating over <em>four</em> arrays sequentially, compared to iterating over a single one one time. But in any case, any cache miss costs are going to be <em>dwarfed</em> by the allocations and the costs of creating all those threads, even on platforms where threads are pretty cheap.) So the key loop you’d care about is the one in <code>operator()</code>.</p>\n\n<p>But look at what that loop is doing! Not only is it doing <em>two</em> indirections into <em>two</em> different arrays (so much for the gains you won by splitting the arrays up—you’re just using them together anyway)… you… you’re also… <em>notify on a condition variable</em>!!! In what is supposedly a hot loop!</p>\n\n<p>And not only that! Even if that loop were godawfully slow (which it isn’t really, for what it does)… <em>it doesn’t matter</em>. Because what’s going to happen next is <em>a series of context switches</em> as the threads that will actually do the work get their turns. So even if you get a cache miss for every access (which is absurd), which is each iteration of that loop, which is once per thread, then each thread still has to context switch (and then go through all the hoopla of locking the mutex, checking the condition variable, reading the task data, etc.). A rough estimate of the cost of an L1 cache miss is ~10 ns. A rough estimate of the cost of a thread context switch: ~10 <em>ms</em>. That’s <em>three orders of magnitude bigger</em>… and that’s a <em>massively</em> conservative estimate!</p>\n\n<p>In other words, all those code acrobatics you went through to in order to avoid cache misses ultimately turn out to give you a performance gain of… not 10%… not 1%… but <em>in the most generous estimate I can muster</em>, only ~0.1%. And the real-life gain is probably going to be much, much less. That’s basically thermal noise at that point; you can’t even tell the difference between cache misses and <em>hardware interrupts</em> at that point.</p>\n\n<p>So, realistically speaking, you are gaining pretty much literally <em>nothing</em> by making your code more convoluted, more difficult to reason about, and more difficult to maintain and debug.</p>\n\n<p>Don’t just read stuff on the internet and blindly apply it. There <em>are</em> situations where a struct-of-arrays design can be <em>much</em> faster than an array-of-structs design—I’ve seen documented cases of 50× improvement. But those are cases where you’re dealing with relatively <em>huge</em> amounts of data… not like a dozen elements, which is roughly the regime you’re dealing with here, but like a hundred thousand or a <em>million</em> elements. You ain’t makin’ a hundred thousand or a million threads, I assure you… and if you are… dude… cache misses are the least of your concerns. Also, those are cases where each operation is very short and quick, like a simple arithmetic calculation. They ain’t doing mutex locks, condition variable notifications, and thread context switches.</p>\n\n<p>Take the time to understand your problem to really grok the context before hacking up your code into spaghetti out of fear of phantom performance traps. And, most importantly, profile, profile, profile. Profile first; <em>then</em> (maybe) optimize.</p>\n\n<blockquote>\n <p>About the bool not being atomic, you wrote \"This should be an atomic. Why? Because it is both read and set without any mutexes guarding it\". But how? The boolean is only set when all the threads are sleeping, or am i missing something?</p>\n</blockquote>\n\n<p>I think you have some confusion about how data is shared across threads. Whether a thread is active or not is completely irrelevant. The problem is that when you’re dealing with multiple cores, you’re often dealing with completely different, completely independent “views” of global memory. And those views are not necessarily deterministic with respect to each other.</p>\n\n<p>(Also, I think you’re still labouring under the misconception that if you <code>wait()</code> on a condition variable, that means the thread has obediently stopped and is just sitting, waiting for you to give it the green light to go again. When a thread is <code>wait()</code>ing, it’s still effectively waking up over and over and over—it keeps checking the condition then (hopefully) if the condition hasn’t been set, yielding then going back to step 1 (but not always; there are spurious wake-ups).)</p>\n\n<p>The most important thing to understand with concurrent programming is that not only do different threads see different views of shared memory, they don’t even see consistent “snapshots”. In other words, you have to stop imagining your program’s state as a single, consistent, universal truth, with different threads just seeing it at different points in time. Two threads may see completely inconsistent “truths”, each of which is impossible from the other thread’s point of view.</p>\n\n<p>For example, say the main thread is running on core 1. Let’s ignore the mutexes for a moment; we’ll get back to them. The destructor gets called, and <code>running</code> gets set to <code>false</code>, and then thread 2 gets notified. But thread 2 is on core 2, and it doesn’t “see” the change to <code>running</code>—it has its own L1 cache, completely distinct from core 1’s L1 cache (L1 cache is usually per-core; L2 can be per-core or shared). So thread 2 gets woken up… but it doesn’t yet see that <code>running</code> is false.</p>\n\n<p>So far this all still makes sense in a deterministic world, but here’s where it starts to get wacky: the compiler and the CPU are <em>both</em> allowed to reorder memory reads/writes. So the main thread may decide to set <code>running</code> to <code>false</code> <em>AFTER</em> it sends the notification. Because why not? It’s a perfectly legal thing for the optimizer or CPU to do, because it makes no difference at all to the semantics of the code in the main thread. The main thread doesn’t care whether <code>running = false</code> “happens-before” <code>conditionals.get()[i].notify_one()</code> or not, right?</p>\n\n<p>Think about it: ignoring the existence of other threads (pretend the mutex lock and cv notify are no-ops), what is the difference between:</p>\n\n<pre><code>running = false;\nfor (size_t i = 0; i < threads_count; i++)\n {\n // effectively no-op: std::unique_lock<std::mutex> lock(mutexes.get()[i]);\n // effectively no-op: conditionals.get()[i].notify_one();\n }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>for (size_t i = 0; i < threads_count; i++)\n {\n // effectively no-op: std::unique_lock<std::mutex> lock(mutexes.get()[i]);\n // effectively no-op: conditionals.get()[i].notify_one();\n }\nrunning = false;\n</code></pre>\n\n<p>(Note that by “effective no-op”, I don’t mean that it doesn’t actually <em>do</em> anything. I just mean that it doesn’t do anything <em>that depends on <code>running</code></em>. The compiler can see that neither of those statements reads (or writes) the value of <code>running</code>, so from the point of view of the value of <code>running</code> they don’t matter.)</p>\n\n<p>There’s no difference, right? There is no indication that the stuff in the <code>for</code> loop has any dependency on <code>running</code> being set to false. Unless the compiler/CPU knows that the stuff in the loop has a dependency on <code>running</code> being set to <code>false</code>, it can’t know that it has to make sure the write to <code>running</code> is done before the loop.</p>\n\n<p>At the same time, thread 2 doesn’t care whether <code>if (!running) { break; }</code> “happens-before” <code>conditional.wait(lock)</code>. Without knowing that the value of <code>running</code> may magically change at any time, there’s no reason that:</p>\n\n<pre><code>while (true)\n {\n if (true)\n {\n // effectively no-op: std::unique_lock<std::mutex> lock(mutex);\n // effectively no-op: conditional.wait(lock); \n }\n if (!running) { break; }\n</code></pre>\n\n<p>couldn’t be rewritten as:</p>\n\n<pre><code>while (running)\n {\n if (true)\n {\n // effectively no-op: std::unique_lock<std::mutex> lock(mutex);\n // effectively no-op: conditional.wait(lock); \n }\n</code></pre>\n\n<p><em>You</em> know that the value of <code>running</code> might change at any time… but the compiler and CPU don’t know that. (This is why, before C++11, people used to use <code>volatile</code> for rudimentary synchronization. <code>volatile</code> would prevent the compiler from making this kind of assumption.)</p>\n\n<p>And note: none of this has anything to do with whether the thread was active or not at the time of <code>running</code> being set, or the cv being notified.</p>\n\n<p>Okay, but there are mutexes involved, and that does change things. Why? Because <em>locking</em> a mutex is effectively an “acquire” event, and <em>releasing</em> a mutex is a “release” event.</p>\n\n<p>What this means is that if you wrapped the reading and writing of <code>running</code> in a mutex, there would be no problem:</p>\n\n<pre><code>// Thread 1:\n{\n auto lock = std::unique_lock(mutex);\n running = false;\n}\n// The mutex being unlocked triggers a \"release\", meaning that\n// everything that happened before the unlocking must be visible as\n// happening before the unlocking.\n// So the next thread that locks the mutex will EITHER see running set\n// properly to true OR properly to false... and not some weird hybrid of\n// the two (if such a thing is possible on a platform).\nconditional.notify_one();\n\n// Thread 2:\n{\n auto lock = std::unique_lock(mutex):\n conditional.wait(lock);\n // wait() relocks the mutex after getting its notification. That\n // locking triggers an “acquire”, which synchronizes with thread 1.\n // So this thread will either see true or false, not\n // half-set-to-false (again, if such a thing is possible).\n\n // Note that this is guarded by the mutex. If it were not (as is the\n // case in your actual code), then what could happen is thread 1\n // could PARTIALLY set its value (or, really, ANYTHING could happen;\n // it would be a data race, which is UB, which means anything\n // goes).\n // But, as I said, it will PROBABLY still \"work\" on all real-life\n // systems.\n if (not running) break;\n}\n</code></pre>\n\n<p>Now, in your actual code, you’ve actually got something peculiar going on that I’m not sure about, because you do the notify while still holding the mutex locked. In theory, this would mean that the worker thread would get the notification, and try to lock the mutex, and block… then the main thread releases the mutex—which triggers the “release” operation—then the worker would be able to lock the mutex—triggering an “acquire”—and all is well. <em>BUT</em>! I know that some implementations avoid that extra block, and simply sorta… “transfer” the lock over. But does that mean the “release” and “acquire” happen? I’m not sure.</p>\n\n<p>In any case, the bottom line is that the rule is: if your data is shared across threads, then it must be guarded by acquire-release barriers of some sort: a mutex works, and so do atomics. Fail to do this, and you’ve got a data race… as you do in your code. A data race is always UB, but that doesn’t mean it actually always manifests, or that it matters when it does. As a practical matter, I think that even if it does manifest in your code’s case, it will still “work”. But it’s still technically wrong.</p>\n\n<p><code>running</code> is mutable shared data. Thus it should either always be read-written while locked by (the same) mutex <em>OR</em> it should be atomic (or otherwise synchronized). Personally, I prefer atomics where possible, especially for tiny bits of data like <code>bool</code>s.</p>\n\n<blockquote>\n <p>But don't i still need multiple mutexes for the conditional variable in any case?</p>\n</blockquote>\n\n<p>I don’t see why, honestly. Conceptually speaking, your worker threads aren’t really independent. They are <em>ALWAYS</em> started all together in lockstep, and <em>ALWAYS</em> finish all together in lockstep (all within a single function: <code>operator()</code>). There’s really only one set of global data you’re sharing—the task data. I don’t see why you need a dozen mutexes for a single block of data. It’s set up once at the start of <code>operator()</code> (and technically it doesn’t need a mutex for that; it just needs a fence… but a mutex is the easiest way to handle that), and then each thread just needs to read it before diving into their task.</p>\n\n<p>Or think of it another way: the point of a mutex is to protect data from being written to by multiple writers, or written to while it’s being read. Okay, so what data is each per-thread mutex guarding? Just the task-specific data (the to/from indices, and the pointers to the function and container). The worker thread doesn’t write to that data, it only reads it. Who else might be writing to that data while the worker thread is reading it? Well, nobody. The data is only changed while all the worker threads are sleeping, and then when they’re running they’re all only reading it. There’s no write contention. You don’t need to guard data that’s only being read (you just need to make sure it’s visible—that is, you need to make sure after you write it, you publish those writes to every thread that will want to read it, but once it’s visible, it doesn’t need to be guarded with a lock).</p>\n\n<p>By the same logic, you don’t really need a dozen condition variables. The only thing you’re using them for is to wake up the threads. Okay, fine, but again, this isn’t <em>really</em> a case of a dozen distinct events. There’s really just <em>one</em> event: a single wake-up of all the worker threads together. What you really want is for a single notification to wake up all the worker threads at once. You could do that with a single condition variable and <code>notify_all()</code>.</p>\n\n<p>Incidentally, I didn’t notice before that both <code>function</code> and <code>container</code> are <em>also</em> global data that isn’t protected. Unlike the case with <code>running</code>… yeah, you’re playing with fire there—this is <em>definitely</em> a bug. You have nothing guaranteeing that <em>either</em> of those writes are ordered before the call to <code>notify_one()</code> for each thread. This is a clear and definite data race. So are the writes to the indices. <em>ALL</em> of these things should be atomics, or guarded by mutexes. Or, at the <em>very</em> least, fences.</p>\n\n<p>You might be able to get away with something like this (very rough and untested code that I honestly really haven't sat down and really reasoned through):</p>\n\n<pre><code>// private inner struct\nstruct pool_thread_t\n{\n std::thread thread;\n std::size_t from;\n std::size_t to;\n std::function<void(std::size_t, std::size_t)> task;\n std::atomic<bool> busy;\n};\n\nstd::vector<pool_thread_t> _threads;\nbool _shutdown = false;\n\n~destructor()\n{\n _shutdown = true;\n\n // Fence makes sure the write above is visible when the atomic\n // writes that follow are visible.\n std::atomic_thread_fence(std::memory_order::release);\n for (auto&& thread : _threads)\n {\n thread.busy.store(true, std::memory_order::relaxed);\n thread.busy.notify_one();\n }\n\n for (auto&& thread : _threads)\n thread.thread.join();\n}\n\ntemplate <typename Container, typename Function>\nauto operator()(Container&& container, Function&& function)\n{\n using std::size;\n\n auto const total_tasks = size(container);\n auto const task_quantum = (total_tasks / _threads.size())\n + bool(total_tasks % _threads.size());\n\n // Set up task data.\n auto task = [&container, &function] (std::size_t from, std::size_t to)\n {\n for (auto i = from; i < to; ++i)\n function(container[i]);\n };\n\n for (auto i = decltype(_threads.size()){}; i < _threads.size(); ++i)\n {\n _threads[i].from = i * task_quantum;\n _threads[i].to = std::min(_threads[i].from + (task_quantum - 1), total_tasks);\n _threads[i].task = task;\n }\n\n // Fence to ensure everything above is visible when the following\n // atomic stores are visible.\n std::atomic_thread_fence(std::memory_order::release);\n for (auto&& thread : _threads)\n {\n thread.busy.store(true, std::memory_order::relaxed);\n thread.busy.notify_one();\n }\n\n // Now just wait for everything to be done.\n for (auto&& thread : _threads)\n thread.busy.wait(true, std::memory_order::acquire);\n}\n\nauto thread_method(std::size_t index)\n{\n // You know, you could just pass a reference to the thread data\n // directly, rather than an index.\n auto&& thread_data = _threads[index];\n\n while (true)\n {\n // Fence ensures that once we read the busy flag is true,\n // we also see every other write done before.\n thread_data.busy.wait(false, std::memory_order::relaxed);\n std::atomic_thread_fence(std::memory_order_acquire);\n\n // Were we woken up because it's shutdown time?\n if (_shutdown)\n return;\n\n // Do the task.\n try\n {\n thread_data.task(thread_data.from, thread_data.to);\n }\n catch (...)\n {\n // I guess just ignore errors.\n }\n\n // Notify that we're not longer busy.\n thread_data.busy.store(false, std::memory_order::release);\n thread_data.busy.notify_one();\n }\n}\n</code></pre>\n\n<p>In C++17 you’re going to need condition variables (and, by extension, mutexes) because atomics can’t wait or notify. But you probably only need a single condition variable to start all the workers running; it’s probably overkill to also use notification for when the workers are done. It’s probably good enough for the main thread to just check “done” flags from all the worker threads and yield its time slice if they’re still busy, because when the workers finish and go to sleep, the schedule will probably switch back to the main thread anyway, so it won’t be wasting that much time.</p>\n\n<p>Or, perhaps a better solution before C++20 is to use promises and futures. You'd just set up the promises for each worker thread, save their futures, then trigger them all to start (using a cv, for example), then just wait on them all. As a bonus, using this technique you could also easily handle errors in the worker threads.</p>\n\n<p>But yeah, the general takeaway is that if your data is shared between threads, it must be synchronized somehow. Either protect it with a mutex, use atomics, or do something else (fences, futures, whatever). Don’t just rely on assumptions about if/when changes to data values become visible across threads. That’s just asking to be burned with data races.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:26:51.383",
"Id": "474629",
"Score": "0",
"body": "0 - About threads stuff being public, it was an error on my side, made it public for early tests and forgot to turn it private later. It should be private.\n\n1 - I agree on the interface, to be fair i wasn't sure about how to simplify it. I'll implement your lambda design, it looks a lot cleaner indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:27:10.067",
"Id": "474630",
"Score": "0",
"body": "2 - About the unique ptr to multiple arrays rather than a single vector of structs:\ni didn't want the vector to eventually reserve more space then required, since i already know beforehand that it will never ever grow.\ni made multiple arrays of a single data rather than structs because i'm mostly iterating on each array individually, so having all contiguous data should improve caching compared to having to skip over data i don't care in a specific loop for each step."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:27:12.833",
"Id": "474631",
"Score": "0",
"body": "At least it makes sense to me to split threads, from-to, and condition_variable-mutex (i agree these two make sense toghether since they're used in the same loops consecutively). But i don't agree in putting from-to in the same contiguous memory as cv-mutex and threads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:27:24.697",
"Id": "474632",
"Score": "0",
"body": "3 - About the bool not being atomic, you wrote \"This should be an atomic<bool>. Why? Because it is both read and set without any mutexes guarding it\". But how? The boolean is only set when all the threads are sleeping, or am i missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:27:52.657",
"Id": "474633",
"Score": "0",
"body": "4 - \"Imagine threads_count is 8. Your loop starts, 6 threads get constructed just fine… but thread 7 fails and throws an exception. Now what happens?\"\nThanks, i didn't consider that like at all. Ty for the in depth explanation.\n\n5 - \"Now, here’s the riddle: is this new work to do, or is this flag still set from the last job, and the main thread just hasn’t had a chance to unset it yet?\" \nSomething like this had my brain hurt the most while writing it.\nBut don't i still need multiple mutexes for the conditional variable in any case?\n\nThanks again for all the insight, was really helpful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:08:44.020",
"Id": "474748",
"Score": "1",
"body": "Your questions are complicated! That means they require some in-depth answers, so I'll extend the answer above."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T07:36:09.157",
"Id": "241860",
"ParentId": "241776",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241860",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:02:08.067",
"Id": "241776",
"Score": "3",
"Tags": [
"c++",
"multithreading"
],
"Title": "Multithreaded for-each for index based bata structures"
}
|
241776
|
<p>The code reads the specified number of bytes from a specified offset in a file, I have handled the partial reads and bytes > buf_size conditions. Could anyone review the code? and say whether the handling strategy is good. The constraint I am not allowed to use system calls other than open, close, read, write,Thanks a ton.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<error.h>
#include<errno.h>
#include<fcntl.h>
#define buf_size 5
int main(int argc, char *argv[])
{
int bytes;
int offset;
int fd;
char *file;
char buf[buf_size];
int rlen = 0;
int len = 0;
int i = 0;
if (argc != 4)
error(1, 0, "Too many or less than the number of arguments");
file = argv[1];
offset = atoi(argv[2]);
bytes = atoi(argv[3]);
fd = open(file, O_RDONLY);
printf("The values of the file descriptor is : %d\n", fd);
if (fd == -1)
error(1, errno, "Error while opening the file\n");
while (1) {
rlen = read(fd, buf, offset);
if (rlen == -1)
error(1, errno, "Error in reading the file\n");
len = len + rlen;
if(len == offset) {
len = 0;
while (1) {
rlen = read(fd, buf, bytes);
if (rlen == -1)
error(1, errno, "Error in reading the file\n");
if (rlen == 0)
return 0;
len = len + rlen;
for (i = 0; i < rlen; i++)
putchar(buf[i]);
if (len == bytes) {
printf("\nSuccess\n");
return 0;
}
bytes = bytes - rlen;
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>Fails with large <code>offset, bytes</code></strong></p>\n\n<p><code>read(fd, buf, offset);</code> reads out of <code>buf[]</code> bounds when <code>offset > buf_size</code>. Same for <code>bytes</code>. This should be tested.</p>\n\n<p>Unclear why <code>buf[buf_size]</code> is so small (5). How about 4096 or 1 Meg?</p>\n\n<p><strong>Handle large offset</strong></p>\n\n<p>I'd expect code to handle offsets far larger than the <code>sizeof buf</code>. Looping on <code>read(fd, buf, offset);</code> if needed.</p>\n\n<p><strong><code>int</code> math</strong></p>\n\n<p>Files sizes can well exceed <code>INT_MAX</code>. For <code>offset, bytes</code>, I'd use <code>long long</code>.</p>\n\n<p><strong>Unneeded loop</strong></p>\n\n<p>Rather than a <code>for()</code> loop <code>for (i = 0; i < rlen; i++) putchar(buf[i]);</code>, use <code>write(1, ...)</code>.</p>\n\n<p><strong>Missing <code>close()</code></strong></p>\n\n<p><strong>Function Limitations</strong></p>\n\n<p>OP has \"not allowed to use system calls other than open, close, read, write\". What about <code>error()</code>, <code>printf()</code>, <code>atoi()</code>, <code>putchar()</code> - or are those classified differently?</p>\n\n<p>With such a limit, looks like a lot of <code>includes</code>.</p>\n\n<p><strong>Algorithm flaw?</strong></p>\n\n<p>The first <code>while (1)</code> loop looks wrong. </p>\n\n<p>Either the first iteration will get the expect <code>offset</code> number of bytes and proceed to the 2nd <code>while ()</code>.</p>\n\n<p>Or </p>\n\n<p>it will read insufficient number of bytes (for reasons other than no -more bytes will ever exist) and loop again, trying to read <code>offset</code> bytes again. I'd expect that <code>offset</code> would have been reduced by the previous <code>rlen</code>. Without that reduction, <code>if(len == offset)</code> may never be satisfied as reading too many <code>offset</code> bytes is then possible.</p>\n\n<p>I'd expect 2 <code>while</code> loops that are not nested. First to read the <code>offset</code> bytes, next to read the <code>bytes</code>.</p>\n\n<p>Further this could be sub-function calls. Something like:</p>\n\n<pre><code>if (read_bytes(handle, offset, no_echo) == OK) {\n if (read_bytes(handle, bytes, echo_to_stdout) == OK) {\n success();\n }\n}\nfail();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T02:19:39.193",
"Id": "474477",
"Score": "0",
"body": "Thanks a lot, I understood them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T21:08:45.737",
"Id": "241782",
"ParentId": "241777",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241782",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:17:14.247",
"Id": "241777",
"Score": "2",
"Tags": [
"c",
"linux",
"unix"
],
"Title": "The code reads from a specified offset to the specified number of bytes in a file"
}
|
241777
|
<p>I'm trying to write up a cross-platform rust library (one, that will be used in iOS/Mac/Android dev etc.) It is based largely on concept's and code from <a href="https://github.com/mozilla/application-services/tree/master/docs/howtos" rel="nofollow noreferrer">Mozilla</a>. One of the requirements I have is to observe changes to struct properties in rust (similar to KVO in Objective-C). The following is a pretty big wall of code (I apologize for that) - being a beginner with Rust, I would appreciate any input on how to improve it. Thanks</p>
<pre><code>use {
ffi_support::{
define_string_destructor, handle_map::ConcurrentHandleMap, rust_string_to_c, ExternError,
FfiStr,
},
lazy_static::lazy_static,
std::{
collections::HashMap,
ffi::c_void,
os::raw::c_char,
sync::{
atomic::{AtomicUsize, Ordering},
RwLock,
},
},
};
define_string_destructor!(observer_destroy_string);
static ID_GEN: AtomicUsize = AtomicUsize::new(1);
/*
I'm storing the callbacks outside the object being observed (as, I would like to
generate this code using a macro, and, I don't see a way to add a property to an
object using a macro).
While, I could add a variable in the struct to store the property, I figure a
hashmap/id combination would be better than having multiple callback variables
being user defined.
*/
#[derive(Eq, PartialEq, Hash, Copy, Clone)]
struct Id(usize);
impl Id {
fn new() -> Self {
Id(ID_GEN.fetch_add(1, Ordering::SeqCst))
}
}
// Object would need to implement this trait, to have their properties observable.
trait Observable {
type KeyType;
fn observable_key(&self) -> Self::KeyType;
}
// Sample observable struct. We are going to observe changes to `name`.
pub struct Person {
id: Id,
name: String,
}
impl Person {
pub fn new(name: &str) -> Self {
Person {
id: Id::new(),
name: name.to_string(),
}
}
}
impl Observable for Person {
type KeyType = Id;
fn observable_key(&self) -> Self::KeyType {
self.id
}
}
static OBSERVER_ID_GEN: AtomicUsize = AtomicUsize::new(1);
/*
When we add a callback, we get a observer id in return. This id is to be used to
unregister a callback when we are no longer interested. Is there a good way to
handle lifetime (esp over FFI)? Is it possible for me to defensively add checks
on Person being deallocated, and an unregister call coming in later? Or, do I just
have to be extra cautious with my code?
*/
#[derive(Eq, PartialEq, Hash, Copy, Clone)]
pub struct ObserverId(usize);
impl ObserverId {
fn new() -> Self {
ObserverId(OBSERVER_ID_GEN.fetch_add(1, Ordering::SeqCst))
}
}
type NameCallbackCallbackType = Box<dyn Fn(&str, &str) + Sync + Send + 'static>;
type FfiCallbackDestructorType = Box<dyn Fn() + Sync + Send + 'static>;
/*
A wrapper to a callback, which holds an optional destructor for the callback
(useful to deallocate Swift closures that are passed in).
*/
struct NameCallback {
callback: NameCallbackCallbackType,
ffi_destructor: Option<FfiCallbackDestructorType>,
}
/*
Without these I get compile errors (around NameCallback not being safe to send
across threads).
*/
unsafe impl Send for NameCallback {}
unsafe impl Sync for NameCallback {}
impl Drop for NameCallback {
fn drop(&mut self) {
if let Some(ref ffi_destructor) = self.ffi_destructor {
ffi_destructor()
}
}
}
struct NameCallbacks(HashMap<ObserverId, NameCallback>);
impl NameCallbacks {
fn new() -> Self {
NameCallbacks(HashMap::new())
}
fn insert(&mut self, callback: NameCallback) -> ObserverId {
let observer_id = ObserverId::new();
self.0.insert(observer_id, callback);
observer_id
}
fn remove(&mut self, observer_id: ObserverId) {
self.0.remove(&observer_id);
}
}
type PersonObservableKeyType = <Person as Observable>::KeyType;
lazy_static! {
static ref OBSERVERS_OF_NAME: RwLock<HashMap<PersonObservableKeyType, NameCallbacks>> =
RwLock::new(HashMap::new());
}
impl Person {
pub fn observe_name<F>(&mut self, f: F) -> ObserverId
where
F: Fn(&str, &str) + Sync + Send + 'static,
{
let mut map = OBSERVERS_OF_NAME.write().unwrap();
let callbacks = map
.entry(self.observable_key())
.or_insert(NameCallbacks::new());
callbacks.insert(NameCallback {
callback: Box::new(f),
ffi_destructor: None,
})
}
pub fn unobserve_name(&mut self, observer_id: ObserverId) {
let mut map = OBSERVERS_OF_NAME.write().unwrap();
map.entry(self.observable_key())
.and_modify(|e| e.remove(observer_id));
}
pub fn set_name(&mut self, name: &str) {
let old_value = self.name.clone();
self.name = name.to_string();
if let Some(name_callbacks) = OBSERVERS_OF_NAME
.read()
.unwrap()
.get(&self.observable_key())
{
for (_, name_callback) in name_callbacks.0.iter() {
(name_callback.callback)(old_value.as_str(), self.name.as_str());
}
}
}
}
lazy_static! {
static ref ITEMS: ConcurrentHandleMap<Person> = ConcurrentHandleMap::new();
}
#[no_mangle]
pub extern "C" fn observer_extern_error_new() -> ExternError {
ExternError::success()
}
#[no_mangle]
pub extern "C" fn observer_person_new(name: FfiStr, err: &mut ExternError) -> u64 {
ITEMS.insert_with_output(err, || Person::new(name.as_str()))
}
#[derive(Copy, Clone)]
struct UserData(*mut c_void);
/* Similar to NameCallback, these are needed to avoid threading compile errors.
*/
unsafe impl Send for UserData {}
unsafe impl Sync for UserData {}
#[no_mangle]
pub extern "C" fn observer_person_observe_name(
h: u64,
user_data: *mut c_void,
callback: fn(*mut c_char, *mut c_char, *mut c_void),
destructor: Option<fn(*mut c_void)>,
err: &mut ExternError,
) -> u64 {
let user_data = UserData(user_data);
ITEMS.call_with_output_mut(err, h, |person| {
let mut map = OBSERVERS_OF_NAME.write().unwrap();
let callbacks = map
.entry(person.observable_key())
.or_insert(NameCallbacks::new());
callbacks
.insert(NameCallback {
callback: Box::new(move |old_value, new_value| {
callback(
rust_string_to_c(old_value),
rust_string_to_c(new_value),
user_data.0,
)
}),
ffi_destructor: {
match destructor {
Some(destructor) => Some(Box::new(move || destructor(user_data.0))),
None => None,
}
},
})
.0 as u64
})
}
#[no_mangle]
pub extern "C" fn observer_person_unobserve_name(h: u64, observer_id: u64, err: &mut ExternError) {
ITEMS.call_with_output_mut(err, h, |person| {
person.unobserve_name(ObserverId(observer_id as usize));
})
}
#[no_mangle]
pub extern "C" fn observer_person_set_name(h: u64, name: FfiStr, err: &mut ExternError) {
ITEMS.call_with_output_mut(err, h, |person| {
person.set_name(name.as_str());
})
}
#[no_mangle]
pub extern "C" fn observer_person_get_name(h: u64, err: &mut ExternError) -> *mut c_char {
ITEMS.call_with_output(err, h, |person| rust_string_to_c(person.name.clone()))
}
#[cfg(test)]
mod tests {
use {super::*, ffi_support::FfiStr, std::ffi::CString};
#[test]
fn test_callback() {
let mut person = Person::new("Bob");
static mut SET_COUNT: u64 = 0;
static mut CALLBACK1_RUN_COUNT: u64 = 0;
static mut CALLBACK2_RUN_COUNT: u64 = 0;
let observer1_id = person.observe_name(|old_value, new_value| unsafe {
match SET_COUNT {
0 => {
assert_eq!("Bob", old_value);
assert_eq!("Nancy", new_value);
}
1 => {
assert_eq!("Nancy", old_value);
assert_eq!("Frank", new_value);
}
2 => {
assert_eq!("Frank", old_value);
assert_eq!("Anthony", new_value);
}
_ => {}
}
CALLBACK1_RUN_COUNT += 1;
});
let observer2_id = person.observe_name(|old_value, new_value| unsafe {
match SET_COUNT {
0 => {
assert_eq!("Bob", old_value);
assert_eq!("Nancy", new_value);
}
1 => {
assert_eq!("Nancy", old_value);
assert_eq!("Frank", new_value);
}
2 => {
assert_eq!("Frank", old_value);
assert_eq!("Anthony", new_value);
}
_ => {}
}
CALLBACK2_RUN_COUNT += 1;
});
person.set_name("Nancy");
unsafe {
SET_COUNT += 1;
assert_eq!(1, CALLBACK1_RUN_COUNT);
assert_eq!(1, CALLBACK2_RUN_COUNT);
}
person.unobserve_name(observer1_id);
person.set_name("Frank");
unsafe {
SET_COUNT += 1;
assert_eq!(1, CALLBACK1_RUN_COUNT);
assert_eq!(2, CALLBACK2_RUN_COUNT);
}
person.unobserve_name(observer2_id);
person.set_name("Anthony");
unsafe {
SET_COUNT += 1;
assert_eq!(1, CALLBACK1_RUN_COUNT);
assert_eq!(2, CALLBACK2_RUN_COUNT);
}
}
static mut SET_COUNT: u8 = 0;
static mut CALLBACK_RUN_COUNT: u8 = 0;
lazy_static! {
static ref NAME1: CString = CString::new("Bob").unwrap();
static ref NAME2: CString = CString::new("Nancy").unwrap();
static ref NAME3: CString = CString::new("Frank").unwrap();
}
#[no_mangle]
fn observer_name_callback(old_value: *mut c_char, new_value: *mut c_char, _: *mut c_void) {
unsafe {
match SET_COUNT {
0 => {
assert!(libc::strcmp(NAME1.as_c_str().as_ptr(), old_value) == 0);
assert!(libc::strcmp(NAME2.as_c_str().as_ptr(), new_value) == 0);
}
1 => {
assert!(libc::strcmp(NAME2.as_c_str().as_ptr(), old_value) == 0);
assert!(libc::strcmp(NAME3.as_c_str().as_ptr(), new_value) == 0);
}
_ => {}
}
observer_destroy_string(old_value);
observer_destroy_string(new_value);
CALLBACK_RUN_COUNT += 1;
}
}
#[test]
fn test_c_callback() {
let mut err = ExternError::default();
let person_handle = observer_person_new(FfiStr::from_cstr(NAME1.as_c_str()), &mut err);
let observer_id = observer_person_observe_name(
person_handle,
std::ptr::null_mut(),
observer_name_callback,
None,
&mut err,
);
observer_person_set_name(person_handle, FfiStr::from_cstr(NAME2.as_c_str()), &mut err);
unsafe {
SET_COUNT += 1;
assert_eq!(1, CALLBACK_RUN_COUNT);
}
observer_person_unobserve_name(person_handle, observer_id, &mut err);
observer_person_set_name(person_handle, FfiStr::from_cstr(NAME3.as_c_str()), &mut err);
unsafe {
SET_COUNT += 1;
assert_eq!(1, CALLBACK_RUN_COUNT);
}
}
}
</code></pre>
<p>While this works, I'm particularly concerned about the following lines</p>
<pre><code>unsafe impl Send for NameCallback {}
unsafe impl Sync for NameCallback {}
</code></pre>
<p>I couldn't get the code to work without them (as I used to get compile errors about not being able to send NameCallback over threads - and, other such issues). Is there a safer way to do this? Or, would I be fine, as long as the callbacks are not called on two threads at the same time (should be unlikely in my use case I think). </p>
<p>Edit: Added comments in code to better explain intent.</p>
<p>Edit: With regards to this comment, </p>
<blockquote>
<p>When we add a callback, we get a observer id in return. This id is to be used to
unregister a callback when we are no longer interested. Is there a good way to
handle lifetime (esp over FFI)? Is it possible for me to defensively add checks
on Person being deallocated, and an unregister call coming in later? Or, do I just
have to be extra cautious with my code?</p>
</blockquote>
<p>I guess it shouldn't matter. If Person goes out of scope, the callback will not be called again. If the observer/closure is released without unregistering, it could be an issue. But, since, we are providing a mechanism to unregister, I'm not sure if we can do better than expect well behaved clients.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T20:07:03.927",
"Id": "474695",
"Score": "0",
"body": "While there are many recommended ways to do `use` constructs, that is... not one. I would add a separate `use` statement for each line at the top."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T13:22:26.587",
"Id": "474930",
"Score": "0",
"body": "@lights0123 Aesthetically, I prefer this style (I find it easier to read), and, it seems to have made it into rust a few years ago. The RFC https://rust-lang.github.io/rfcs/2128-use-nested-groups.html#drawbacks mentions grepping being an issue with this style. Are there any other disadvantages to this style? Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T14:43:38.280",
"Id": "474936",
"Score": "0",
"body": "there's no problems with it, it's just unconventional."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T20:36:52.000",
"Id": "241779",
"Score": "3",
"Tags": [
"rust",
"observer-pattern"
],
"Title": "Observer pattern over FFI"
}
|
241779
|
<p>I have an ECS implementation I wish to make more cache friendly and I'm stuck on what I should do.</p>
<p>Let me first present you with the implementation.</p>
<p><code>ECSManager.h</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>class ECSManager
{
private:
std::unordered_map<unsigned int, std::vector<std::unique_ptr<ComponentBase>>> m_Components;
std::unordered_map<unsigned int, std::unique_ptr<Entity>> m_Entities;
std::vector<std::unique_ptr<System>> m_Systems;
public:
void Update()
{
for (const auto& system : m_Systems)
{
auto entities = GetEntities(system->GetComponentsList());
system->Update(std::move(entities), this);
}
}
const Entity& CreateEntity(std::string&& name)
{
std::unique_ptr<Entity> e(new Entity(std::forward<std::string>(name)));
unsigned int id = e->GetID();
m_Entities.try_emplace(id, std::move(e));
return *m_Entities[id].get();
}
template <typename TSystem, typename... Args>
const System& CreateSystem(Args&&... args)
{
static_assert(std::is_base_of<System, TSystem>::value, "type parameter of this class must derive from System");
m_Systems.push_back(std::unique_ptr<TSystem>(new TSystem(std::forward<Args>(args)...)));
return *m_Systems[m_Systems.size() - 1].get();
}
template <typename TComponent, typename... Args>
void AddComponent(unsigned int entityId, Args&&... args)
{
unsigned int componentID = TComponent::ID;
if (m_Components.find(componentID) == m_Components.end())
m_Components[componentID] = std::vector<std::unique_ptr<ComponentBase>>();
m_Components[componentID].push_back(std::unique_ptr<TComponent>(new TComponent(std::forward<Args>(args)...)));
m_Entities[entityId]->AddComponent(componentID, m_Components[componentID].size() - 1);
}
template <typename TComponent>
TComponent& GetComponent(const Entity& entity)
{
static_assert(std::is_base_of<ComponentBase, TComponent>::value, "type parameter of this class must derive from Component");
auto componentsIndex = entity.GetComponentsIndex();
return *dynamic_cast<TComponent*>(m_Components[TComponent::ID][componentsIndex[TComponent::ID]].get());
}
template <typename TComponent>
std::vector<TComponent>& GetComponents()
{
unsigned int componentID = TComponent::ID;
return m_Components[componentID];
}
std::vector<std::vector<std::reference_wrapper<Entity>>> GetEntities(const std::vector<DynamicBitset>& componentsList)
{
std::vector<std::vector<std::reference_wrapper<Entity>>> entities;
for (unsigned int i = 0; i < componentsList.size(); i++)
{
auto& componentIDs = componentsList[i];
size_t count = componentIDs.size();
entities.push_back(std::vector<std::reference_wrapper<Entity>>{});
for (const auto& entity : m_Entities)
{
const auto& entitySignature = entity.second->GetSignature();
if (count > entitySignature.size())
continue;
bool equal = true;
for (std::size_t i = 0; i != count; i++)
{
if (componentIDs[i]() && !entitySignature[i]())
{
equal = false;
break;
}
}
if (!equal)
continue;
entities[i].push_back(*entity.second.get());
}
}
return entities;
}
};
</code></pre>
<p><code>ECSManager</code> is responsible for holding the different kind of Components, Entities, and Systems as-well as creating them (no need for removing ATM).</p>
<p>When adding a Component to an Entity the <code>ECSManager</code> will not only keep track of the Component but will also call <code>AddComponent(componentID, m_Components[componentID].size() - 1);</code> on the Entity which will make the Entity keep hold of the index of that component ID inside an internal data structure so later this could be used as a lookup method to find an Entity's specific component type inside <code>m_Components</code> using <code>template <typename TComponent> TComponent& GetComponent(const Entity& entity)</code>.</p>
<p><code>ECSManager</code> also call <code>Update</code> each frame and calls the <code>Update</code> method of each System with the relevant entities the system wish to operate on by calling <code>GetEntities(system->GetComponentsList());</code> and finding which entities' components signature match the component signature the System wants to operate on.</p>
<p>Problem <strong>I think</strong> there's with this implementation being cache friendly:</p>
<ul>
<li>System operates on a vector of matching entities based on component signature <code>std::vector<std::vector<std::reference_wrapper<Entity>>></code> while the vectors are stored and served to the System in linear fashion, when iterating them let's assume there will be one line cache load for the vector's items but also a line cache for each of the item since references are pointers behind the scene.
So optimally System could be served a vector of value type entities but this will be a problem since systems potentially modify entities so we can't pass copies, and we can't pass the whole original <code>m_Entities</code> vector (let's assume <code>m_Entities</code> is now <code>std::vector<Entity></code> instead of what it is in my implementation) since the System needs to operated only on a subset of entities.
<br/>I think an option would be to pass <strong>ALL</strong> entities to the <code>Update</code> method of a System with a descriptor array of what entities should be used by this system (as suggested in Scott Meyer's <a href="https://medium.com/software-design/why-software-developers-should-care-about-cpu-caches-8da04355bb8a" rel="nofollow noreferrer">article</a>) so the whole descriptor array will be loaded into cache and not the whole entity array but I find A problem with this approach:
Entity in my implementation could be simplified to just an ID of type <code>uint32_t</code> for example so if we had 100 entities let's say we'll load into cache <code>100 * sizeof(bool)</code> + <code>sizeof(Entity) * number_of_valid_entities_for_specific_system</code> bytes instead of <code>100 * sizeof(uint32_t)</code> which <strong>IS</strong> a nice micro optimization but if we had say 10000000000 entities we would still iterate over 10000000000 items which I'm not sure if this micro optimization will outweigh its benefits as more entities are presented.</li>
<li><p>Lets now assume we tackled somehow the first problem.
Now each system gets a linear set of entities by value to operate on. Now each system will query each entity for the relevant components it wants to operate on with a call to <code>template <typename TComponent> TComponent& GetComponent(const Entity& entity)</code>. This is also not cache friendly since <code>m_Components</code> is stored in an <code>std::unordered_map</code> which is not stored linearly and another problem here again is that we have vector of pointers so we'll have a cache line load for each dereference of the component which is inevitable since I'm holding a vector of pointers. I do this because <code>ComponentBase</code> is an abstract class and I can't have <code>std::vector<T></code> where <code>T</code> is abstract. One way this can be solved is that instead of System <code>Update</code> operating on entities it will operate on contiguous array of components.A possible implementation could be as follows:</p>
<pre><code>template <typename TComponent>
class ComponentManager {
std::vector<TComponent> m_Components;
std::vector<Entity> m_Entities;
Component& Create(Entity entity)
{
m_Components.push_back(TComponent());
m_Entities.push_back(entity);
return m_Components.back();
}
};
ComponentManager<Transform> transforms;
transforms.Create(entity);
// System update loop
for(size_t i = 0; i < transforms.GetCount(); ++i)
{
Transform& transform = transforms[i];
}
</code></pre></li>
</ul>
<p>But the problem with this is if we have the system operates on more entities with more than on component that we would have to either reference another <code>ComponentManager<TComponent></code> and use a lookup method with a map involved again causing alot of cache misses and loading of new cache lines or if we could somehow sync the indices of different <code>ComponentManager<TComponent></code> to match to the index of the same entity but that wouldn't be possible because take this example:</p>
<pre><code>Entity e1;
// add Mass component to e1
// Now ComponentManager<Mass>[0] is e1 mass
Entity e2;
// add Transform component to e2
// Now ComponentManager<Transform>[0] is e2 transform
// add Mass component to e2
// Now ComponentManager<Mass>[1] is e2 mass
...
Entity e3;
// add RigidBody component to e3
// Now ComponentManager<RigidBody>[0] is e3 rigidbody
// add Mass component to e3
// Now ComponentManager<Mass>[2] is e3 mass
</code></pre>
<p>we can either sync <code>e2</code> mass to be the first mass at index 0 or <code>e3</code> mass to be the first mass at index 0 but we can't have them both at index 0.</p>
<ul>
<li>Beside these 2 points which I think they're the main issue there're so easy to fix issues such as change <code>std::vector<std::unique_ptr<System>> m_Systems;</code> to <code>std::vector<System> m_Systems;</code> to avoid cache line loading for each dereferenced system and other issues are really dependent on what solution I'll go with so I don't wanna talk to much about them.</li>
</ul>
<p>So these are basically the issues as <strong>I SEE THEM</strong>, maybe I'm wrong, maybe there're more, I'm not sure and would like people who have better understanding give me their opinions and hear their ideas.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T22:18:02.190",
"Id": "241785",
"Score": "1",
"Tags": [
"c++",
"c++11",
"entity-component-system"
],
"Title": "ECS implementation cache friendly"
}
|
241785
|
<p>My take on a binary search algorithm without research or knowledge of an efficient one. It would be appreciated if one could show me an efficient way to do it using recursion or a more pythonic approach.</p>
<pre><code>from math import *
numList = [i for i in range(11)]
while True:
try:
beginning = 0
end = len(numList) - 1
mid = floor(((end-beginning)/2) + beginning)
value = int(input("What value would you like to search for?: "))
notFound = True
while notFound:
if value > end or value < beginning:
print("The value is not in the list")
break
elif value == mid:
print("The value is in the list")
print("The index is " + str(mid))
notFound = False
elif value == end:
print("The value is in the list")
print("The index is " + str(end))
notFound = False
elif value > mid:
beginning = mid
mid = floor(((end-beginning)/2) + beginning)
elif value < mid:
end = mid
mid = floor(((end-beginning)/2) + beginning)
except ValueError:
print("Invalid characters")
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><code>numList</code> is not used (this is \"ok\" as <code>numList[i] == i</code>). There is <code>value == mid</code> or <code>value == end</code> several times. But this just means you are comparing a value to be found with an index. The correct way would be <code>value == numList[mid]</code>.</p>\n\n<p>Consider using a function that does the binsearch for you.</p>\n\n<p>You may or may not use recursion. There is a nice way to do binsearch without recursion.</p>\n\n<p>I have also incorporated some naming conventions of python. If you are interested try programs like <code>pylint</code>. I have also added a bit nicer string formatting and some other python features you can live without but can come handy.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"Binary search.\"\"\"\nfrom random import randint\n\ndef bin_search(sorted_list, to_find):\n \"\"\"Searches the sorted_list for a to_find.\n If the to_find is found return (True, index)\n Otherwise return (False, 0)\n \"\"\"\n beg = 0\n end = len(sorted_list) - 1\n while beg <= end:\n mid = (end + beg) // 2 # integer division\n if sorted_list[mid] == to_find:\n return (True, mid)\n if sorted_list[mid] < to_find:\n (beg, end) = (mid + 1, end)\n else: # sorted_list[mid] > to_find\n (beg, end) = (beg, mid - 1)\n return (False, 0)\n\n# Create a sorted list of random numbers\nMY_LIST = sorted(randint(0, 100) for _ in range(20))\nprint(MY_LIST)\n\nwhile True:\n try:\n TO_FIND = int(input('Enter value you want to find: '))\n (FOUND, INDEX) = bin_search(sorted_list=MY_LIST, to_find=TO_FIND)\n if FOUND:\n print(f'Found {TO_FIND} at index: {INDEX}!')\n else:\n print(f'Value {TO_FIND} not found!')\n except ValueError:\n print('Invalid number to find')\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T09:06:39.667",
"Id": "241808",
"ParentId": "241788",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T00:41:21.703",
"Id": "241788",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "Python Binary Search"
}
|
241788
|
<p>I'd love some pointers on how to refactor this</p>
<pre><code>async function validate_request_args(req, request_type) {
let problem_id;
const errors = [];
switch (request_type) {
case "post":
if (req.body.id == null) {
errors.push({
msg: "Missing id of the problem",
param: "id"
});
} else {
problem_id = req.body.id;
}
break;
case "get":
if (req.query.id == null) {
errors.push({
msg: "Missing id of the problem",
param: "id"
})
} else {
problem_id = req.query.id;
}
break;
}
if (errors.length === 0) {
const problem = await models.Problem.findByPk(problem_id);
if (problem == null) {
errors.push({
msg: `Problem with id ${problem_id} does not exist `,
param: "id"
});
}
return monet.Validation.success(problem)
}
return monet.Validation.fail(errors);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T01:23:21.063",
"Id": "474476",
"Score": "0",
"body": "Will `request_type` always be `post` or `get`, or could it be something else like `put`?"
}
] |
[
{
"body": "<p>To start with, I see what's likely to be a logic error. At the bottom, you do:</p>\n\n<pre><code>if (problem == null) {\n errors.push({\n msg: `Problem with id ${problem_id} does not exist `,\n param: \"id\"\n });\n}\nreturn monet.Validation.success(problem)\n</code></pre>\n\n<p>If the <code>problem</code> isn't found, you push an error object to the <code>errors</code> array, but then you return <code>.success</code> anyway and don't use the <code>errors</code> array again. In such a case, I think you want to call <code>monet.Validation.fail</code> with the error object instead, and not call <code>.success</code>.</p>\n\n<p>Once that's done, note that you only ever have at most one element in the <code>errors</code> array, which <code>.fail</code> gets called with. It would be less repetitive to immediately call <code>.fail</code> and return when an error is encountered. Also, since the <code>fail</code> calls are all similar (<code>monet.Validation.fail([{ msg: SOME_MESSAGE, param: 'id' }])</code>), you can make the code DRY by putting that into a helper function:</p>\n\n<pre><code>const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);\n</code></pre>\n\n<p>Also, <code>switch</code> is almost never the right tool for the job IMO - it's quite verbose and can be error-prone when one forgets to <code>break</code> (which is surprisingly common). If the request type will be either <code>post</code> or <code>get</code>, use the conditional operator to figure out the property to look up on <code>req</code> instead:</p>\n\n<pre><code>const { id } = req[requestType === 'post' ? 'body' : 'query'];\n</code></pre>\n\n<p>I'd highly recommend against using loose equality <code>==</code>. It requires an expectation that any reader of the code understands <a href=\"https://i.stack.imgur.com/35MpY.png\" rel=\"nofollow noreferrer\">its strange rules</a>. Better to use strict equality. Or, if the <code>id</code> or <code>problem</code>, if it exists, will be truthy (which sounds likely), it would look even nicer to use a truthy test:</p>\n\n<pre><code>if (!id) {\n return fail('Missing id of the problem');\n}\n</code></pre>\n\n<p>If you <em>actually need</em> the logic you're implementing with <code>==</code> to check that the expressions aren't <code>null</code> <em>and</em> aren't <code>undefined</code> (but could be anything else, including other falsey values), then best to test both of those explicitly:</p>\n\n<pre><code>if (id === null || id === undefined) {\n return fail('Missing id of the problem');\n}\n</code></pre>\n\n<p>I think it would also be useful to follow the standard Javascript naming conventions and use <code>camelCase</code> for variable names in most cases.</p>\n\n<p>All together:</p>\n\n<pre><code>const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);\nasync function validateRequestArgs(req, requestType) {\n const { id } = req[requestType === 'post' ? 'body' : 'query'];\n if (!id) {\n return fail('Missing id of the problem');\n }\n const problem = await models.Problem.findByPk(id);\n if (!problem) {\n return fail(`Problem with id ${id} does not exist`);\n }\n return monet.Validation.success(problem);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T22:40:23.357",
"Id": "475110",
"Score": "0",
"body": "your edited solution ignores cases where id=0. I've fixed it"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T01:51:29.277",
"Id": "241791",
"ParentId": "241790",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "241791",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T01:20:53.113",
"Id": "241790",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Node refactor if/else mess"
}
|
241790
|
<p>My take on Doubly Linked List in Python. Is there a more efficient and compact way to do this? Are there any bugs in my program if so how can i fix it?</p>
<p><strong>PS:</strong> I'm a beginner in Object Oriented Programming, so i might have gaps in my knowledge, please explain any new concept i failed to add to my implementation, Thanks.</p>
<pre class="lang-py prettyprint-override"><code>class Node:
def __init__(self, data):
self.prev = None
self.data = data
self.next = None
class Doubly_Linked_List:
def __init__(self):
self.head = None
self.length = 0
def __iter__(self):
CurrentNode = self.head
while CurrentNode != None:
yield CurrentNode.data
CurrentNode = CurrentNode.next
def __getitem__(self, index):
length = self.length
if index > length-1:
raise IndexError("Index Exceeds The Length of Linked List")
elif index < 0:
if index < -length:
raise IndexError("Index Exceeds The Length of Linked List")
else:
count = -length
CurrentNode = self.head
while count != index:
CurrentNode = CurrentNode.next
count += 1
else:
count = 0
CurrentNode = self.head
while index != count:
CurrentNode = CurrentNode.next
count += 1
return CurrentNode.data
def __len__(self):
return self.length
def __str__(self):
CurrentNode = self.head
result = []
while CurrentNode != None:
result.append(CurrentNode.data)
CurrentNode = CurrentNode.next
return f'{result}'
def find_index(self, value):
if not self.length:
return -1
index = 0
CurrentNode = self.head
while CurrentNode.data != value:
CurrentNode = CurrentNode.next
index += 1
if CurrentNode == None:
break
if CurrentNode != None:
return index
else:
return -1
def append(self, value):
head = self.head
NewNode = Node(value)
if head == None:
self.head = NewNode
else:
PrevNode = head
CurrentNode = head.next
while CurrentNode != None:
PrevNode = CurrentNode
CurrentNode = CurrentNode.next
PrevNode.next = NewNode
CurrentNode = NewNode
CurrentNode.prev = PrevNode
self.length += 1
def insert(self, index, value):
head = self.head
NewNode = Node(value)
length = self.length
if index > length-1:
raise IndexError("Index Exceeds Length of Linked List!")
elif index < 0:
if index < -length:
raise IndexError("Index Exceeds The Length of Linked List")
else:
self.insert(length+index, value)
return
elif index == 0:
if head == None:
self.head = NewNode
else:
NewNode.next = head
head.prev = NewNode
self.head = NewNode
else:
if index == length-1:
self.append(value)
else:
PrevNode = head.prev
CurrentNode = head
NextNode = head.next
count = 0
while count != index:
PrevNode = CurrentNode
CurrentNode = NextNode
NextNode = NextNode.next
count += 1
PrevNode.next = NewNode
NewNode.next = CurrentNode
self.length += 1
def delete_index(self, index):
head = self.head
length = self.length
if index > length-1:
raise IndexError("Index Exceeds the Length of Linked List!")
elif index == 0:
self.head = head.next
self.head.prev = None
head.next = None
elif index < 0:
if index < -length:
raise IndexError("Index Exceeds The Length of Linked List")
else:
self.delete_value(self.__getitem__(index))
return
else:
if index == length-1:
PrevNode = head
CurrentNode = head.next
while CurrentNode != None:
PrevNode = CurrentNode
CurrentNode = CurrentNode.next
PrevNode.prev.next = None
PrevNode.prev = None
else:
PrevNode = head.prev
CurrentNode = head
NextNode = head.next
count = 0
while count != index:
PrevNode = CurrentNode
CurrentNode = NextNode
NextNode = NextNode.next
count += 1
NextNode.prev = PrevNode
PrevNode.next = CurrentNode.next
self.length -= 1
def delete_value(self, value):
if self.length == 0:
return False
else:
index = self.find_index(value)
if index == -1:
raise ValueError(f"{value} is not in linked_list.")
else:
self.delete_index(index)
return True
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T02:55:22.767",
"Id": "241792",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"linked-list"
],
"Title": "Implementing Doubly Linked List in Python"
}
|
241792
|
<p>This simple program, that I call <code>trim(1)</code>, trims trailing lines and, if the flag <code>-l</code> is passed as an argument, it also removes empty lines and lines containing only blanks.</p>
<p>I did this as an exercise for learning C and good practices of C programming in UNIX.</p>
<p>It reads from standard input if no argument is passed or read from the files passed as arguments.</p>
<p>I am a bit suspicious of that realloc idiom for reallocing the buffer if it gets full. Is it right?</p>
<pre><code>#include <err.h>
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MID 0 /* in middle of line */
#define BEG 1 /* at beginning of line */
static int blankline = 0;
static int exitval = EXIT_SUCCESS;
static void trim(FILE *fp);
static void usage(void);
/* remove trailing blanks and delete blank lines */
int
main(int argc, char *argv[])
{
int ch;
FILE *fp;
while ((ch = getopt(argc, argv, "l")) != -1) {
switch (ch) {
case 'l':
blankline = 1;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc == 0) {
trim(stdin);
} else {
while (*argv) {
if ((fp = fopen(*argv, "r")) == NULL) {
warn("%s", *argv);
exitval = EXIT_FAILURE;
} else {
trim(fp);
fclose(fp);
}
argv++;
}
}
}
/* trim trailing blanks from fp; if blankline is set also remove blank lines */
static void
trim(FILE *fp)
{
char *buf = NULL;
size_t i, size, newsize;
int status;
int c;
size = BUFSIZ;
if (buf == NULL)
if ((buf = malloc(size)) == NULL)
err(EXIT_FAILURE, "malloc");
i = 0;
status = BEG;
while ((c = getc(fp)) != EOF) {
if (isblank(c)) { /* collect blanks in buf */
if (i >= size) { /* realloc */
newsize = size + BUFSIZ;
if (newsize <= size) /* check for overflow */
errc(EXIT_FAILURE, EOVERFLOW, "realloc");
size = newsize;
if ((buf = realloc(buf, size)) == NULL)
err(EXIT_FAILURE, "realloc");
}
buf[i++] = c;
} else if (c == '\n') {
if (status == MID || (!blankline))
putchar('\n');
status = BEG;
i = 0;
} else {
fwrite(buf, 1, i, stdout);
putchar(c);
status = MID;
i = 0;
}
}
if (ferror(fp)) {
warn("getc");
exitval = EXIT_FAILURE;
}
}
/* show usage */
static void
usage(void)
{
(void)fprintf(stderr, "usage: trim [-l] [file...]\n");
exit(EXIT_FAILURE);
}
</code></pre>
|
[] |
[
{
"body": "<p>Well designed code.</p>\n\n<hr>\n\n<blockquote>\n <p>I am a bit suspicious of that realloc idiom for reallocing the buffer if it gets full. Is it right?</p>\n</blockquote>\n\n<p>I see no errors.</p>\n\n<p>Nit: I'd rather see <code>newsize</code> declared locally. It is only used there.</p>\n\n<pre><code>// newsize = size + BUFSIZ;\nsize_t newsize = size + BUFSIZ;\n</code></pre>\n\n<hr>\n\n<p>Other</p>\n\n<p><strong>Unneeded code</strong></p>\n\n<p>The initial allocation is not needed. <code>realloc()</code> in the loop can handle starting from 0</p>\n\n<pre><code>//size = BUFSIZ;\n//if (buf == NULL)\n// if ((buf = malloc(size)) == NULL)\n// err(EXIT_FAILURE, \"malloc\");\nsize = 0;\n</code></pre>\n\n<p>Perhaps there is a concern about ...</p>\n\n<pre><code>fwrite(NULL, 1, 0, stdout); \n</code></pre>\n\n<p>... yet given the spec \"If size or nmemb is zero, fwrite returns zero and the state of the stream remains unchanged.\", I see no issue.</p>\n\n<p>Either way I'd consider the micro-optimization below, just for the sake of avoiding the <code>fwite()</code> function call as <code>i==0</code> will be quite common. (Usually I do not encourage any micro-op - I'll make an exception here)</p>\n\n<pre><code>// fwrite(buf, 1, i, stdout);\nif (i > 0) fwrite(buf, 1, i, stdout);\n</code></pre>\n\n<p><strong>Checking output</strong></p>\n\n<p>Code does not check the return values of <code>fwrite(), putchar(c)</code>. Robust code would and report the problem - even if it is rare.</p>\n\n<p><strong>Missing <code>free()</code></strong></p>\n\n<p>Free the allocation, else <code>trim()</code> leaks memory.</p>\n\n<pre><code>free(buf);\n</code></pre>\n\n<p><strong><code>ferror()</code></strong></p>\n\n<p>Good that code checks this.</p>\n\n<p><strong><code>main()</code> always reports success</strong></p>\n\n<p><code>main()</code> employs the implied <code>return 0;</code>. Yet failure is possible.</p>\n\n<p>Given code has <code>exitval = EXIT_FAILURE;</code>, I'd expect <code>main()</code> to <code>return exitval;</code> in the end.</p>\n\n<p><strong>Initialize</strong></p>\n\n<p>Rather than declare then assign lines later, consider declare with initialization.</p>\n\n<pre><code>// int status;\n// ...\n// status = BEG;\nint status = BEG;\n\n// size_t size;\n// ...\n// size = BUFSIZ;\nsize_t size = BUFSIZ;\n</code></pre>\n\n<p>Same for <code>i</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T14:04:29.583",
"Id": "474550",
"Score": "0",
"body": "*\"Given code has exitval = EXIT_FAILURE;, I'd expect main() to return exitval; in the end.\"* LOL, it was supposed to `return exitval`, I really forgot it. Thanks for seeing it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T14:08:06.537",
"Id": "474552",
"Score": "0",
"body": "*\"Code does not check the return values of fwrite(), putchar(c)\"*. Should I use an `ferror(stdout)` in the end of the function instead of checking the return values of `fwrite(3)` and `putchar(3)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T14:18:37.883",
"Id": "474553",
"Score": "0",
"body": "@barthooper Perhaps. A more direct approach would take action as soon as the error occurs. IMO a write error is most likely on the first write - otherwise it is rare. Your call."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T12:02:59.750",
"Id": "241817",
"ParentId": "241794",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241817",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T04:00:23.623",
"Id": "241794",
"Score": "2",
"Tags": [
"c",
"unix"
],
"Title": "Trim trailing lines and remove blank lines in C"
}
|
241794
|
<p>I am learning C, and wrote this <a href="https://en.wikipedia.org/wiki/Pig_Latin" rel="noreferrer">pig-latin</a> translator.</p>
<p>If no argument is given, it operates on standard input. Otherwise, it operates on the arguments given.</p>
<p>Here are some examples:</p>
<pre class="lang-bsh prettyprint-override"><code>$ echo "The quick brown fox jumps over Vladmir's lazy young Yggdrasil!" | ./piglatin
Ethay ickquay ownbray oxfay umpsjay overway Admir'svlay azylay oungyay Yggdrasilway!
$ ./piglatin "Now is the time, for all good men to come to the aid of their party"
Ownay isway ethay imetay, orfay allway oodgay enmay otay omecay otay ethay aidway ofway eirthay artypay
</code></pre>
<pre><code>#include <err.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define SUFFIXC "ay"
#define SUFFIXV "way"
static void usage(void);
static void piglatin(const char *s);
static int isvowel(const char *s);
/* Encodes English-language phrases into Pig Latin. */
int
main(int argc, char *argv[])
{
int c;
while ((c = getopt(argc, argv, "h")) != -1) {
switch (c) {
case 'h':
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc == 0) {
char *line = NULL;
size_t linesize = 0;
ssize_t linelen;
while ((linelen = getline(&line, &linesize, stdin)) != -1) {
if (line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
piglatin(line);
}
free(line);
if (ferror(stdin))
err(EXIT_FAILURE, "stdin");
} else {
while (argc-- > 0)
piglatin(*argv++);
}
if (ferror(stdout))
err(EXIT_FAILURE, "stdout");
return EXIT_SUCCESS;
}
/* translate s into Pig Latin */
static void
piglatin(const char *s)
{
const char *p, *onset, *root, *end, *suffix;
bool upper;
while (*s != '\0') {
while (!isalpha(*s) && *s != '\'' && *s != '\0')
putchar(*s++);
upper = false;
if (isupper(*s))
upper = true;
if (*s == '\0')
break;
onset = s;
while (isalpha(*s) && !isvowel(s)) {
if (*s == 'q' && *(s+1) == 'u')
s++;
s++;
}
root = s;
while (isalpha(*s) || *s == '\'')
s++;
end = s;
suffix = (onset == root) ? SUFFIXV : SUFFIXC;
for (p = root; p != end; p++) {
if (p == root && upper)
putchar(toupper(*p));
else
putchar(*p);
}
for (p = onset; p != root; p++) {
if (p == onset && upper)
putchar(tolower(*p));
else
putchar(*p);
}
printf("%s", suffix);
}
printf("\n");
}
/* test if first letter of s is a vowel */
static int
isvowel(const char *s)
{
switch (tolower(*s)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return 1;
case 'y':
return (isvowel(s+1) ? 0 : 1);
}
return 0;
}
static void
usage(void)
{
(void) fprintf(stderr, "usage: piglatin [phrase...]\n");
exit(EXIT_FAILURE);
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Inadvertent case dependency?</strong></p>\n\n<p>Should not the below code also work with <code>'Q'</code>, <code>'U'</code>?</p>\n\n<pre><code>if (*s == 'q' && *(s+1) == 'u')\n</code></pre>\n\n<p><strong><code>char</code> functions (advanced issue)</strong>`</p>\n\n<p>The Std C library functions treat <code>char *</code> data as if it was accessed by <code>unsigned char *</code>.</p>\n\n<p>This is important in select cases.</p>\n\n<p><code>tolower(int ch)</code>, <code>is...()</code> are well defined for values in the <code>unsigned char</code> range and <code>EOF</code>, else UB. When <code>*s < 0</code>, <code>tolower(*s)</code> is a problem. Casting to <code>(unsigned char)</code> fixes that.</p>\n\n<pre><code>isvowel(const char *s) {\n // switch (tolower(*s)) {\n switch (tolower((unsigned char) *s)) {\n</code></pre>\n\n<p>With some extended ASCII encoding this is useful, yet with UTF8, the issue moot as <code>tolower()</code> is wholly inadequate.</p>\n\n<hr>\n\n<p><strong>Deeper pedantic detail</strong></p>\n\n<p><code>(unsigned char) *s</code> is the wrong solution with non-2's complement and <em>signed</em> <code>char</code> (not seen these days) as code should access the data an <code>unsigned char</code>. </p>\n\n<pre><code>isvowel(const char *s) {\n const char *us = (const char *) s;\n switch (tolower(*us)) {\n</code></pre>\n\n<p>With 2's complement the result is the same with either approach. IAC, I doubt much C code these days would survive a new non-2's complement integer encoding so no real reason to worry about this deep detail.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>Code lacks <code>{}</code> in simple blocks. I find the later style easier to review and maintain. As with such style issues, code to your group's coding standard.</p>\n\n<pre><code>} else {\n while (argc-- > 0)\n piglatin(*argv++);\n}\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>} else {\n while (argc-- > 0) {\n piglatin(*argv++); \n }\n}\n</code></pre>\n\n<p><strong>Consider local variables, initialization and code reduction</strong></p>\n\n<pre><code>//bool upper;\n//...\n// upper = false;\n// if (isupper(*s))\n// upper = true;\n bool upper = isupper(*s);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T18:26:55.053",
"Id": "241830",
"ParentId": "241795",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241830",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T04:10:44.527",
"Id": "241795",
"Score": "7",
"Tags": [
"c",
"pig-latin"
],
"Title": "Pig Latin translator in C"
}
|
241795
|
<p>I am trying to improve the performance of one of my project's methods, which obtains the command line of a process using WMI. A summary of key points:</p>
<ul>
<li>The method is on an object representing a Windows Process.</li>
<li>Many (hundreds) of such objects will exist</li>
<li>The code to obtain the command line for a single process takes ~50 ms to run. </li>
<li>The code to obtain the command lines for all processes takes ~200 ms to run.</li>
<li>The goal of my code is to pre-fetch the results for all processes and store in a map, so other objects can simply fetch their results from the map</li>
<li>If I get all ~200 processes one by one, the whole iteration takes over 10 seconds. If I fetch once and cache, the entire iteration takes only ~250ms.</li>
<li>The map key is a process ID. These can be re-used but the new process will have a later start time than the time the original key was inserted.</li>
<li>To keep the map from retaining too much stale data, I desire to periodically clear it. Iterating over stale elements is much less efficient than a clear-and-refill.</li>
</ul>
<p>In theory, it wouldn't hurt for multiple threads to be storing information at the same time, as they would be writing the same key and value. However, the cost of locking is probably much lower than the cost of fetching the information to store, so one key goal is to only have a single thread executing the expensive call.</p>
<p>I considered the use of <code>ConcurrentHashMap</code> but think with the way my get and put are sequenced that it wouldn't provide sufficient checking. </p>
<p>Questions I have:</p>
<ul>
<li>Is this code thread safe? </li>
<li>If not, can it be made so?</li>
<li>Could using a <code>ReentrantReadWriteLock</code> improve this?</li>
<li>I continually see "static maps are a bad idea" but don't see a good alternative here. Is there an obvious (to others), safer option?</li>
</ul>
<p>I have attempted to extract the relevant portions of the code with the map locking, unlocking, and access below which should be sufficient for review. The full code can be accessed <a href="https://github.com/oshi/oshi/pull/1194" rel="nofollow noreferrer">on my PR here</a>. </p>
<pre><code>public class WindowsOSProcess extends AbstractOSProcess {
// The map and its lock. Static for intended access by all process objects
private static final Map<Integer, Pair<Long, String>> commandLineCache = new HashMap<>();
private static final ReentrantLock commandLineCacheLock = new ReentrantLock();
// Each object will only fetch its own string once via this memoized getter
private Supplier<String> commandLine = memoize(this::queryCommandLine);
// The public facing API method that fetches via the memoizer
@Override
public String getCommandLine() {
return this.commandLine.get();
}
// The query method. Could be called from multiple different
// objects at the same time
private String queryCommandLine() {
commandLineCacheLock.lock();
Pair<Long, String> pair = commandLineCache.get(getProcessID());
// Valid process must have been started before map insertion
if (pair != null && getStartTime() < pair.getA()) {
// Entry is valid, return it!
commandLineCacheLock.unlock();
return pair.getB();
} else {
// Invalid entry, rebuild cache
// Invalidate processes started after this time
long now = System.currentTimeMillis();
// "Expensive" method, takes ~200ms
WmiResult<CommandLineProperty> commandLineAllProcs = Win32Process.queryCommandLines(null);
// Periodically clear cache to recover resources when its size is 2*# of
// processes
if (commandLineCache.size() >= commandLineAllProcs.getResultCount() * 2) {
commandLineCache.clear();
}
// Iterate results and put in map, storing current PID along the way
String result = "";
for (int i = 0; i < commandLineAllProcs.getResultCount(); i++) {
int pid = WmiUtil.getUint32(commandLineAllProcs, CommandLineProperty.PROCESSID, i);
String cl = WmiUtil.getString(commandLineAllProcs, CommandLineProperty.COMMANDLINE, i);
commandLineCache.put(pid, new Pair<>(now, cl));
if (pid == getProcessID()) {
result = cl;
}
}
commandLineCacheLock.unlock();
return result;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One thing that immediately jumps out at me is, that you don't use a finally-block to free the lock (as is recommended in the according javadoc btw.), i.e. if there's a single exception in processing, your whole code will be basically dead, as the lock will never be freed anymore.</p>\n\n<p>Thus, to cite the docs, I'd rather do:</p>\n\n<pre><code>commandLineCacheLock.lock();\ntry {\n // do all the processing here\n}\nfinally {\n commandLineCacheLock.unlock();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T06:02:36.723",
"Id": "474484",
"Score": "0",
"body": "Thanks! And now that I see I'm basically just wrapping the whole code block I'm wondering if I shouldn't just use synchronized (on a static object such as the map itself)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T06:07:38.393",
"Id": "474485",
"Score": "0",
"body": "As `synchronized` carries a bad gut-feeling for me (probably just subjective) I'd stick to the lock. Apart from that, you might reallly benefit from a ReadWrite-lock, but sorry, at this time I just really cannot wrap my head around this. (Just got up ;-))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T06:15:51.220",
"Id": "474486",
"Score": "0",
"body": "I considered a double-checked implementation where the first map read was outside the lock for performance, with a second read inside it... but that's really probably overkill here..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T15:06:28.000",
"Id": "474558",
"Score": "0",
"body": "I'll go ahead and accept this since it was an extremely valuable contribution. After a night's sleep I think I will keep the same core locking code here but move to a singleton object (using.a memoizer for thread safety of the instance)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T05:41:08.233",
"Id": "241799",
"ParentId": "241798",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T05:03:18.820",
"Id": "241798",
"Score": "1",
"Tags": [
"java",
"thread-safety",
"hash-map",
"locking"
],
"Title": "Is this locked use of a Java HashMap thread safe?"
}
|
241798
|
<p>I had old <code>enum</code>, I converted it to Enumeration class and added one method inside (<code>isValid</code>). I am not sure if it is good approach to add such small business logic into Enumeration class. I would like to understand if this is a good approach or not. </p>
<p>Here is <strong>old</strong> <code>enum</code>:</p>
<pre><code>internal enum Rule
{
None = 0,
CompensationIsZero = 1,
CompensationLessThanDemand = 2,
CompensationBetweenZeroAndDemand = 3,
CompensationEqualsDemand = 4,
CompensationLessOrEqualsDemand = 5
}
</code></pre>
<p>Here it is rewritten to <code>Enumeration</code> class and <code>IsValid</code> method is added.</p>
<pre><code> public class Rule : Enumeration
{
public static readonly Rule None = new Rule (0, "None");
public static readonly Rule CompensationIsZero = new Rule (1, "CompensationIsZero ");
public static readonly Rule CompensationLessThanDemand = new Rule(2, "CompensationLessThanDemand ");
....
// there are about 5 rules
public Rule(int id, string name)
: base(id, name)
{ }
public bool IsValid(decimal compensation, decimal demand, int rule) {
if (rule == Rule.None.Id) return true;
if (rule == Rule.CompensationIsZero.Id) then return compensation == 0;
if (rule == Rule.CompensationLessThanDemand .Id) then return compensation < demand;
...
}
}
</code></pre>
<p><code>Enumeration</code> class implementation version is very similar like in this article (<a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types</a>)</p>
<p>Thus I have values <code>compensation</code> and <code>demand</code> (these come from UI).
And I have some type based on which I get Rule value from database.
And so I call method <code>IsValid (compensation, demand, ruleIdFromDb)</code>. If it is not validated then I show error on UI. </p>
|
[] |
[
{
"body": "<p>Shouldn't the 'IsValid' method be static? I suppose you use it like <code>Rule.IsValid(calculatedCompensation, 0, Rule.CompensationIsZero.Id)</code>, (as general idea, obviously it can be simplified).</p>\n\n<p>Anyway PERSONALLY I would not do this, because <code>Rule</code> is no more an <code>Enum</code>, you gave it logic, that usually <code>Enum</code> don't have. I would have keep the <code>Enum</code> as original and built on top of that a <code>Class</code> with the required logic. (Maybe called <code>RuleValidator</code> with a static method <code>public static bool IsValid(Rule rule, decimal compensation, decimal demand) {...}</code>.</p>\n\n<p>If this does not concern you, than another way could be to write an extension method:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static class RuleExtensions \n{\n public static bool Validate(this Rule rule, decimal compensation, decimal demand) \n {\n switch (rule) \n {\n case None: return true;\n case CompensationIsZero: return compensation == 0;\n case CompensationLessThanDemand : return compensation < demand;\n // ecc...\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T07:55:09.763",
"Id": "474493",
"Score": "0",
"body": "Your comment make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T08:44:15.017",
"Id": "474496",
"Score": "0",
"body": "can I ask one more question, what if I would like to have different error messages based on which Case failed. Should I add static property ErrorMessage or should error message be returned from Validate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T06:17:06.613",
"Id": "474602",
"Score": "0",
"body": "I can't think a super elegant solution, I'm still junior. But I would go for something like `public static bool Validate (this Rule rule, decimal compensation, decimal demand, out string errorMessage) {...}`. Usage: `if (!Rule.None.Validate.(10, 0, out var error)) Console.WriteLine(error);`. Inside `Validate` then, before returning false, you would set `errorMessage` with a string retrieved form some kind of external resource (like the .resx files, or a DB). This because you could need the message to change (like for localization)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T07:53:46.277",
"Id": "241803",
"ParentId": "241800",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T07:33:41.290",
"Id": "241800",
"Score": "2",
"Tags": [
"c#",
".net",
"enum"
],
"Title": "Enum conversion to Enumeration class with small Business Logic inside"
}
|
241800
|
<p>Yes, this is one of my assignments.</p>
<p><strong>Question:</strong></p>
<p>I am asked to rewrite a generic QuickSort algorithm using only Java List Interface.
The purpose is that the algorithm can be executed for both LinkedList and ArrayList with any type extends Comparable interface. Professor suggests me that I should think stackwise and list approach (instead of in-place approach), using as less memory as possible and still maintain O(nlogn) complexity.</p>
<p><strong>What I got so far</strong></p>
<p>I have these lists <code>lessThanPivot, equalPivot, greaterThanPivot</code> to store the partitions, <code>sortedList</code> to store the output sorted array.
These lists are put on top of my class to reuse instead of instantiate them in every pass.</p>
<pre class="lang-java prettyprint-override"><code>
import java.util.*;
public class QuickSort<T extends Comparable<T>>
{
public List<T> lessThanPivot, equalPivot, greaterThanPivot, sortedList;
/**
* A generic recursive QuickSort algorithms which should work on any Comparable Objects.
* @param data: the list of items to be sorted
* @return
*/
public void quickSort(List<T> data, int start, int end)
{
if (start > end) return;
end = Math.min(data.size(), end);
T pivot = null;
//Construct buffer lists
ListIterator<T> iterator = data.listIterator(end);
while (iterator.hasPrevious() && iterator.previousIndex() >= start)
{
T current = iterator.previous();
if (pivot == null) pivot = current;
if (current.compareTo(pivot) < 0) lessThanPivot.add(current);
else if (current.compareTo(pivot) == 0) equalPivot.add(current);
else greaterThanPivot.add(current);
iterator.remove();
}
int lessThanPivotStartIndex = start + greaterThanPivot.size() + equalPivot.size();
int greaterThanPivotEndIndex = start + greaterThanPivot.size() - 1;
copyBufferListsToOriginalList(data);
//Recursively sort the less than pivot
if (lessThanPivotStartIndex < end && end <= data.size()) quickSort(data, lessThanPivotStartIndex, end);
//In case all the lessThanPivot and equalPivot has been moved to output array, recursively call to sort the whole data
//as it now contains only greaterThanPivot
else if (lessThanPivotStartIndex > data.size()) {quickSort(data, 0, data.size()); return;}
//Recursively sort the greater than pivot
if (greaterThanPivotEndIndex > start) quickSort(data, start, greaterThanPivotEndIndex);
}
/**
* Function to copy back the buffer lists to original list
* @param data
*/
private void copyBufferListsToOriginalList(List<T> data)
{
if (lessThanPivot.isEmpty() || lessThanPivot.size() <= 1) {
copy(lessThanPivot, sortedList);
copy(equalPivot, sortedList);
if (greaterThanPivot.size() <= 1) copy(greaterThanPivot, sortedList);
else copy(greaterThanPivot, data);
}else {
copy(greaterThanPivot, data);
copy(equalPivot, data);
copy(lessThanPivot, data);
}
}
/**
* Function to copy items from one list to another using iterator
* @param source: The source list
* @param destination: The destination list
*/
private void copy(List<T> source, List<T> destination)
{
// destination.addAll(source);
// source.clear();
ListIterator<T> iterator = source.listIterator();
while (iterator.hasNext())
{
destination.add(iterator.next());
iterator.remove();
}
}
}
</code></pre>
<p>This is how I am instantiating these lists and calling QuickSort class</p>
<pre class="lang-java prettyprint-override"><code>public class MainArrayList {
public static void main(String[] args) {
int maximumNumberOfItem = (int) Math.pow(10, 1);
List<Integer> toBeSorted;
QuickSort<Integer> qs = new QuickSort<>();
qs.lessThanPivot = new ArrayList<>();
qs.equalPivot = new ArrayList<>();
qs.greaterThanPivot = new ArrayList<>();
qs.sortedList = new ArrayList<>();
}
}
</code></pre>
<p>Ideally, I should have <code>MainLinkedList</code> class, which is identical with <code>MainArrayList</code> but these lists will be <code>LinkedList</code> instead.</p>
<p><strong>Problems</strong></p>
<ul>
<li>Even though my QuickSort can sort correctly, but it runs quite slow compare to recursive in-place versions.</li>
<li>I got StackOverflow exception when n = 10,000.</li>
</ul>
<p>I am not sure what is wrong and what could I improve on my program.</p>
<p>Thanks for your all advice and stay safe.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T09:30:31.253",
"Id": "474509",
"Score": "0",
"body": "`O(nlogn)` *time* sticking to *list instead of in-place* may prove challenging with `java.util.ArrayList<>`: please show/compare run time for a linked variant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T09:55:05.053",
"Id": "474513",
"Score": "0",
"body": "@greybeard I've just updated the question with my classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:03:51.407",
"Id": "474514",
"Score": "0",
"body": "(I almost commented you don't show `QuickSort<>` instantiating its lists.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:33:26.267",
"Id": "474521",
"Score": "0",
"body": "@greybeard the purpose is the QuickSort can work with both ```LinkedList``` and ```ArrayList```. If the input array is ArrayList, then I will instantiate these lists as ```ArrayList``` and vice versa. (it's a homework assignment, you know)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:35:41.313",
"Id": "474522",
"Score": "0",
"body": "I have a strong feeling that my recursive calls are causing the slowness ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T05:46:45.337",
"Id": "474736",
"Score": "2",
"body": "Show at least one setup where your code did seem to sort: I got `java.lang.UnsupportedOperationException` immediately trying to sort *{ 3, 1, 4, 5, 9, 4, 3, 7, 0 }*. Better yet, show your *unit tests*."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T08:49:13.487",
"Id": "241806",
"Score": "1",
"Tags": [
"java",
"quick-sort"
],
"Title": "QuickSort - List Interface Java"
}
|
241806
|
<h1>Note for future reference and google searches</h1>
<p>The list of urls for IP retrieving will very likely need continuous adjustments in the future.</p>
<pre><code>// Few services that should return the IP as plain text,
// properly configured to accept CORS
const IP_URLs = [
'https://api.ipify.org/',
'https://ipecho.net/plain',
'https://api.kwelo.com/v1/network/ip-address/my',
'https://myexternalip.com/raw',
];
</code></pre>
<hr />
<h1>Original question</h1>
<p>This code is for retrieving the public IP address. I wanted something that can automatically switch between a few services in case the some of them are down. Since I do not use jquery in my project, I preferred the Fetch API aiming at keeping the code as light as possible. I was not able to find anything similar in the web, so here we go!</p>
<p>I am mostly concerned about correctness, but since I consider myself a beginner in JS, also readability, style, indentation are all very relevant. Should I have used <code>async/await</code>?</p>
<pre><code>// Few services that should return the IP as plain text, properly configured to accept CORS
const IP_URLs = [
'https://api.ipify.org/',
'https://ipecho.net/plain',
'https://api.kwelo.com/v1/network/ip-address/my',
'https://myexternalip.com/raw',
];
// Log my public IP in the console
get_ip(IP_URLs, console.log);
// Trampoline that deep copies the urls array to later allow for pop() and recursion
function get_ip(urls, callback) {
get_ip_impl(urls.slice(), callback);
}
function get_ip_impl(urls, callback) {
if (urls.length > 0) {
let url = urls.pop();
let init = {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-store', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/text'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
};
fetch( url, init).then(
response => {
response.text().then(
txt => { if (isValidIP(txt)) {
callback(txt);
} else {
console.log("Invalid IP: "+url+" --> "+txt);
get_ip_impl(urls, callback);
}
},
notxt => { console.log("text(): "+url+" --> "+notxt);
get_ip_impl(urls, callback);
}
)
},
reason => { console.log("Fetch: "+url+" --> "+reason);
get_ip_impl(urls, callback); }
);
} else {
callback("No more URLs");
}
}
function isValidIP(txt) {
return /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(txt);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T09:00:36.140",
"Id": "474500",
"Score": "0",
"body": "*I am mostly concerned about correctness* Does it work currently, as far as you've been able to tell?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T09:01:33.263",
"Id": "474501",
"Score": "1",
"body": "@CertainPerformance of course it does! But there may be hidden bugs and/or corner cases."
}
] |
[
{
"body": "<p>One of the main reasons Promises were created was to avoid the ugly nesting of callbacks when multiple asynchronous actions need to occur. For example, rather than</p>\n\n<pre><code>fn1(dataToSend, dataForFn2 => {\n fn2(dataForFn2, dataForFn3 => {\n fn3(dataForFn3, processedData => {\n console.log(processedData);\n });\n });\n});\n</code></pre>\n\n<p>If the functions returned Promises instead of accepting callbacks, the above could be done with</p>\n\n<pre><code>fn1(dataToSend)\n .then(fn2)\n .then(fn3)\n .then(processedData => {\n console.log(processedData);\n });\n</code></pre>\n\n<p>The Promise-as-callback antipattern is when you <strong>nest</strong> <code>.then</code>s in other <code>.then</code>s or pass around callbacks rather than <em>chaining</em> another <code>.then</code> onto the previous Promise. This is the trap you're falling into here. Since <code>fetch</code> returns a Promise itself, it would be best to return that Promise and allow consumers of this script to use it. That is, it would be really convenient (and appropriate) if consumers to be able to do something like</p>\n\n<pre><code>get_ip(IP_URLs)\n .then(console.log)\n .catch(handleErrors);\n</code></pre>\n\n<p>Another related nesting issue you might consider is, instead of</p>\n\n<pre><code>if (goodCondition) {\n // lots of code\n} else {\n callback(\"No more URLs\");\n}\n</code></pre>\n\n<p>Rather than having to keep track of which brackets correspond to what upper condition, it might be preferable to return early instead:</p>\n\n<pre><code>if (!goodCondition) {\n callback(\"No more URLs\");\n return;\n}\n// lots of code\n</code></pre>\n\n<p>But if you return the Promises instead of using callbacks, this should cease to be an issue.</p>\n\n<p>The <code>init</code> object you're constructing seems strangely complicated. Many of the properties you're passing are the default ones already (like <code>method: 'get'</code>, <code>redirect: 'follow'</code>) or useless (<code>credentials: 'same-origin'</code>). Unless you're deliberately trying to affect some things with the object, it would be simpler and less confusing to omit it entirely (the script looks to work just fine without it, none of the properties look useful).</p>\n\n<p>You have a <em>lot</em> of fail-handlers. If you really want to exhaustively identify what's OK and what isn't, it would be good to also check if the <em>response</em> is OK too:</p>\n\n<pre><code>return fetch(url).then(\n response => {\n if (!response.ok) {\n console.log('Response was not OK:', response.status);\n return getIPFromNextSite(urls);\n }\n</code></pre>\n\n<p>But unless you're actively analyzing exactly which stage is working and what isn't, and really need all those <code>.fail</code> handlers, you might consider <a href=\"https://stackoverflow.com/questions/24662289/when-is-thensuccess-fail-considered-an-antipattern-for-promises\">avoiding them</a> and <code>.catch</code>ing errors at the end instead:</p>\n\n<pre><code>function getIPFromNextSite(urls) {\n if (!urls.length) {\n // Send control flow to the consuming .catch block:\n throw new Error('No more URLs');\n }\n const url = urls.pop();\n return fetch(url)\n .then(response => response.text())\n .then((txt) => {\n if (isValidIP(txt)) {\n // Send control flow to the consuming .then block:\n return txt;\n } else {\n return getIPFromNextSite(urls);\n }\n })\n .catch((err) => {\n return getIPFromNextSite(urls);\n });\n}\n</code></pre>\n\n<p>It's only a comment in your code, but <code>.slice</code> does not deep copy arrays - it only shallow copies them. (Since the array here contains immutable strings, a shallow copy is fine anyway.)</p>\n\n<p>If you want to follow the standard Javascript naming conventions, you could consider using <code>camelCase</code> for functions and most variables by default.</p>\n\n<p>When declaring variables, best to <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">always use <code>const</code></a>. Using <code>let</code> warns readers of the code that you may reassign the variable name, which results in more cognitive overhead (and is confusing if there isn't actually any chance of the name being reassigned).</p>\n\n<p>In full, this is how I would do it:</p>\n\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 IP_URLs = [\n 'https://api.ipify.org/',\n 'https://ipecho.net/plain',\n 'https://api.kwelo.com/v1/network/ip-address/my',\n 'https://myexternalip.com/raw',\n];\nfunction getIPFromNextSite(urls) {\n if (!urls.length) {\n // Send control flow to the consuming .catch block:\n throw new Error('No more URLs');\n }\n const url = urls.pop();\n return fetch(url)\n .then(response => response.text())\n .then((txt) => {\n if (isValidIP(txt)) {\n // Send control flow to the consuming .then block:\n return txt;\n } else {\n return getIPFromNextSite(urls);\n }\n })\n .catch((err) => {\n return getIPFromNextSite(urls);\n });\n}\nfunction isValidIP(txt) {\n return /^(?!0)(?!.*\\.$)((1?\\d?\\d|25[0-5]|2[0-4]\\d)(\\.|$)){4}$/.test(txt);\n}\nconst getIP = urls => getIPFromNextSite(urls.slice());\n\ngetIP(IP_URLs).then(console.log);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <p>Should I have used async/await?</p>\n</blockquote>\n\n<p>You could. If you need to exhaustively check every error path, it would require a lot of ugly <code>try</code>/<code>catch</code> boilerplate, but if you just want a result, it looks moderately cleaner than the version above:</p>\n\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 IP_URLs = [\n 'https://api.ipify.org/',\n 'https://ipecho.net/plain',\n 'https://api.kwelo.com/v1/network/ip-address/my',\n 'https://myexternalip.com/raw',\n];\nasync function getIPFromNextSite(urls) {\n for (const url of urls) {\n try {\n const response = await fetch(url);\n const text = await response.text();\n if (isValidIP(text)) {\n // Send control flow to the consuming .then block:\n return text;\n }\n } catch(e) {\n // Don't do anything, just continue on to next iteration\n }\n }\n // Send control flow to the consuming .catch block:\n throw new Error('No more URLs');\n}\nfunction isValidIP(txt) {\n return /^(?!0)(?!.*\\.$)((1?\\d?\\d|25[0-5]|2[0-4]\\d)(\\.|$)){4}$/.test(txt);\n}\nconst getIP = urls => getIPFromNextSite(urls);\n\ngetIP(IP_URLs).then(console.log);</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-05-06T10:11:08.730",
"Id": "241811",
"ParentId": "241807",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241811",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T08:59:02.583",
"Id": "241807",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Retrieving my public IP address with the javascript Fetch API (no jquery, no json)"
}
|
241807
|
<p>To display all the shops, I get data from a database (Firestore) and push them into array and <code>setState</code>, and use map to display shops from <code>this.state{ shops }</code>.</p>
<p>This is working okay, but I am wondering if there are better ways.</p>
<pre><code>export default class Shop extends Component {
constructor(props) {
super(props);
this.state = {
shops: [],
};
}
async componentDidMount() {
const querySnapshot = await db.mShopsCollection().get();
const shops = [];
querySnapshot.forEach((doc) => {
const shop = {
id: doc.id,
address1: doc.data().address1,
address2: doc.data().address2,
address3: doc.data().address3,
name: doc.data().name,
prefecture: doc.data().prefecture,
zip_code: doc.data().zip_code,
};
shops.push(shop);
});
this.setState({ shops });
}
render() {
const { shops } = this.state;
return (
<View>
{shops.map((shop) => (
<TouchableOpacity onPress={this.handleShowMap} key={shop.id}>
<View>
<View>
<Text>{shop.name}</Text>
<Text>
〒
{shop.zip_code}
{'\n'}
{shop.prefecture}
{shop.address1}
{shop.address2}
{'\n'}
{shop.address3}
</Text>
</View>
</TouchableOpacity>
))}
</View>
);
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T10:09:25.073",
"Id": "474515",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>There are a couple of improvements you can make in your <code>componentDidMount</code>.</p>\n\n<p>First, you create an empty array of <code>shops</code>, then push to it in every iteration over the <code>querySnapshot</code>. When constructing an array by transforming another array (or array-like collection), the appropriate method to use is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array.prototype.map</code></a>. You can get an array of documents from the snapshot by accessing its <code>.docs</code> property.</p>\n\n<p>Second, rather than calling <code>doc.data</code> many times repetitively, you can make an array of properties and extract each of them from the document being iterated over, putting them into a new object with <code>Object.fromEntries</code>:</p>\n\n<pre><code>async componentDidMount() {\n const querySnapshot = await db.mShopsCollection().get();\n const properties = ['address1', 'address2', 'address3', 'name', 'prefecture', 'zip_code'];\n const shops = querySnapshot.docs.map((doc) => {\n const data = doc.data();\n return {\n id: doc.id,\n ...Object.fromEntries(properties.map(prop => data[prop]))\n };\n });\n this.setState({ shops });\n}\n</code></pre>\n\n<p>Lodash's <a href=\"https://lodash.com/docs/4.17.15#pick\" rel=\"nofollow noreferrer\"><code>pick</code></a> is another method that can be used to extract certain properties from an object into a new object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T06:28:16.857",
"Id": "241856",
"ParentId": "241810",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T09:21:57.127",
"Id": "241810",
"Score": "2",
"Tags": [
"javascript",
"react-native"
],
"Title": "Displaying information from shops"
}
|
241810
|
<p>I have a code that adds a user to the database, getting the username from the dialog.My fragment implements the interface with the onInputSend method, which is called by the dialog when the user clicks the desired button.
Here is the code that adds the user to the database. I want to hear criticism of my code.</p>
<p>UsersActivity</p>
<pre><code> public void onInputSend(@NonNull InputTextAlertDialog dialog, @NotNull String input) {
userActionManager.isEmptyUser(input)
.doOnSubscribe(disposable -> disposables.add(disposable))
.subscribe(empty -> insertUser(dialog, input, empty));
}
private void insertUser(InputTextAlertDialog dialog, String userName, boolean isEmpty) {
if (isEmpty) {
if (!userName.trim().isEmpty()) {
userActionManager.insertUser(new User(userName));
dialog.cancel();
} else {
dialog.setErrorMessage(getString(R.string.user_not_have_name));
}
} else {
dialog.setErrorMessage(getString(R.string.user_already_exists));
}
}
</code></pre>
<p>InputTextAlertDialog</p>
<pre><code>class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {
var onInputOkListener: OnInputOkListener? = null
private var input: EditText? = null
private var error: TextView? = null
var colorError: Int = Color.RED
set(colorError: Int) {
field = colorError
error!!.setTextColor(colorError)
}
init {
error = view.findViewById(R.id.error_text)
input = view.findViewById(R.id.input)
error!!.setTextColor(colorError)
}
fun setErrorMessage(errorMessage: String?) {
error!!.text = errorMessage
input!!.backgroundTintList = ColorStateList.valueOf(colorError);
}
override fun initOkClickListener() {
ok.setOnClickListener { v: View? ->
ok()
}
}
override fun ok() {
onInputOkListener?.onInputSend(this, input!!.text.toString())
}
override fun getLayout(): Int {
return R.layout.input_text_layout
}
interface OnInputOkListener {
fun onInputSend(dialog: InputTextAlertDialog, input: String)
}
}
</code></pre>
<p>BaseAlertDialog</p>
<pre><code>public abstract class BaseAlertDialog {
AlertDialog alertDialog;
protected Button cancel;
protected Button ok;
protected View view;
private AlertDialog.Builder builder;
protected Context context;
BaseAlertDialog(Context context) {
this.context = context;
initDialog(context);
initViews(view);
initCancelClickListener();
initOkClickListener();
}
private void initDialog(Context context) {
if (getLayout() != 0) {
view = LayoutInflater.from(context).inflate(getLayout(), null);
} else {
throw new RuntimeException("In getLayout () you should return the layout id");
}
builder = new AlertDialog.Builder(context);
builder.setView(view);
alertDialog = builder.create();
}
private void initViews(View view) {
cancel = view.findViewById(R.id.cancel);
ok = view.findViewById(R.id.ok);
}
private void initCancelClickListener() {
cancel.setOnClickListener(v -> {
alertDialog.cancel();
});
}
protected void initOkClickListener() {
if (ok != null) {
ok.setOnClickListener(v -> {
ok();
alertDialog.cancel();
});
}
}
public void cancel(){
alertDialog.cancel();
}
public void show(){
alertDialog.show();
}
abstract void ok();
abstract int getLayout();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T13:47:02.807",
"Id": "474543",
"Score": "0",
"body": "I'm only here for the Kotlin... Would it be an error if the `input` or `error` would be absent?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T13:56:02.407",
"Id": "474544",
"Score": "0",
"body": "Also it seems you're missing some code in UsersActivity... (the surrounding class eg.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T14:00:35.653",
"Id": "474546",
"Score": "0",
"body": "I left here only the code that interests me for verification.input NotNull he cannot be absent.What means error would be absent?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T14:07:09.120",
"Id": "474551",
"Score": "0",
"body": "I mean should `findViewById` always find the view, or would it be ok if it didn't?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T15:37:04.147",
"Id": "474562",
"Score": "0",
"body": "ok can not be found, cancel is required"
}
] |
[
{
"body": "<h1>Nullable</h1>\n<p>Your fields are optionals: you put a <code>?</code> after the type.<br />\nThis means every time you need to access them, you need to check if it is null...<br />\nIf you want the fields to be always present, throw the NullPointerException when <code>findViewById</code> doesn't return a view.<br />\nThen you can make your field not nullable and you can remove all the (now) redundant checks...</p>\n<h1>oneline function</h1>\n<pre><code>override fun getLayout(): Int {\n return R.layout.input_text_layout\n}\n</code></pre>\n<p>This function doesn't need 3 lines of attention...<br />\nChange it to one:</p>\n<pre><code>override fun getLayout(): Int = R.layout.input_text_layout\n</code></pre>\n<p>you could remove the return-type as well:</p>\n<pre><code>override fun getLayout() = R.layout.input_text_layout\n</code></pre>\n<h1>init</h1>\n<p>Personal choice:</p>\n<p>I like to make everything as short as possible.\nThis can be done by declaring the fields straight away instead of in the init block:</p>\n<pre><code>class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {\n\n var onInputOkListener: OnInputOkListener? = null \n\n var colorError: Int = Color.RED\n set(colorError: Int) {\n field = colorError\n error!!.setTextColor(colorError)\n } \n\n\n private var input: EditText = view.findViewById(R.id.input)!!\n private var error: TextView = view.findViewById(R.id.error_text)!!\n\n init {\n error!!.setTextColor(colorError)\n }\n}\n</code></pre>\n<h2>also</h2>\n<p>We can make the code above a bit simpler by using <code>also</code>:<br />\n<code>also</code> is a function which is called upon a variable (called the receiver).<br />\n<code>also</code> will return the receiver and accepts a lambda as parameter.<br />\nInside that lambda, it gives one parameter: the receiver.<br />\nTherefor the following code:</p>\n<pre><code>class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {\n private var error: TextView = view.findViewById(R.id.error_text)!!\n\n init {\n error!!.setTextColor(colorError)\n }\n}\n</code></pre>\n<p>can be reduced to:</p>\n<pre><code>class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {\n private var error: TextView = view.findViewById(R.id.error_text)!!\n .also{ v: TextView -> v.setTextColor(colorError) }\n}\n</code></pre>\n<p>And if there is only one param, it can be accessed using it:</p>\n<pre><code>class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {\n private var error: TextView = view.findViewById(R.id.error_text)!!\n .also{ it.setTextColor(colorError) }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T08:33:29.763",
"Id": "241867",
"ParentId": "241813",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241867",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T11:03:25.760",
"Id": "241813",
"Score": "2",
"Tags": [
"java",
"strings",
"android",
"error-handling",
"kotlin"
],
"Title": "Code for adding a user to the database"
}
|
241813
|
<p>This is a matrix-vector multiplication program using multi-threading. It takes matrixfile.txt and vectorfile.txt names, buffer size, and number of splits as input and splits the matrixfile into splitfiles in main function (matrix is divided into smaller parts). Then mapper threads writes the value into buffer and reducer thread writes result into resultfile.txt. Resultfile algorithm is not efficient but the code works which I tested with various inputs. </p>
<p>I appreciate any correction and comment.</p>
<p><strong><em>Program:</em></strong></p>
<pre><code>/* -*- linux-c -*- */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <pthread.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <semaphore.h>
#include "common.h"
#include "stdint.h"
const int ROWS = 10000;
const int COLS = 3;
int twodimen[10000][3];
int count_lines;
int vector[10000];
int vector_lines;
int NUMBER_OF_ROWS;
int splitnum;
int INPUT_BUF_SIZE;
sem_t *sem_mutex; /* protects the buffer */
sem_t *sem_full; /* counts the number of items */
sem_t *sem_empty; /* counts the number of empty buffer slots */
void * mapperThread(void * xx){
int filecount = (intptr_t)xx;
char filename[20] = "splitfile";
char txt[5] = ".txt";
char num[10];
sprintf(num, "%d", filecount);
strcat(filename, num);
strcat(filename, txt);
printf ("mapper thread started with: %s \n", filename);
struct buffer * bp = find(filecount);
// OPENING SPLIT FILE
FILE *splitfileptr;
char *sline = NULL;
size_t slen = 0;
ssize_t sread;
splitfileptr = fopen(filename, "r");
if (splitfileptr == NULL){
exit(EXIT_FAILURE);
}
while ((sread = getline(&sline, &slen, splitfileptr)) != -1) {
char *line_copy = strdup(sline);
if (SYNCHRONIZED) {
sem_wait(sem_empty);
sem_wait(sem_mutex);
// CRITICAL SECTION BEGIN
bp->buf[bp->in] = line_copy;
bp->count = bp->count + 1;
bp->in = (bp->in + 1) % INPUT_BUF_SIZE; // incrementing buffer count, updating
// CRITICAL SECTION END
sem_post(sem_mutex); // releasing the mutex
sem_post(sem_full); // incrementing full count, sem_post is signal operation
}
}
printf("producer ended; bye...\n");
pthread_exit(0);
}
void * reducerThread(char* resultfilename){
printf("reducer thread started\n");
FILE *resultfileptr;
char *line = NULL;
size_t len = 0;
ssize_t read;
char* item;
int index = 0;
while (index < count_lines) {
for(int i = 0; i < splitnum; i++){
struct buffer * bp = find(i);
if (SYNCHRONIZED && bp->count != 0) {
sem_wait(sem_full); // checks whether buffer has item to retrieve, if full count = 0, this statement will cause consumer to wait
sem_wait(sem_mutex); // makes sure when we are executing this section no other process executes at the buffer
// CRITICAL SECTION BEGIN
item = bp->buf[bp->out]; // just retrieving the buffer. putting into item.
bp->count = bp->count - 1;
bp->out = (bp->out + 1) % INPUT_BUF_SIZE; // updating out index variable, this is a circular bufer
index++;
printf("retrieved item is: %s", item);
twodimen[atoi(&item[0]) - 1][0] = atoi(&item[0]);
twodimen[atoi(&item[0]) - 1][2] = twodimen[atoi(&item[0]) - 1 ][2] + atoi(&item[4]) * vector[atoi(&item[2]) - 1];
// CRITICAL SECTION END
sem_post(sem_mutex); //
sem_post(sem_empty); // number of empty cells in the buffer should be 1 more. incrementing empty size.
}
}
}
// WRITING TO RESULTFILE
resultfileptr = fopen(resultfilename, "w+");
for(int i = 0; i < NUMBER_OF_ROWS; i++){
for(int j = 0; j < COLS; j++){
if(twodimen[i][j] != 0 && twodimen[i][j + 2] != 0){
char str[10];
sprintf(str, "%d %d \n", twodimen[i][j], twodimen[i][j + 2]);
fprintf(resultfileptr, "%s", str);
}
}
}
printf("consumer ended; bye...\n");
fflush (stdout);
pthread_exit(NULL);
}
int main(int argc, char**argv)
{
clock_t start_time = clock();
const char *const matrixfilename = argv[1];
const char *const vectorfilename = argv[2];
const char *const resultfilename = argv[3];
const int K = atoi(argv[4]);
INPUT_BUF_SIZE = atoi(argv[5]);
splitnum = K;
printf ("mv started\n");
printf ("%s\n", matrixfilename);
printf ("%s\n", vectorfilename);
printf ("%s\n", resultfilename);
printf ("K is %d\n", K);
printf ("splitnum is %d\n", splitnum);
printf ("INPUT_BUF_SIZE is %d\n", INPUT_BUF_SIZE);
if(INPUT_BUF_SIZE > BUFSIZE || INPUT_BUF_SIZE < 100){
printf("Buffer input should be between 100 and 10000, BUFSIZE = 10000 will be used as default \n");
INPUT_BUF_SIZE = BUFSIZE;
}
FILE *fileptr;
count_lines = 0;
char filechar[10000], chr;
fileptr = fopen(matrixfilename, "r");
// extract character from file and store it in chr
chr = getc(fileptr);
while(chr != EOF)
{
// count whenever new line is encountered
if(chr == '\n')
{
count_lines = count_lines + 1;
}
// take next character from file
chr = getc(fileptr);
}
printf("countlines is %d \n", count_lines);
fclose(fileptr); // close file
printf("There are %d lines in in a file\n", count_lines);
int s = count_lines / K;
int remainder = count_lines % K;
printf("S is %d \n", s);
FILE *fw, *fr;
char *line = NULL;
size_t len = 0;
ssize_t read;
// CREATING SPLIT FILES AND WRITING TO THEM
for(int i = 0; i < K; i++){
char filename[20] = "splitfile";
char txt[5] = ".txt";
char its[10];
sprintf(its, "%d", i);
strcat(filename, its);
strcat(filename, txt);
fw = fopen(filename, "w+");
fr = fopen(matrixfilename, "r");
if(i == K - 1){
for(int j = 0; j < count_lines; j++){
while(((read = getline(&line, &len, fr)) != -1) && j >= (i * s)){
char *line_copy = strdup(line);
fprintf(fw, "%s", line_copy);
j++;
}
}
}
else{
for(int j = 0; j < count_lines; j++){
while(((read = getline(&line, &len, fr)) != -1) && j >= (i * s) && j <= (i + 1) * s - 1){
char *line_copy = strdup(line);
fprintf(fw, "%s", line_copy);
j++;
}
}
}
fclose(fw);
fclose(fr);
}
FILE *vectorfileptr;
vector_lines = 0;
char vchr;
vectorfileptr = fopen(vectorfilename, "r");
vchr = getc(vectorfileptr);
line = NULL;
len = 0;
// COUNTING THE SIZE OF VECTOR
while(vchr != EOF)
{
// count whenever new line is encountered
if(vchr == '\n')
{
vector_lines = vector_lines + 1;
}
// take next character from file
vchr = getc(vectorfileptr);
}
fclose(vectorfileptr);
printf("There are %d lines in vector file\n", vector_lines);
vector[vector_lines];
vectorfileptr = fopen(vectorfilename, "r");
if (vectorfileptr == NULL)
exit(EXIT_FAILURE);
int linenumber = 0;
while ((read = getline(&line, &len, vectorfileptr)) != -1) {
char *line_copy = strdup(line);
vector[linenumber] = atoi(line_copy);
linenumber++;
}
fclose(vectorfileptr);
for(int i = 0; i < vector_lines; i++){
printf("vector %d: %d\n", i, vector[i]);
}
FILE *countfileptr;
countfileptr = fopen(matrixfilename, "r");
NUMBER_OF_ROWS = 0;
while ((read = getline(&line, &len, countfileptr)) != -1) {
char *line_copy = strdup(line);
if(atoi(&line_copy[0]) > NUMBER_OF_ROWS){
NUMBER_OF_ROWS = atoi(&line_copy[0]);
}
}
fclose(countfileptr);
/* first clean up semaphores with same names */
sem_unlink (SEMNAME_MUTEX);
sem_unlink (SEMNAME_FULL);
sem_unlink (SEMNAME_EMPTY);
/* create and initialize the semaphores */
sem_mutex = sem_open(SEMNAME_MUTEX, O_RDWR | O_CREAT, 0660, 1);
if (sem_mutex < 0) {
perror("can not create semaphore\n");
exit (1);
}
printf("sem %s created\n", SEMNAME_MUTEX);
sem_full = sem_open(SEMNAME_FULL, O_RDWR | O_CREAT, 0660, 0);
if (sem_full < 0) {
perror("can not create semaphore\n");
exit (1);
}
printf("sem %s created\n", SEMNAME_FULL);
sem_empty = sem_open(SEMNAME_EMPTY, O_RDWR | O_CREAT, 0660, BUFSIZE); // initially bufsize items can be put
if (sem_empty < 0) {
perror("can not create semaphore\n");
exit (1);
}
printf("sem %s create\n", SEMNAME_EMPTY);
for(int i = 0; i < splitnum; i++){
insertFirst(0,0,0,i);
}
int err;
pthread_t tid[splitnum];
printf ("starting thread\n");
for(int i = 0; i < splitnum; i++){
err = pthread_create(&tid[i], NULL, (void*) mapperThread, (void*)(intptr_t)i);
if(err != 0){
printf("\n Cant create thread: [%s]", strerror(err));
}
}
pthread_t reducertid;
pthread_create(&reducertid, NULL, (void*) reducerThread, (char*) resultfilename);
for(int i = 0; i < splitnum; i++){
pthread_join(tid[i],NULL);
}
pthread_join(reducertid,NULL);
// join reducer thread
// closing semaphores
sem_close(sem_mutex);
sem_close(sem_full);
sem_close(sem_empty);
/* remove the semaphores */
sem_unlink(SEMNAME_MUTEX);
sem_unlink(SEMNAME_FULL);
sem_unlink(SEMNAME_EMPTY);
fflush( stdout );
exit(0);
}
</code></pre>
<p><strong><em>HEADER file:</em></strong></p>
<pre><code>/* -*- linux-c -*- */
#ifndef COMMON_H
#define COMMON_H
#define TRACE 1
#define SEMNAME_MUTEX "/name_sem_mutex"
#define SEMNAME_FULL "/name_sem_fullcount"
#define SEMNAME_EMPTY "/name_sem_emptycount"
#define ENDOFDATA -1 // marks the end of data stream from the producer
// #define SHM_NAME "/name_shm_sharedsegment1"
#define BUFSIZE 10000 /* bounded buffer size */
#define MAX_STRING_SIZE
// #define NUM_ITEMS 10000 /* total items to produce */
/* set to 1 to synchronize;
otherwise set to 0 and see race condition */
#define SYNCHRONIZED 1 // You can play with this and see race
struct buffer{
struct buffer *next;
char * buf[BUFSIZE]; // string array
int count; /* current number of items in buffer */
int in; // this field is only accessed by the producer
int out; // this field is only accessed by the consumer
int source; // index of the producer
};
struct buffer *head = NULL;
struct buffer *current = NULL;
void printList(){
struct buffer *ptr = head;
while(ptr != NULL){
printf("items of buffer %d: \n", ptr->source);
printf("buffer count is : %d \n", ptr->count);
printf("buffer in is : %d \n", ptr->in);
printf("buffer out is : %d \n", ptr->out);
for(int i = 0; i < ptr->count; i++){
printf("%s", ptr->buf[i]);
}
ptr = ptr->next;
}
}
void insertFirst(int count, int in, int out, int source){
struct buffer *link = (struct buffer*) malloc(sizeof(struct buffer));
for(int i = 0; i < BUFSIZE; i++){
link->buf[i] = "";
}
link->count = count;
link->in = in;
link->out = out;
link->source = source;
link->next = head;
head = link;
}
struct buffer* find(int source){
struct buffer* current = head;
if(head == NULL){
return NULL;
}
while(current->source != source){
if(current->next == NULL){
return NULL;
}
else{
current = current->next;
}
}
return current;
}
#endif
</code></pre>
|
[] |
[
{
"body": "<p>A few semi-random observations.</p>\n\n<p>You define functions in your header file, so if you include that in multiple source files in one project you'll get multiple definition errors from the linker. (Also, those functions are using standard library functions without including the required header files.)</p>\n\n<p><code>main</code> makes assumptions about the number of parameters passed to the program. If you don't pass enough, you'll dereference a NULL or out-of-bounds pointer (e.g., an invalid value for <code>argv[5]</code>). You should verify that you have enough parameters (by checking <code>argc</code>) before attempting to access any of the parameters.</p>\n\n<p>Rather than the verbose <code>count_lines = count_lines + 1;</code>, you can just use <code>++count_lines;</code>.</p>\n\n<p>Your code for building the split filename is nearly identical in the two places you use it. You can put it in a function to avoid the duplication, and simplify it by using <code>sprintf</code> to build the entire filename rather than using <code>sprintf</code> and <code>strcat</code>.</p>\n\n<pre><code>sprintf(buf, \"splitfile%d.txt\", n);\n</code></pre>\n\n<p>where <code>buf</code> and <code>n</code> are passed as parameters to the function. <code>buf</code> should be long enough to hold any value for <code>n</code>, 9 + 4 + 1 + 11 = 25 characters, assuming <code>n</code> is no larger than 32 bits. (That's 9 bytes for the base filename, 4 for the extension, 1 for the terminating nul, and 11 for a signed 32 bit integer printed as a decimal.)</p>\n\n<p>You don't verify that <code>fw</code> and <code>fr</code> (and some of your other file handles) have successfully been opened before making use of them.</p>\n\n<p>Most of your <code>strdup</code> calls will leak, and are not necessary.</p>\n\n<p>At one point in <code>main</code> you call <code>atoi(&line_copy[0])</code> twice - one inside an <code>if</code>, and once in the following statement. This should be called once, stored in a local variable:</p>\n\n<pre><code>int nr = atoi(line_copy);\nif (nr > NUMBER_OF_ROWS)\n NUMBER_OF_ROWS = nr;\n</code></pre>\n\n<p><code>reducerThread</code> will be an infinite loop if <code>SYNCHRONIZED</code> is 0.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T03:30:54.750",
"Id": "241848",
"ParentId": "241818",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241848",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T12:27:00.400",
"Id": "241818",
"Score": "3",
"Tags": [
"c",
"multithreading",
"thread-safety"
],
"Title": "C code using process synchronization and multi-threading"
}
|
241818
|
<p>I have been shifting all of my SQL queries to prepared statements in the past few weeks and all of the INSERT statements run extremely fast, however, UPDATE is taking an inordinate amount of time. At present, I am adding to the prepared statement then sending. Updating 20 records can take over two minutes sometimes. Here is my code:</p>
<pre><code>if (updatePhoneList.elements().size()>0) {
LOGGER.info("Will process " + updatePhoneList.elements().size() + " records");
Date startDate = new Date();
try {
String compiledQuery = "UPDATE CUSTDATA.CUST_CONTACT_INFO SET CBR = ?, LAST_UPDATED_TIME = SYSDATE "
+ "WHERE ORDER_ID = ? AND CUSTNUM = ?";
PreparedStatement bulkInsertStatement = dbConnection.prepareStatement(compiledQuery);
for(int arrayPos = 0; arrayPos <= updatePhoneList.elements().size() -1 ; arrayPos++) {
currentCust = updatePhoneList.elements().get(arrayPos).prop("CUSTNUM").stringValue();
currentPhone = updatePhoneList.elements().get(arrayPos).prop("CUSTPHONE").stringValue();
bulkInsertStatement.setString(1, currentPhone);
bulkInsertStatement.setString(2, currentCust);
bulkInsertStatement.setString(3, outageId);
}
updatedRecords = bulkInsertStatement.executeBatch();
bulkInsertStatement.close();
Date endDate = new Date();
long execTimeMSec = (endDate.getTime()-startDate.getTime());
LOGGER.info("Returning success: " + success);
} catch (Exception e) {
success = false;
}
}
</code></pre>
<p>When I wrote this , I had no indices, but indexed the CUST_CONTACT_INFO to index on ORDER_ID and CUSTNUM. It runs markedly faster.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T22:32:24.037",
"Id": "474594",
"Score": "4",
"body": "Is this UPDATE or INSERT code? `updatePhoneList` suggests the former, but `bulkInsertStatement` the latter. What is the SQL statement? How is the table defined? What keys, indexes, constraints are defined? Just not enough detail here to answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T06:02:53.603",
"Id": "474739",
"Score": "1",
"body": "You lament the performance of a `compiledQuery` without so much as showing it. Please add relevant parts of the schema (including indexes) and the *execution plan*, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T13:46:32.063",
"Id": "475077",
"Score": "0",
"body": "Your changes are a step in the right direction, but I don't think all comments have been addressed."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T14:21:32.277",
"Id": "241822",
"Score": "1",
"Tags": [
"java",
"beginner",
"sql"
],
"Title": "Slow updates with updating rows in database with preparedStatement"
}
|
241822
|
<p>This is my first Python web scraper (and overall my first Python project). I am also relatively new to OOP but do understand its core fundamentals. The script below scrapes two local news sites for their daily weather / allergy forecasts and converts it into an HTML file which opens locally in my browser. The file path also has a CSS file to style the output. </p>
<p>I know this code is not clean, and that it's not object oriented. Nothing is abstracted away into a function. I know that would be best practice, but I don't know enough to know <em>how</em> to clean it up. Any and all suggestions are very welcome.</p>
<pre><code>
import requests
from bs4 import BeautifulSoup
import urllib.request
from PIL import Image
import webbrowser, os
kxanUrl = 'https://www.kxan.com/weather/forecast/todays-forecast/'
kxanPage = requests.get(kxanUrl)
kvueUrl = 'https://www.kvue.com/allergy'
kvuePage = requests.get(kvueUrl)
soup = BeautifulSoup(kxanPage.content, 'html.parser')
weatherHtmlData = soup.find("div", {"class": "article-content rich-text"})
weatherText = weatherHtmlData.get_text()
tempHighHtml = soup.find('span', {"class": "high"})
tempHigh = tempHighHtml.get_text()
tempLowHtml = soup.find('span', {"class": "low"})
tempLow = tempLowHtml.get_text()
allergyImage = urllib.request.urlretrieve("http://cdn.tegna-media.com/kvue/weather/allergy16x9.jpg", "allergy_forecast.jpg")
image = Image.open("allergy_forecast.jpg")
template = """<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Daily Austin Forecast</title>
</head>
<body>
<h1>Weather <span class="text-primary">Forecast</span></h1>
<div>
Today's High: tempHigh | Today's Low: tempLow
<br>
<br>
FORECAST_INFORMATION
</div>
<h1>Allergy <span class="text-primary">Forecast</span></h1>
<img src="allergy_forecast.jpg"></img>
</body>
</html>"""
template = template.replace("FORECAST_INFORMATION", str(weatherText))
template = template.replace("tempHigh", str(tempHigh))
template = template.replace("tempLow", str(tempLow))
with open("forecast.html", "w") as file:
file.write(template)
webbrowser.open('file://' + os.path.realpath("forecast.html"))
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T15:57:38.100",
"Id": "241825",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"web-scraping"
],
"Title": "Scraping local news sites"
}
|
241825
|
<p>Since Python 3.6 and <a href="https://www.python.org/dev/peps/pep-0525/" rel="nofollow noreferrer">PEP 525</a> one can use <a href="https://docs.python.org/3/glossary.html#term-asynchronous-generator" rel="nofollow noreferrer">asynchronous generator</a>:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
async def asyncgen():
yield 1
yield 2
async def main():
async for i in asyncgen():
print(i)
asyncio.run(main())
</code></pre>
<p>I created a function which is able to wrap any asynchronous generator, the same way you would wrap a basic function using <code>@decorator</code>.</p>
<pre class="lang-py prettyprint-override"><code>def asyncgen_wrapper(generator):
async def wrapped(*args, **kwargs):
print("The wrapped asynchronous generator is iterated")
gen = generator(*args, **kwargs)
try:
value = await gen.__anext__()
except StopAsyncIteration:
return
while True:
to_send = yield value
try:
value = await gen.asend(to_send)
except StopAsyncIteration:
return
return wrapped
</code></pre>
<p>Wrapping an asynchronous generator seems quite complicated compared to wrapping a basic generator:</p>
<pre class="lang-py prettyprint-override"><code>def gen_wrapper(generator):
def wrapped(*args, **kwargs):
return (yield from generator(*args, **kwargs))
return wrapped
</code></pre>
<p>I mainly concerned about <strong>correctness</strong> of my wrapper. I want the wrapper to be as transparent as possible regarding the wrapped generator. Which leads me to have two questions:</p>
<ul>
<li>Is there a more straightforward way to implement a decorator for asynchronous generators?</li>
<li>Does my implementation handle all possible edge cases (think to <code>asend()</code> for example)?</li>
</ul>
|
[] |
[
{
"body": "<p>\"Correct\" is nebulous. If it were to mean here something like \"the semantics of any wrapped generator through the public API is the same as if it were not wrapped, apart from a print statement before the generator is created\", then, no, the code isn't correct since it doesn't preserve the effects of raising an exception or closing the generator. For example,</p>\n\n<pre><code>import asyncio\n\nclass StopItNow( Exception ): \n pass\n\nasync def f():\n try:\n yield 0\n except StopItNow:\n yield 1\n\nasync def g( f ): \n x = f()\n print( await x.asend( None ) )\n print( await x.athrow( StopItNow ) )\n\nasyncio.run( g( f ) )\nasyncio.run( g( asyncgen_wrapper( f ) ) )\n</code></pre>\n\n<p>. I think it would be a non-trivial undertaking to \"correctly\" implement a wrapper. Interestingly, in the same PEP (525) that you've linked in your question,</p>\n\n<blockquote>\n <p>While it is theoretically possible to implement yield from support for asynchronous generators, it would require a serious redesign of the generators implementation.</p>\n</blockquote>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0525/#asynchronous-yield-from\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0525/#asynchronous-yield-from</a></p>\n\n<p>. You might find that it's a whole lot easier to implement some sort of injection or parameterise the generator itself to accept callables.</p>\n\n<p>Otherwise, from my experimentation and taking hints from <a href=\"https://www.python.org/dev/peps/pep-0380/#formal-semantics\" rel=\"nofollow noreferrer\">PEP 380</a>, there are implementation details that are omitted from PEP 525 that would be necessary to emulate the behaviour of an unwrapped generator.</p>\n\n<p>This is the result of some toying around:</p>\n\n<pre><code>import functools\nimport sys\n\ndef updated_asyncgen_wrapper( generator ): \n\n @functools.wraps( generator )\n async def wrapped( *args, **kwargs ): \n print( \"iterating wrapped generator\" )\n\n gen = generator( *args, **kwargs )\n to_send, is_exc = ( None, ), False\n\n while True:\n try:\n do = gen.athrow if is_exc else gen.asend\n value = await do( *to_send )\n except StopAsyncIteration:\n return\n try:\n to_send, is_exc = ( (yield value), ), False\n except GeneratorExit:\n await gen.aclose()\n raise\n except:\n to_send, is_exc = sys.exc_info(), True\n\n return wrapped\n</code></pre>\n\n<p>. This isn't \"correct\" either, since it doesn't disambiguate between an attempt to close the generator and an explicit throw of an instance of <code>GeneratorExit</code>, which is, though, marked distinctly for usage by the <a href=\"https://docs.python.org/3/library/exceptions.html#GeneratorExit\" rel=\"nofollow noreferrer\">former case</a>. This <em>might</em> be <em>good enough</em> for internal use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:38:08.057",
"Id": "241906",
"ParentId": "241829",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241906",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T17:09:53.650",
"Id": "241829",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"asynchronous",
"async-await",
"generator"
],
"Title": "Wrapping an asynchronous generator in Python"
}
|
241829
|
<p>I have a panel that has 4 images per row and a lot of rows. Each image has a 15 pixels separation and are 250,250 each.</p>
<p>Here is a screenshot:</p>
<p><a href="https://i.stack.imgur.com/YUuB5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YUuB5.jpg" alt="enter image description here"></a></p>
<p>I'd like to be able to click on a picture and identify the image number (from 0 top left to the right). Of course, avoiding the separation.</p>
<pre><code> protected override void OnMouseClick(MouseEventArgs e)
{
vsValue = VerticalScroll.Value;
// what row ?
double ScrollVposition = vsValue + e.Y;
double row = Math.Floor(ScrollVposition / (BitmapHeight + BitmapSpacing)); // it's the right row, unless i clicked on the spacing
int topEdge = ((BitmapHeight + BitmapSpacing) * (int)row) + BitmapSpacing; // the Y coordinate of the top of the image
int bottomEdge = topEdge + BitmapHeight; // the bottom of that same image
if (ScrollVposition < bottomEdge && ScrollVposition > topEdge) // check if the click happens between the top and the bottom of the image
{ } // row is the right row number
else row = -1; // not an image
// what column ? same logic as the row
double width = e.X;
double col = Math.Floor(width / (BitmapWidth + BitmapSpacing));
col = Math.Min(col, perCol-1); // got space after the last col on the right
int leftEdge = ((BitmapWidth + BitmapSpacing) * (int)col) + BitmapSpacing;
int rightEdge = leftEdge + BitmapWidth;
int ima;
if (width < rightEdge && width > leftEdge && row >= 0)
ima = ((int)row * perCol) + (int)col;
else ima = -1;
picture_id = ima;
base.OnMouseClick(e);
}
</code></pre>
<p>Do you think I can improve it?</p>
<p>EDIT : Here is the paint event :</p>
<pre><code> base.OnPaint(e);
e.Graphics.TranslateTransform(this.AutoScrollPosition.X,
this.AutoScrollPosition.Y);
First_id = getTopPictureId(VerticalScroll.Value);
int buffer = 20;
int limithaute = Math.Min(First_id + buffer, fp.Count());
for (int i = First_id; i < limithaute; i++) //
{
System.Drawing.Image img = GetImage(fp[i]);
e.Graphics.DrawImage(img, new PointF(BitmapSpacing + (BitmapSpacing * (i % perCol) + (BitmapWidth * (i % perCol))),
BitmapSpacing + (BitmapSpacing * (i / perCol)) + (BitmapHeight * (i / perCol))));
}
</code></pre>
<p>A bit of explanation, the for loop goes through the images i'd like to show (the list of 3000+ total, the scrolling have a disposition process). Fp is the list of files that contains the images.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T01:19:41.633",
"Id": "474595",
"Score": "0",
"body": "How are you showing the image? If you use a `Picturebox`, you can handle the `MouseClick` event directly instead of all those calculations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T07:07:37.113",
"Id": "474604",
"Score": "0",
"body": "no i'm overriding the paint event with drawimage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T07:15:21.970",
"Id": "474605",
"Score": "1",
"body": "Is directly drawing them necessary? A `PictureBox` would make your life a lot easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T09:41:15.533",
"Id": "474612",
"Score": "0",
"body": "@tinstaafl: Sounds like a good answer to me!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T09:42:03.657",
"Id": "474613",
"Score": "0",
"body": "Since it seems to matter how you draw your images, it might make ssense to include some code regarding that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T10:50:33.550",
"Id": "474621",
"Score": "0",
"body": "done. the pictureBox idea is problematic as i'm drawing these pictures on the fly. i'm showing 12 and the buffer of drawn images is 20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T13:38:45.163",
"Id": "474663",
"Score": "0",
"body": "Please add the necessary tags to identify whether this is WPF, WinForms etc. We need context."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T21:47:58.020",
"Id": "241839",
"Score": "3",
"Tags": [
"c#",
"winforms"
],
"Title": "Identify clickable area in a big panel"
}
|
241839
|
<p>I am making a C# console maths test where the user answers maths questions.</p>
<p>I am trying to add a timer to the test, I have managed to make a timer but when I run my code it becomes a mess!</p>
<p>Here is some example code:</p>
<pre><code>class Program
{
public static OtherCode()
{
\\*other code for test
}
public class Timer
{
public static int Timers(int timeLeft)
{
do
{
Console.Write("\rtimeLeft: {0} ", timeLeft);
timeLeft--;
Thread.Sleep(1000);
} while (timeLeft > 0);
Console.Write(Environment.NewLine);
return timeLeft;
}
}
public static void Main(string[] args)
{
int numberOfSeconds = 30;
Thread thread = new Thread(new ThreadStart(() => {
TimerClass.Timers(numberOfSeconds);
}));
thread.Start();
\\other code
OtherCode();
}
}
</code></pre>
<p>Here is my full code:
<a href="https://github.com/CrazyDanyal1414/mathstester" rel="nofollow noreferrer">https://github.com/CrazyDanyal1414/mathstester</a></p>
<p>This is what it looks like when I run the code and try to type an answer to a question:
<a href="https://i.stack.imgur.com/8kxl3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8kxl3.png" alt="enter image description here"></a></p>
<p>As you can see my timer code is overlapping my question code.</p>
<p>If I use Console.SetCursorPosition(), my timer doesn't move but When I try to type an answer to a maths question my code makes me write it on the same line as the timer like so:<a href="https://i.stack.imgur.com/c4U0M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c4U0M.png" alt="enter image description here"></a></p>
<p>Any help appreciated!</p>
|
[] |
[
{
"body": "<p>Several things:</p>\n\n<ul>\n<li>When doing multi-processing and sharing a resource (in this case, the console window), you should use locks to prevent two threads using the same resource at once. This is the source of your problems. When updating the counter you probably need to hold the lock while moving the cursor to the timer, change the timer string, and hold it until you set the cursor back to the bottom of the console. On the other thread you'd have to maintain the lock while reading user input.</li>\n<li>You don't need to roll-your-own timers. You can use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netcore-3.1\" rel=\"nofollow noreferrer\">.NET's Timer class</a>. Notice that <a href=\"https://stackoverflow.com/a/1303708/6104191\"><code>Thread.Sleep()</code> is not accurate</a> and you're not really counting seconds (even if you roll-your-own than you should probably do it with time deltas and not with thread sleeps).</li>\n<li>Don't use the <code>Thread</code> class, use the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl\" rel=\"nofollow noreferrer\">Task Parallel Library class</a>. It'll be much easier. You will need to use <code>Task.Delay</code> instead of <code>Thread.Sleep</code></li>\n<li>Notice that you're line-breaking outside of the loop and not inside. Also <code>WriteLine</code> will add a line-break at the end automatically</li>\n</ul>\n\n<p>If you're merely learning the language (I noticed the \"beginner\" tag) than I suggest you learn the points I've mentioned. They're more important than learning a specific (and somewhat advanced) use case of C# console applications where you change text while accepting user input. I believe it would be easier for you if it would be a simple WPF application instead of a console application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:16:20.263",
"Id": "241879",
"ParentId": "241841",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T23:20:23.797",
"Id": "241841",
"Score": "1",
"Tags": [
"c#",
"beginner",
"timer"
],
"Title": "Run a timer while waiting for user input"
}
|
241841
|
<p>I've been working on a program that automates the painful task of downloading each file from a website for courses one by one and sorting them using python. This is my first python webscraping project on this scale, as such I would love some advice and lessons on how to make my code better! <a href="https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/" rel="nofollow noreferrer">Here</a> is the website I'm scraping.</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
import time
import os
import shutil
import re
path = r'https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/'
# For changing the download location for this browser temporarily
options = webdriver.ChromeOptions()
preferences = {"download.default_directory": r"E:\Utilities_and_Apps\Python\MY PROJECTS\Test data\Downloads", "safebrowsing.enabled": "false"}
options.add_experimental_option("prefs", preferences)
# Acquire the Course Link and Get all the directories
browser = webdriver.Chrome(chrome_options=options)
browser.get(r"https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/")
time.sleep(2)
elements = browser.find_elements_by_css_selector(".mdui-text-truncate")
# loop for as many directories there are
for i in range(15, len(elements)):
# At each directory, it refreshes the page to update the webelements in the list, and returns the current directory that is being worked on
browser.get(path)
time.sleep(2)
elements = browser.find_elements_by_css_selector(".mdui-text-truncate")
element = elements[i]
# checks if the folder for the directory already exists
current_directory_name = element.text[11:].strip(" .")
current_folder_path = "E:\\Utilities_and_Apps\\Python\\MY PROJECTS\\Test data\Downloads\\" + current_directory_name
if os.path.exists(current_folder_path):
pass
else:
os.mkdir(current_folder_path)
# Formatting what has been downloaded and sorted, and
print(current_directory_name, "------------------------------", sep="\n")
# moves on to the directory to get the page with the files
element.click()
# pausing for a few secs for the page to load, and running the same mechanism to get each file using the same method used in directory
time.sleep(3)
files = browser.find_elements_by_css_selector(".mdui-text-truncate")
for j in range(len(files)):
files = browser.find_elements_by_css_selector(".mdui-text-truncate")
_file = files[j]
# constants for some if statements
download = True
move = True
current_file_name = _file.text[17:].strip()
# If file exists, then pass over it, and don't do anything, and moveon to next file
if os.path.exists(current_folder_path + "\\" + current_file_name):
pass
# If it doesnt exist, then depending on its extension, do specific actions with it
else:
# Downloads the mp4 files by clicking on it, and finding the input tag which contains the download link for vid in its value attribute
if ".mp4" in current_file_name:
_file.click()
time.sleep(2)
download_path = browser.find_element_by_css_selector("input").get_attribute("value")
current_file_name = re.search(r'https://coursevania.courses.workers.dev/\[coursevania.com\]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20\+%20Algorithms/.+/(.+)', download_path, re.DOTALL).group(1)
# Checks if file exists again, incase the filename is different then the predicted filename orderly generated.
if os.path.exists(current_folder_path + "\\" + current_file_name):
move = False
download = False
# returns to the previous page with the files
browser.back()
# self explanatory
elif ".html" in current_file_name:
download_path = path + current_directory_name + "/" + current_file_name
if os.path.exists(current_folder_path + "\\" + current_file_name):
move = False
download = False
else:
# acquires the download location by going to the parent tag which is an a tag containing the link for html in its 'href' attribute
download_path = _file.find_element_by_xpath('..').get_attribute('href').replace(r"%5E", "^")
current_file_name = re.search(r'https://coursevania.courses.workers.dev/\[coursevania.com\]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20\+%20Algorithms/.+/(.+)', download_path, re.DOTALL).group(1).replace("%20", " ")
time.sleep(2)
current_file_path = "E:\\Utilities_and_Apps\\Python\\MY PROJECTS\\Test data\Downloads\\" + current_file_name
# responsible for downloading it using a path, get allows downloading, by source links
if download:
browser.get(download_path)
# while the file doesn't exist/ it hasn't been downloaded yet, do nothing
while True:
if os.path.exists(current_file_path):
break
time.sleep(1)
# moves the file from the download spot to its own folder
if move:
shutil.move(current_file_path, current_folder_path + "\\" + current_file_name)
print(current_file_name)
# formatter
print("------------------------------", "", sep="\n")
time.sleep(3)
</code></pre>
<p>Output:</p>
<pre><code>1. Introduction
------------------------------
1. How To Succeed In This Course.mp4
1. How To Succeed In This Course.vtt
1.1 Interview Mind Map.html
1.2 Technical Interview Mind Map.html
2. Join Our Online Classroom!.html
3. Exercise Meet The Community!.html
------------------------------
10. Data Structures Trees
------------------------------
1. Trees Introduction.mp4
1. Trees Introduction.vtt
1.1 Technical Interview Mind Map.html
10. Solution lookup().mp4
10. Solution lookup().vtt
10.1 Solution Code.html
11. Bonus Exercise remove().mp4
11. Bonus Exercise remove().vtt
11.1 Exercise Repl.html
11.2 Binary Search Tree VisuAlgo.html
12. Solution remove().mp4
12. Solution remove().vtt
12.1 Solution Code.html
13. AVL Trees + Red Black Trees.mp4
13. AVL Trees + Red Black Trees.vtt
14. Resources AVL Trees + Red Black Trees.html
15. Binary Heaps.mp4
15. Binary Heaps.vtt
15.1 VisuAlgo Binary Heap.html
16. Quick Note on Heaps.mp4
16. Quick Note on Heaps.vtt
16.1 A great explanation of why.html
17. Priority Queue.mp4
17. Priority Queue.vtt
17.1 Priority Queue Javascript Code.html
18. Trie.mp4
18. Trie.vtt
19. Tree Review.mp4
19. Tree Review.vtt
19.1 Technical Interview Mind Map.html
2. Binary Trees.mp4
2. Binary Trees.vtt
3. O(log n).mp4
3. O(log n).vtt
4. Correction Binary Search Trees.html
5. Binary Search Trees.mp4
5. Binary Search Trees.vtt
5.1 Binary Search Tree VisuAlgo.html
6. Balanced VS Unbalanced BST.mp4
6. Balanced VS Unbalanced BST.vtt
6.1 Big O Cheat Sheet.html
7. BST Pros and Cons.mp4
7. BST Pros and Cons.vtt
8. Exercise Binary Search Tree.mp4
8. Exercise Binary Search Tree.vtt
8.1 Exercise Repl.html
9. Solution insert().mp4
9. Solution insert().vtt
9.1 Solution Code.html
------------------------------
... To Be Continued
</code></pre>
|
[] |
[
{
"body": "<p>Nice.</p>\n\n<p>Alas I don't have enough time for a comprehensive review so I will not refactor your whole code. Instead I will just focus on a few points.</p>\n\n<p>First of all, I would add a few <strong>constants</strong> (written as UPPERCASE) for more flexibility and to avoid <strong>repetition</strong>:</p>\n\n<pre><code>ROOT_URL = r'https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/'\n</code></pre>\n\n<p>The path: <code>\"E:\\\\Utilities_and_Apps\\\\Python\\\\MY PROJECTS\\\\Test data\\Downloads\\\\\"</code> appears multiple times in your code, this is unnecessary.\nAdd another constant:</p>\n\n<pre><code>DOWNLOAD_PATH = \"E:\\\\Utilities_and_Apps\\\\Python\\\\MY PROJECTS\\\\Test data\\Downloads\\\"\n</code></pre>\n\n<hr>\n\n<p>The DOM selection method could be improved because you use a mix of Selenium and regex:</p>\n\n<pre><code>download_path = browser.find_element_by_css_selector(\"input\").get_attribute(\"value\")\ncurrent_file_name = re.search(r'https://coursevania.courses.workers.dev/\\[coursevania.com\\]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20\\+%20Algorithms/.+/(.+)', download_path, re.DOTALL).group(1)\n</code></pre>\n\n<p>Parsing HTML with regex can quickly become a nightmare and is generally discouraged. Instead you can use a parsing library like Beautiful Soup. This is often done in conjunction with the <code>requests</code> module but since you are using Selenium here you can use the built-in functions available to you (notably the <code>find_elements_by_...</code> functions).</p>\n\n<p>I advise you to break up the code in small functions to separate functionality, and make the code easier to maintain. For instance you could have one function that retrieves all the links of interest in a given page, and another function to fetch those URLs and download the files.</p>\n\n<hr>\n\n<p>Delays: Instead of setting arbitrary waits with <code>time.sleep</code> (that will either be too long or too short depending on the network conditions) you can use Selenium functions again (<code>WebDriverWait</code>), to determine when the page is 'loaded' or at least half-ready, for example by waiting for certain elements to appear. And if they do not appear or take too long (timeout), then there is no point proceeding with the rest of the code.</p>\n\n<p>This can be tricky, and the criteria will vary from one site to another. Sometimes you spend more time looking for the right signals than on coding.\nMy own approach in this particular case is to wait until the progress bar disappears but YMMV (I have tried to wait until the list of courses is loaded but that didn't seem to work well). This is not perfect and probably can be improved.</p>\n\n<p>See chapter: <a href=\"https://selenium-python.readthedocs.io/waits.html#explicit-waits\" rel=\"nofollow noreferrer\">5. Waits</a></p>\n\n<p>So in this case I am waiting until the control with class name <code>.mdui-progress</code> becomes invisible. I have determined this by using the Firefox inspector (under menu Tools/Web Developer) and setting up some breakpoints to freeze the page while it is reloading. This is not so straightforward but it's a question of practice.</p>\n\n<hr>\n\n<p>Now for some code. I have used Selenium with Firefox on Linux so the code has been adapted to run on my platform. Please disregard the Firefox directives and use yours instead.<br/>\nI note that your are on Windows but the code should be OK.<br/>\n<strong>NB</strong>: I added a few imports and removed <code>re</code>.</p>\n\n<hr>\n\n<pre><code>import time\nimport os, sys\nimport shutil\nfrom typing import (Dict, List)\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\n\n# constants\nROOT_URL = r'https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/'\nDOWNLOAD_PATH = \"E:\\\\Utilities_and_Apps\\\\Python\\\\MY PROJECTS\\\\Test data\\Downloads\\\\\"\n\noptions = FirefoxOptions()\n#options.add_argument(\"--headless\")\noptions.add_argument(\"--private-window\")\ndriver = webdriver.Firefox(options=options)\n\n\ndef get_links(driver: webdriver.firefox, xpath_selector: str) -> List[Dict]:\n links = []\n elems = driver.find_elements_by_xpath(xpath_selector)\n for elem in elems:\n url = elem.get_attribute(\"href\")\n class_name = elem.get_attribute(\"class\")\n links.append({\n \"url\": url,\n \"class_name\": class_name\n })\n return links\n\n\n# could return bool \ndef wait_for_page_load():\n # borrowed code: https://stackoverflow.com/questions/26566799/wait-until-page-is-loaded-with-selenium-webdriver-for-python\n try:\n # wait for page to load\n print(\"Waiting for page load...\")\n WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '.mdui-progress')))\n print(\"Page should now be ready, continue\")\n except TimeoutException:\n print(\"Timed out/failed to load page\")\n sys.exit()\n\n\n# load the main page and wait\ndriver.get(ROOT_URL)\nwait_for_page_load()\nprint(f'Links from {ROOT_URL}:')\nlinks = get_links(driver=driver, xpath_selector=\"//li/a\")\nfor link in links:\n url = link[\"url\"]\n class_name = link[\"class_name\"]\n print(f'Link: {url}: class name: {class_name}')\n if class_name.startswith('folder'):\n print('=> Folder: to be crawled')\n if class_name.startswith('file'):\n print('=> File: to be downloaded')\n</code></pre>\n\n<p>Details:</p>\n\n<ul>\n<li>The function <code>get_links</code> returns a <strong>list of dictionaries</strong>, for each link found I am returning the URL + the class name for the href tag: this is useful to differentiate between <strong>folders</strong> and <strong>files</strong>. Then all you have to do is enumerate the links and decide on whether to crawl further or download the file. The process should be made <strong>recursive</strong> et voilà.</li>\n<li>For more flexibility you can specify the xpath selector so as to reuse the function on other sites</li>\n<li>The xpath selector here is simply to look for A tags embedded in LI tags.</li>\n<li>The function <code>wait_for_page_load</code> waits for the progress bar to disappear, then I consider the page 'loaded' and ready to be inspected</li>\n<li>I have not implemented a download function</li>\n<li>I have attempted to use proper type hinting for the functions, but no docstrings</li>\n</ul>\n\n<p>If you add the recursion I think the final code could be quite short.</p>\n\n<p>Regarding the download, I am not sure how to determine it has finished. Probably by waiting for the file to appear in the Downloads folder. on Linux I might use <code>inotifywait</code> but this is an OS-dependent approach.</p>\n\n<hr>\n\n<p>Future improvements:</p>\n\n<p>Adding some <strong>parallel processing</strong> would be nice, to crawl multiple pages at the same time and download several files at once but be gentle with third-party websites. They could block you if they think you are bot and crawling too fast to be human.</p>\n\n<p>Or you could collect all the file links and download them in bulk at the end of the process. </p>\n\n<p>To get the file name from the URL you can simply do this:</p>\n\n<pre><code>from urllib.parse import urlparse\n\ndef get_file_name_from_url(url: str) -> str:\n u = urlparse(url)\n return os.path.basename(u.path))\n</code></pre>\n\n<p>But you should <strong>sanitize</strong> the file names as they may contain special characters that your OS will not accept (I think Windows does not accept the colon in file names for example). Unless your browser does that automatically.</p>\n\n<hr>\n\n<p>Sample output: folders</p>\n\n<pre>\nWating for page load...\nPage should now be ready, continue\nLinks from https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/:\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/10.%20Data%20Structures%20Trees/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/11.%20Data%20Structures%20Graphs/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/12.%20Algorithms%20Recursion/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/13.%20Algorithms%20Sorting/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/14.%20Algorithms%20Searching%20+%20BFS%20+%20DFS/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/15.%20Algorithms%20Dynamic%20Programming/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/16.%20Non%20Technical%20Interviews/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/17.%20Offer%20+%20Negotiation/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/18.%20Thank%20You/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/19.%20Extras%20Google,%20Amazon,%20Facebook%20Interview%20Questions/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/2.%20Getting%20More%20Interviews/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/20.%20Contributing%20To%20Open%20Source%20To%20Gain%20Experience/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/21.%20Bonus%20Extra%20Bits/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/22.%20Extras/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/3.%20Big%20O/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/4.%20How%20To%20Solve%20Coding%20Problems/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/5.%20Data%20Structures%20Introduction/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/6.%20Data%20Structures%20Arrays/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/7.%20Data%20Structures%20Hash%20Tables/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/8.%20Data%20Structures%20Linked%20Lists/: class name: folder\n=> Folder: to be crawled\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/9.%20Data%20Structures%20Stacks%20+%20Queues/: class name: folder\n=> Folder: to be crawled\n</pre>\n\n<p>Sample output: files</p>\n\n<pre>\nLinks from https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/:\nWating for page load...\nPage should now be ready, continue\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/1.%20How%20To%20Succeed%20In%20This%20Course.mp4?a=view: class name: file view\n=> File: to be downloaded\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/1.%20How%20To%20Succeed%20In%20This%20Course.vtt: class name: file\n=> File: to be downloaded\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/1.1%20Interview%20Mind%20Map.html?a=view: class name: file view\n=> File: to be downloaded\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/1.2%20Technical%20Interview%20Mind%20Map.html?a=view: class name: file view\n=> File: to be downloaded\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/2.%20Join%20Our%20Online%20Classroom!.html?a=view: class name: file view\n=> File: to be downloaded\nLink: https://coursevania.courses.workers.dev/[coursevania.com]%20Udemy%20-%20Master%20the%20Coding%20Interview%20Data%20Structures%20+%20Algorithms/1.%20Introduction/3.%20Exercise%20Meet%20The%20Community!.html?a=view: class name: file view\n=> File: to be downloaded\n</pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T15:22:06.743",
"Id": "474814",
"Score": "0",
"body": "This is an amazing response, got more useful information than i needed, Greatly appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T00:54:48.813",
"Id": "241915",
"ParentId": "241842",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241915",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T23:51:22.223",
"Id": "241842",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"file-system",
"web-scraping",
"selenium"
],
"Title": "Webscraping With Selenium - a Course Downloader and Sorter"
}
|
241842
|
<p>I write this program based on the algorithm of the word frequency counter program on the K&R book, page 139. I added some idioms of mine, some command-line options, and a dynamically allocable buffer.</p>
<p>Use it on stdin or give one or more file as arguments.<br>
The option <code>-k</code> considers only keywords (beginning with <code>_</code> or alphabetic character), and words consisting of symbols are ignored.<br>
The option <code>-w</code> considers words as a string of characters separated by white space.</p>
<p>Here is the code:</p>
<pre><code>#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
/* the tree node */
struct tnode {
char *word; /* pointer to the text */
unsigned long count; /* number of occurrences */
struct tnode *left; /* left child */
struct tnode *right; /* right child */
};
static int exitval = EXIT_SUCCESS;;
static int spaceword = 0;
static int keyword = 0;
static char *buf = NULL;
static size_t bufsize = 0;
#define CHECKBUF(i) \
{if (bufsize == 0 || (i) >= bufsize - 1) { \
size_t newsize = bufsize + BUFSIZ; \
\
if (newsize <= bufsize) /* check for overflow */ \
errc(EXIT_FAILURE, EOVERFLOW, "realloc"); \
bufsize = newsize; \
if ((buf = realloc(buf, bufsize)) == NULL) \
err(EXIT_FAILURE, "realloc"); \
}}
static int getfreq(struct tnode **, FILE *);
static void putfreq(struct tnode *);
static void addtree(struct tnode **, char *);
static char *getword(FILE *);
static void usage(void);
/* word frequency count */
int
main(int argc, char *argv[])
{
struct tnode *root = NULL;
FILE *fp;
int c;
while ((c = getopt(argc, argv, "kw")) != -1) {
switch (c) {
case 'k':
keyword = 1;
break;
case 'w':
spaceword = 1;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc == 0) {
if (getfreq(&root, stdin) == -1)
err(EXIT_FAILURE, "stdin");
} else {
while (*argv) {
if ((fp = fopen(*argv, "r")) == NULL) {
warn("%s", *argv);
exitval = EXIT_FAILURE;
} else {
if (getfreq(&root, fp) == -1) {
warn("%s", *argv);
exitval = EXIT_FAILURE;
}
fclose(fp);
}
argv++;
}
}
free(buf);
putfreq(root);
if (ferror(stdout))
err(EXIT_FAILURE, "stdout");
return exitval;
}
/* print the frequency of each word in tree */
static void
putfreq(struct tnode *tree)
{
if (tree != NULL) {
putfreq(tree->left);
if (printf("%7lu %s\n", tree->count, tree->word) < 0)
err(EXIT_FAILURE, "stdout");
free(tree->word);
putfreq(tree->right);
free(tree);
}
}
/* populate tree with the frequences of words in fp; return -1 on error on fp */
static int
getfreq(struct tnode **tree, FILE *fp)
{
char *buf;
while ((buf = getword(fp)) != NULL)
if (!keyword || (keyword && (*buf == '_' || isalpha(*buf))))
addtree(tree, buf);
if (ferror(fp))
return -1;
return 1;
}
/* add a node with w, at or below p */
static void
addtree(struct tnode **p, char *w)
{
int cond;
if (*p == NULL) { /* if a new word has arrived, make a new node */
*p = malloc(sizeof **p);
if (*p == NULL)
err(EXIT_FAILURE, "malloc");
if (((*p)->word = strdup(w)) == NULL)
err(EXIT_FAILURE, "strdup");
(*p)->count = 1;
(*p)->left = (*p)->right = NULL;
} else if ((cond = strcmp(w, (*p)->word)) == 0) { /* repeated word */
(*p)->count++;
} else if (cond < 0) { /* less than into left subtree */
addtree(&((*p)->left), w);
} else if (cond > 0) { /* greater than into right subtree */
addtree(&((*p)->right), w);
}
}
/* get next word from fp; if fp is NULL, free buffer and return null */
static char *
getword(FILE *fp)
{
size_t i = 0;
int c;
while (isspace(c = getc(fp)))
;
if (c == EOF)
return NULL;
if (spaceword) {
while (!isspace(c)) {
CHECKBUF(i);
buf[i++] = c;
c = getc(fp);
}
goto done;
}
if (c == '_' || isalpha(c)) {
while (c == '_' || isalnum(c)) {
CHECKBUF(i);
buf[i++] = c;
c = getc(fp);
}
ungetc(c, fp);
goto done;
}
while (c != '_' && !isalpha(c) && c != EOF && !isspace(c)) {
CHECKBUF(i);
buf[i++] = c;
c = getc(fp);
}
ungetc(c, fp);
done:
buf[i] = '\0';
return buf;
}
/* show usage */
static void
usage(void)
{
(void)fprintf(stderr, "usage: wfreq [-kw] [file...]\n");
exit(EXIT_FAILURE);
}
</code></pre>
<p>Here is an example of using <code>wfreq(1)</code> (the name I gave to this word frequency counter) on its own source code, with the option <code>-k</code>:</p>
<pre><code> 1 BUFSIZ
4 CHECKBUF
2 EOF
1 EOVERFLOW
10 EXIT_FAILURE
1 EXIT_SUCCESS
5 FILE
12 NULL
4 _
3 a
1 add
5 addtree
1 and
4 argc
8 argv
1 arrived
1 at
1 below
3 break
14 buf
1 buffer
7 bufsize
23 c
2 case
8 char
1 check
2 child
4 cond
5 count
1 ctype
1 default
1 define
3 done
1 each
5 else
7 err
1 errc
1 errno
1 error
1 exit
4 exitval
1 fclose
2 ferror
1 file
1 fopen
1 for
18 fp
1 fprintf
4 free
1 frequences
2 frequency
1 from
1 get
4 getc
4 getfreq
1 getopt
3 getword
2 goto
1 greater
7 h
1 has
10 i
23 if
2 in
7 include
10 int
2 into
1 is
1 isalnum
3 isalpha
3 isspace
1 k
4 keyword
2 kw
6 left
1 less
1 long
1 lu
1 main
1 make
2 malloc
2 n
2 new
3 newsize
1 next
3 node
1 null
1 number
1 occurrences
3 of
2 on
2 optind
1 or
1 overflow
14 p
1 pointer
1 populate
1 print
1 printf
5 putfreq
1 r
3 realloc
1 repeated
7 return
6 right
4 root
3 s
1 show
3 size_t
1 sizeof
3 spaceword
15 static
1 stderr
2 stdin
1 stdio
1 stdlib
3 stdout
1 strcmp
2 strdup
1 string
10 struct
2 subtree
1 switch
1 text
2 than
4 the
10 tnode
1 to
13 tree
2 ungetc
1 unistd
1 unsigned
5 usage
9 void
7 w
2 warn
1 wfreq
7 while
2 with
10 word
1 words
</code></pre>
|
[] |
[
{
"body": "<p>Some ideas:</p>\n\n<p><strong>Alternative code</strong></p>\n\n<pre><code>// if (bufsize == 0 || (i) >= bufsize - 1)\nif ((i) + 1 >= bufsize)\n</code></pre>\n\n<p><strong>UB when <code>*buf < 0</code></strong></p>\n\n<p><code>is...(ch)</code> functions defined for <code>ch</code> in the <code>unsigned char</code> range and <code>EOF</code>.</p>\n\n<pre><code>// isalpha(*buf)\nisalpha((unsigned char) *buf)\n</code></pre>\n\n<p><strong>Help</strong></p>\n\n<p>Too bad <code>usage()</code> does not include option detail like</p>\n\n<blockquote>\n <p>The option -k considers only keywords (beginning with _ or alphabetic character), and words consisting of symbols are ignored.<br>\n The option -w considers words as a string of characters separated by white space.</p>\n</blockquote>\n\n<p><strong>Creeping feature</strong></p>\n\n<p>Option for output sorted by usage.</p>\n\n<p><strong>Alt code: star reduction</strong></p>\n\n<p>To change most of the <code>(*p)</code> to a tidy <code>tn</code>, consider:</p>\n\n<pre><code>// v--- I'd expect a const\n// static void addtree(struct tnode **p, char *w) {\nstatic void addtree(struct tnode **p, const char *w) {\n int cond;\n struct tnode *tn = *p;\n if (tn == NULL) { /* if a new word has arrived, make a new node */\n *p = tn = malloc(sizeof *tn);\n if (tn == NULL)\n err(EXIT_FAILURE, \"malloc\");\n if ((tn->word = strdup(w)) == NULL)\n err(EXIT_FAILURE, \"strdup\");\n tn->count = 1;\n tn->left = tn->right = NULL;\n } else if ((cond = strcmp(w, tn->word)) == 0) { /* repeated word */\n tn->count++;\n } else if (cond < 0) { /* less than into left subtree */\n addtree(&(tn->left), w);\n } else if (cond > 0) { /* greater than into right subtree */\n addtree(&(tn->right), w);\n }\n}\n</code></pre>\n\n<p><strong>Reduced allocations by 2 idea</strong></p>\n\n<p>Since allocation of a node always occurs with a <em>string</em>: research <a href=\"https://en.wikipedia.org/wiki/Flexible_array_member\" rel=\"nofollow noreferrer\">Flexible array member</a> and do both in one allocation.</p>\n\n<pre><code>struct tnode {\n unsigned long count; /* number of occurrences */\n struct tnode *left; /* left child */\n struct tnode *right; /* right child */\n char word[]; /* text array*/ // FAM\n};\n\n*p = malloc(sizeof **p + strlen(w) + 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:19:21.307",
"Id": "474641",
"Score": "0",
"body": "*\"if ((i) + 1 >= bufsize)\"* I was using it in a previous version, but then I thought on the case that (i) + 1 overflow and be less than `bufsize` and then I decided to check for `bufsize == 0` first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:45:01.087",
"Id": "474655",
"Score": "0",
"body": "*\"Reduced allocations by 2 idea\"*: but then I would have to check for overflow for the sum of the three operands, which would make the code more complex."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T01:44:40.183",
"Id": "241844",
"ParentId": "241843",
"Score": "1"
}
},
{
"body": "<h2>Overall Impression</h2>\n<p>This code would be difficult to maintain especially if someone else had to pick up where the original coder had left off. This due primarily to the use of macros, multiple goto's and global variables.</p>\n<p>A second consideration is that as the program uses more memory to contain the buffer, performance might be impacted.</p>\n<p>A third consideration also about the performance is that the program will perform better if it reads a large block of text from the input file and then processes that text using string or character manipulation rather then using charater based input.</p>\n<h2>Global Variables</h2>\n<p>Even though the variables the global namespace is protected from the variables <code>exitval</code>, <code>spaceword</code>, <code>keyword</code>, <code>buf</code> and <code>bufsize</code> by the use of static, programming within the file is still using the variables as global variables. This makes the code harder to write, read and debug because without searching the whole program it's not clear where the variables are modified. Use local variables whenever possible, and pass necessary information into functions as needed.</p>\n<h2>Use of Macros</h2>\n<p>It's clear why the code has a macro (<code>CHECKBUF</code>) in it, it is to reduce code repetition which is good, however, it would be better to use a function rather than a macro. One of the drawbacks of using macros is that they are very difficult to debug because the code in them is not expanded in the debugger. Another drawback is that they tend to hide things if memory allocation , goto's or <code>exit()</code> statements are in them, this code has 2 out of 3 of those hidden items in the macro.</p>\n<h2>Portability</h2>\n<p>The C programming language is very portable as long as the C programming standard is followed, and not some other standard such as <code>POSIX</code>. Two of the header files in this code (<code>err.h</code> and <code>unistd.h</code>) are not portable to Windows with out additional work being done to port that code or the associated libraries.</p>\n<p>More portable code would write error messages and warning messages to <code>stderr</code> and not use <code>err()</code>, <code>warn()</code> or <code>errc()</code>. You could write your own portable library that recreates these functions, it might be a very good learning experience that you could share here on code review.</p>\n<p>Another library function you could consider writing because it isn't portable is <code>getopt()</code>. I think this might even be a better learning experience.</p>\n<h2>The Use of Goto's</h2>\n<p>There is sometimes a need to use goto's in error handling code, but that is pretty rare. To use multiple goto's for flow control in a function is to return to the original versions of BASIC and FORTRAN which didn't have many of the modern programming constructs. This used to be known as speghetti code. Blocks of code can be nested inside if statements, if the blocks of code ae too large or complex they can become functions. In the C programming language the <code>break;</code> statement can be used to exit a logic block. In the case of the <code>getword()</code> function perhaps it would be better to have it call two function that process the text, one for the <code>-k</code> switch and one for the <code>-w</code> switch.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T03:34:08.947",
"Id": "474597",
"Score": "0",
"body": "Detail: \"err.h and unistd.h) are not portable to Windows\". I just compiled code with `#include <err.h> #include <unistd.h>` on my Windows PC. The limitations is not an OS one. It is a compiler one. Perhaps you are thinking of VS?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:55:11.287",
"Id": "474638",
"Score": "0",
"body": "@chux-ReinstateMonica Well since I have to be able to compile C# and .Net for consulting reasons, yes it is VS, however, before I posted my answer I have checked and neither one of the files are in the C programming standard, they are POSIX. Non of my Linux machine are working at the moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:21:41.460",
"Id": "474642",
"Score": "0",
"body": "On the global variables: `exitval` has to be global, since it should be modified every time a warning occurs. `spaceword` and `keyword` are flags, I could pass then as a single bit set variable as argument to `getfreq()`. `buf` and `bufsize` could be static on `getword` but then, how would I `free(3)` `buf` at the end of `main`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:34:21.103",
"Id": "474646",
"Score": "0",
"body": "Take a good look at the usage of `exitval` the only place it is used is in `main()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:34:36.447",
"Id": "474647",
"Score": "0",
"body": "*\"it would be better to use a function rather than a macro\"*, but it is called inside three loops. Using a function would have the overhead of function call at each `while` iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:35:56.253",
"Id": "474649",
"Score": "0",
"body": "@pacmaninbw indeed, in other codes of mine the exitval is modified by other functions, so I am used to put it as global, but in this one it does not occur."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:36:23.153",
"Id": "474650",
"Score": "0",
"body": "Since you are using character input rather than reading a block of text at a time and processing it internally, this doesn't matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T13:35:32.087",
"Id": "474660",
"Score": "1",
"body": "@barthooper `CHECKBUF(i)` could replaced with `if (i + 1 >= bufsize) checkcode(i, &bufsize, &buf);`. Since the `if()` is seldom true, the function overhead is not significant."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T02:03:18.513",
"Id": "241845",
"ParentId": "241843",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241845",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T23:55:30.363",
"Id": "241843",
"Score": "3",
"Tags": [
"c",
"binary-tree",
"binary-search-tree"
],
"Title": "C word frequency counter"
}
|
241843
|
<p>If you could rate my code, 1-10. What will it be and provide reasoning on why you gave that answer, i feel like i could of written this code better but i don't know what i am missing or what i could have done to make it better</p>
<pre><code>import random
print('Lets play Rock Paper Scissors')
user_point = 0 #To keep track of the points
bot_point = 0
for tries in range (1,4):
try:
user_guess = input('Rock Paper Scissors? ')
choices = ['Rock','Paper','Scissors']
bot_guess = random.choice(choices) #Will randomly pick from the list 'choices'
while user_guess not in choices:#if the user tries to put in anything other then the choices given
print('Please enter the choices above!')
user_guess = input('Rock Paper Scissors? ')
except ValueError:
print('Please choose from the choices above ') #Just in case user tries to put a different value type
user_guess = input('Rock Paper Scissors? ')
#DEBUG = "The bot did " + bot_guess
#print(DEBUG)
if user_guess == bot_guess:
print('Tie!')
elif user_guess == "Rock" and bot_guess == "Paper":
print('The bot earns a point!')
bot_point += 1
elif user_guess == 'Paper' and bot_guess == "Rock":
print('The user earns a point!')
user_point += 1
elif user_guess == 'Paper' and bot_guess == 'Scissors':
print('The bot earns a point')
bot_point += 1
elif user_guess == 'Scissors' and bot_guess == 'Paper':
print('The user earns a point')
user_point += 1
elif user_guess == 'Rock' and bot_guess == 'Scissors':
print('The user earns a point')
user_point += 1
elif user_guess == 'Scissors' and bot_guess == 'Rock':
print('The bot earns a point')
bot_point += 1
print('After ' + str(tries) + ' tries. ' + ' The score is')
print('The User: ' + str(user_point))
print('The Bot: ' + str(bot_point))
if user_point > bot_point:
print('THE USER IS THE WINNER!!!')
else:
print('THE BOT IS THE WINNER!!!')
</code></pre>
|
[] |
[
{
"body": "<p>I give it a 0 because I tied the bot and the bot still wins.</p>\n\n<p>Just kidding.</p>\n\n<p>Without considering some of the ways this could be made simpler and more compact (ie. strictly from a style guide point of view), this would be rated exactly a 4.88/10 (at least, that's what <code>pylint</code> is claiming):</p>\n\n<pre><code>************* Module rps\nrps.py:3:13: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:6:47: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:7:13: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:9:19: C0326: No space allowed before bracket\nfor tries in range (1,4):\n ^ (bad-whitespace)\nrps.py:9:21: C0326: Exactly one space required after comma\nfor tries in range (1,4):\n ^ (bad-whitespace)\nrps.py:13:25: C0326: Exactly one space required after comma\n choices = ['Rock','Paper','Scissors']\n ^ (bad-whitespace)\nrps.py:13:33: C0326: Exactly one space required after comma\n choices = ['Rock','Paper','Scissors']\n ^ (bad-whitespace)\nrps.py:15:19: C0326: Exactly one space required before assignment\n bot_guess = random.choice(choices) #Will randomly pick from the list 'choices'\n ^ (bad-whitespace)\nrps.py:17:0: C0301: Line too long (106/100) (line-too-long)\nrps.py:21:110: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:21:0: C0301: Line too long (110/100) (line-too-long)\nrps.py:32:22: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:35:23: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:38:22: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:41:23: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:44:23: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:45:58: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:59:37: C0303: Trailing whitespace (trailing-whitespace)\nrps.py:1:0: C0114: Missing module docstring (missing-module-docstring)\nrps.py:6:0: C0103: Constant name \"user_point\" doesn't conform to UPPER_CASE naming style (invalid-name)\nrps.py:7:0: C0103: Constant name \"bot_point\" doesn't conform to UPPER_CASE naming style (invalid-name)\n\n-----------------------------------\nYour code has been rated at 4.88/10\n</code></pre>\n\n<p>It is OK to ignore the last 2 messages. Pylint thinks variable that are declared outside functions are supposed to be constants. But in this case the script is so short that creating functions doesn't make sense.</p>\n\n<ul>\n<li>formatting on the trailing comments:</li>\n</ul>\n\n<pre><code>bot_guess = random.choice(choices) #Will randomly pick from the list 'choices'\nwhile user_guess not in choices:#if the user tries to put in anything other then the choices given\n</code></pre>\n\n<p>much nicer to do: <code><code><one space>#<one space><comment></code></p>\n\n<pre><code>bot_guess = random.choice(choices) # will randomly pick from the list 'choices'\nwhile user_guess not in choices: # if the user tries to put in anything other then the choices given\n</code></pre>\n\n<ul>\n<li>The <code>if-elif</code> statements used to determine the winner can be simplified quite a bit. Think about it like this: there are only 3 outcomes, so you should only need 3 checks, at most. There are several ways to do it, but here is one I thought of:</li>\n</ul>\n\n<pre><code> if user_guess == bot_guess:\n print('Tie!')\n elif choices.index(user_guess) == (choices.index(bot_guess) + 2) % 3:\n print('The bot earns a point!')\n bot_point += 1\n else:\n print('The user earns a point')\n user_point += 1\n</code></pre>\n\n<ul>\n<li><p>The list <code>choices = ['Rock','Paper','Scissors']</code> is treated as a constant, so declare it at the top of the file, right after the import statements (and it actually <em>should</em> be in all UPPER CASE). Since the content won't change, it would be good practice to use a tuple instead of a list (just swap the square brackets <code>[...]</code> for parens <code>(...)</code>).</p></li>\n<li><p>Python 3.4 introduced a <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">feature called f-strings</a> that make string formatting a lot cleaner. Read the link for all †he details, but the main takeaway from it is that if you prefix a string literal with an <code>f</code>, it allows for string interpolation \"on the fly\":</p></li>\n</ul>\n\n<pre><code>print('After ' + str(tries) + ' tries. ' + ' The score is') # NO!!!\nprint(f'After {tries} tries, the score is') # YES!!!!\n</code></pre>\n\n<ul>\n<li>The <code>try-except</code> block is not needed. You can replace it with:</li>\n</ul>\n\n<pre><code>user_guess = ''\nbot_guess = random.choice(choices)\nwhile True:\n user_guess = input('Rock Paper Scissors? ')\n if user_guess in choices:\n break\n else:\n print(\"you must pick a choice from the list!\")\n</code></pre>\n\n<ul>\n<li>You could also combine the <code>user_point</code> and <code>bot_point</code> into a single <code>points</code> variable, and assign negative points for the bot and positive points for the user. This is kind of like taking the users side: you earn points by winning, and lose them when the bot wins. The downside is that you can't keep track of how many points each player has earned, only the difference between the 2.</li>\n</ul>\n\n<p>So in the end, I get this:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport random\n\nCHOICES = ('Rock', 'Paper', 'Scissors')\npoints = 0\nprint('Lets play Rock Paper Scissors')\nfor tries in range(1, 4):\n user_guess = ''\n bot_guess = random.choice(CHOICES)\n while True:\n user_guess = input('Rock Paper Scissors? ')\n if user_guess in CHOICES:\n break\n else:\n print(\"you must pick a choice from the list!\")\n print(f\"The bot did {bot_guess}\")\n if user_guess == bot_guess:\n print('Tie!')\n elif CHOICES.index(user_guess) == (CHOICES.index(bot_guess) + 2) % 3:\n print('The bot earns a point!')\n points -= 1\n else:\n print('The user earns a point!')\n points += 1\nif points > 0:\n print(f'After {tries} tries, THE USER IS THE WINNER BY {points}!!!')\nelif points == 0:\n print(f'After {tries} tries, IT\\'S A TIE!!!')\nelse:\n print(f'After {tries} tries, THE BOT IS THE WINNER BY {points * -1}!!!')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T01:18:09.940",
"Id": "474724",
"Score": "0",
"body": "the part about the `CHOICES.index(user_guess) == (CHOICES.index(bot_guess) + 2) % 3:` , May you explain it, im not understanding how it works. @Z4-tier"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T02:01:50.800",
"Id": "474727",
"Score": "0",
"body": "Sure, that one was a little tricky. if you have an array `['R', 'P', 'S']` then `R` is index 0, `P` index 1 and `S` index 2. It just happens that this array is ordered in a way such that, whichever option you choose, if you move 2 index positions to the right (wrapping around from `S` back to `R`) you always land on the item that will lose to the one you picked. So this basically says \"If the user chooses the item that is 2 to the right of whatever the bot picks, then the bot wins\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T02:02:47.107",
"Id": "474728",
"Score": "0",
"body": "And actually, looking at it now, `CHOICES` should probably be a tuple and not a list, since it should be immutable. I'll change it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T02:27:52.800",
"Id": "474730",
"Score": "0",
"body": "Ohhhhhhh Thank you so much for clarification, but one more question, if the guess wraps around by two, always putting up the winning match up then what is the point of the `% 3` part @Z4-tier"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:02:10.860",
"Id": "474847",
"Score": "1",
"body": "`%` is the remainder operator, it's what is making the guess wrap around. If you break that line down for a specific set up values, it works like this: say `bot_guess = 'Scissors'`. then `CHOICES.index(bot_guess) == 2` since 'Scissors' is at index 2. So we get `(CHOICES.index(bot_guess) + 2) % 3 == (2 + 2) % 3 == 4 % 3 == 1`. If the user had picked the item at index 1 (paper) they would lose, but if they had picked the item at index 0 (rock), they win. In general, `n % m` will give the remainder after *integer division* of `n` divided by `m`. (`2%4=2`, `4%4=0`, `6%4=2`, `8%4=0`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T23:34:16.973",
"Id": "474872",
"Score": "0",
"body": "Thank you so much for your help!!!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T08:19:06.613",
"Id": "241865",
"ParentId": "241847",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T03:24:49.100",
"Id": "241847",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"rock-paper-scissors"
],
"Title": "I made a Rock paper scissors game with Python 3.8"
}
|
241847
|
<p>Can this be made any simpler/shorter/more efficient?</p>
<p>This function will compute paycheck amount according to hours worked and rate per hour.</p>
<pre><code>def compute_pay(hours: int, rate: float) -> float:
"""Computes pay according to hours worked and rate per hours.
For every hour worked after the 40th hour the rate per hour
is multipled by 1.5
"""
pay = 0
if hours > 40:
pay += 40 * rate
hours -= 40
pay += hours * rate * 1.5
else:
pay = hours * rate
return pay
hrs = int(input('Hours: '))
hrs_rate = float(input('Rate: '))
print('Pay:', compute_pay(hrs, hrs_rate))
</code></pre>
<p>This is my second take on the above function:</p>
<pre><code>def compute_pay(hours: int, rate: float) -> float:
"""Computes pay according to hours worked and rate per hours.
For every hour worked after the 40th hour the rate per hour
is multipled by 1.5
"""
hours -= 40
if hours > 0:
pay = 40 * rate + (hours * rate * 1.5)
else:
pay = (hours + 40) * rate
return pay
hrs = int(input('Hours: '))
hrs_rate = float(input('Rate: '))
print('Pay:', compute_pay(hrs, hrs_rate))
</code></pre>
<p>My aim is to have begginers' friendly logic while introducing Python features.</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review. I think the simpler way of expressing your code would look like this:</p>\n\n<pre><code>def compute_pay(hours: int, rate: float) -> float:\n return (min(hours, 40) + (max(0, hours - 40) * 1.5)) * rate\n\nhrs = int(input('Hours: '))\nhrs_rate = float(input('Rate: '))\n\nprint('Pay:', compute_pay(hrs, hrs_rate))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T06:19:59.223",
"Id": "241855",
"ParentId": "241850",
"Score": "3"
}
},
{
"body": "<pre class=\"lang-py prettyprint-override\"><code>def compute_pay(hours: int, rate: float) -> float:\n return (hours + max(0, hours-40)/2) * rate\n</code></pre>\n\n<p>EDIT:\nAll <code>hours</code> must be multiplied with <code>rate</code> i.e. <code>hours*rate</code>. If <code>hours</code> is more than 40, then we need these extra hours to be multiplied with 1.5.</p>\n\n<p>How much extra pay do we need to add to <code>hours*rate</code> to get correct pay? That would be </p>\n\n<pre><code> max(0,hours-40)*1.5*rate - max(0,hours-40)*rate # Why subtract? Think! \n= max(0,hours-40)*0.5*rate\n</code></pre>\n\n<p>Therefore, <code>pay = hours*rate + max(0,hours-40)*0.5*rate</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T08:30:18.500",
"Id": "475264",
"Score": "0",
"body": "Did you mean `(hours + max(0, hours-40)*2) * rate` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T07:14:48.313",
"Id": "242173",
"ParentId": "241850",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241855",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T04:25:00.440",
"Id": "241850",
"Score": "4",
"Tags": [
"python"
],
"Title": "Simple Compute Pay Function"
}
|
241850
|
<p>I was trying to solve the following question:</p>
<p><strong>You are given 2 arrays: one representing the time people arrive at a door and other representing the direction they want to go(in or out) You have to find at what time each person will use the door provided no 2 people can use the door at the same time. Constraints: the door starts with ‘in’ position, in case of a conflict(2 or more people trying to use the door at the same time), the direction previously used holds precedence. If there is no conflict whoever comes first uses the door. Also if no one uses the door, it reverts back to the starting ‘in’ position. Should be linear time complexity.</strong></p>
<p>Is this a good approach? Can I get my code reviewed / refactored? Any advice regarding the following approach? Is there a better way to do this?</p>
<pre><code>public class Doors {
public class visitor {
int time;
String dir;
public visitor(int time, String dir) {
this.time = time;
this.dir = dir;
}
}
public String defaultDir = "In";
public String lastDir = defaultDir;
public static void main(String[] args) {
int[] time = new int[] { 2, 3, 5, 1, 7, 4, 2 };
String dir[] = new String[] { "In", "Out", "In", "Out", "Out", "In", "Out" };
Doors obj = new Doors();
obj.findTime(time, dir);
}
private void findTime(int[] time, String[] dir) {
Map<Integer, Map<String, List<visitor>>> myMap = new TreeMap<>();
for (int i = 0; i < time.length; i++) {
List<visitor> myList = new ArrayList<Doors.visitor>();
if (!myMap.containsKey(time[i])) {
Map<String, List<visitor>> visitorMap = new HashMap<String, List<visitor>>();
myList.add(new visitor(time[i], dir[i]));
visitorMap.put(dir[i], myList);
myMap.put(time[i], visitorMap);
} else {
Map<String, List<visitor>> visitorMap = myMap.get(time[i]);
if (!visitorMap.containsKey(dir[i])) {
myList.add(new visitor(time[i], dir[i]));
visitorMap.put(dir[i], myList);
} else {
myList = visitorMap.get(dir[i]);
myList.add(new visitor(time[i], dir[i]));
visitorMap.put(dir[i], myList);
}
}
}
for (Entry<Integer, Map<String, List<visitor>>> entry : myMap.entrySet()) {
if (entry.getValue().size() > 1) { // now we know multiple people are trying to enter at the same time
List<visitor> visitors = entry.getValue().get(lastDir);
for (visitor v : visitors) {
System.out.println(v.time + " : " + v.dir);
}
lastDir = lastDir.contentEquals("In") ? "Out" : "In";
visitors = entry.getValue().get(lastDir);
for (visitor v : visitors) {
System.out.println(v.time + " : " + v.dir);
}
} else {
if (entry.getValue().containsKey("In")) {
List<visitor> visitors = entry.getValue().get("In");
for (visitor v : visitors) {
System.out.println(v.time + " : " + v.dir);
}
lastDir = "In";
} else {
List<visitor> visitors = entry.getValue().get("Out");
for (visitor v : visitors) {
System.out.println(v.time + " : " + v.dir);
}
lastDir = "Out";
}
}
entry.setValue(new HashMap<String, List<visitor>>());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:32:22.980",
"Id": "474644",
"Score": "0",
"body": "I would have done it by sorting a List<Visitor>, but that's not linear time complexity. Oh well, I failed the interview."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:44:08.703",
"Id": "474653",
"Score": "0",
"body": "To be a bit more helpful, the question is basically \"create a TreeMap that allows duplicate keys\". A bit challenging for an interview question. And this comment is after 30 minutes or more of thought."
}
] |
[
{
"body": "<p>I finally came up with an idea that might work.</p>\n\n<p>I created a <code>TreeMap<Integer, List<String>></code>.</p>\n\n<p>Here's the output from my last test run. The first group is the <code>TreeMap</code> I created. The second group is a <code>List<Visitor></code> that I created from the map. I just used the <code>Visitor</code> class <code>toString</code> method to output the <code>List</code>.</p>\n\n<pre><code>1 [Out]\n2 [In, Out]\n3 [Out]\n4 [In]\n5 [In]\n7 [Out]\n\nVisitor [time=1, direction=Out]\nVisitor [time=2, direction=Out]\nVisitor [time=2, direction=In]\nVisitor [time=3, direction=Out]\nVisitor [time=4, direction=In]\nVisitor [time=5, direction=In]\nVisitor [time=7, direction=Out]\n</code></pre>\n\n<p>Here's the code. It took me several hours to come up with this idea. I don't envy anyone trying to come up with this in an interview.</p>\n\n<p>Edited to add: I'm not sure what comments the OP is looking for.</p>\n\n<p>The <code>createMap</code> method checks to see if a key, value pair exists indirectly. If the value is null, the key, value pair doesn't exist. So I create an <code>ArrayList<String></code> and add the key, value to the map. If the key, value pair exists, then I add the string to the value <code>List</code>. Since the value is a <code>List</code>, I maintain the order of the input people.</p>\n\n<p>The <code>createList</code> method is a little more complicated. I iterate through the map keys, retrieving the <code>List<String></code> value for each key. If there's only one element in the <code>List</code> (one person), I put them through the door and set the default direction of the door.</p>\n\n<p>If there's more than one element in the <code>List<String></code> value, I iterate through the <code>List</code> twice. Once with the default door direction, and once again with the opposite door direction. Since the List for one time value is likely to be small, the double iteration is pretty short.</p>\n\n<p>Worst case, when everyone arrives at the door at the same time, the cost of creating the map, and iterating through the map value is <code>3n</code>, which is effectively <code>n</code>.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\n\npublic class Doors {\n\n public static void main(String[] args) {\n int[] time = new int[] { 2, 3, 5, 1, 7, 4, 2 };\n String direction[] = new String[] { \"In\", \"Out\", \n \"In\", \"Out\", \"Out\", \"In\", \"Out\" };\n Doors obj = new Doors();\n List<Visitor> visitors = \n obj.findTime(time, direction);\n for (Visitor visitor : visitors) {\n System.out.println(visitor);\n }\n }\n\n public List<Visitor> findTime(int[] time, \n String[] direction) {\n Map<Integer, List<String>> map =\n createMap(time, direction);\n printMap(map);\n return createList(map);\n }\n\n private void printMap(Map<Integer, List<String>> map) {\n Set<Integer> set = map.keySet();\n Iterator<Integer> iter = set.iterator();\n while (iter.hasNext()) {\n Integer key = iter.next();\n List<String> value = map.get(key);\n System.out.println(key + \" \" + value);\n }\n System.out.println();\n }\n\n private Map<Integer, List<String>> createMap(\n int[] time, String[] direction) {\n Map<Integer, List<String>> map = new TreeMap<>();\n for (int i = 0; i < time.length; i++) {\n Integer key = time[i];\n List<String> value = map.get(key);\n if (value == null) {\n value = new ArrayList<>();\n }\n value.add(direction[i]);\n map.put(key, value);\n }\n return map;\n }\n\n private List<Visitor> createList(\n Map<Integer, List<String>> map) {\n List<Visitor> visitors = new ArrayList<>();\n String defaultDirection = \"In\";\n Set<Integer> set = map.keySet();\n Iterator<Integer> iter = set.iterator();\n while (iter.hasNext()) {\n Integer key = iter.next();\n List<String> value = map.get(key);\n if (value.size() == 1) {\n String s = value.get(0);\n Visitor visitor = new Visitor(key, s);\n visitors.add(visitor);\n defaultDirection = s;\n } else {\n createVisitors(visitors, defaultDirection, \n key, value);\n defaultDirection = changeDefaultDirection(\n defaultDirection);\n createVisitors(visitors, defaultDirection, \n key, value);\n }\n }\n return visitors;\n }\n\n private void createVisitors(List<Visitor> visitors, \n String defaultDirection, Integer key, \n List<String> value) {\n for (int i = 0; i < value.size(); i++) {\n String s = value.get(i);\n if (s.equals(defaultDirection)) {\n Visitor visitor = new Visitor(key, s);\n visitors.add(visitor);\n }\n }\n }\n\n private String changeDefaultDirection(\n String defaultDirection) {\n return defaultDirection.equals(\"In\") ? \"Out\" : \"In\";\n }\n\n public class Visitor {\n\n private final Integer time;\n\n private final String direction;\n\n public Visitor(Integer time, String direction) {\n this.time = time;\n this.direction = direction;\n }\n\n public int getTime() {\n return time;\n }\n\n public String getDirection() {\n return direction;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"Visitor [time=\");\n builder.append(time);\n builder.append(\", direction=\");\n builder.append(direction);\n builder.append(\"]\");\n return builder.toString();\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T19:42:18.747",
"Id": "474693",
"Score": "0",
"body": "Hey @Gilbert Le Blanc I like this approach. Could you add some more comments to the code. Like for the methods createList and createMap?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T16:29:45.113",
"Id": "241890",
"ParentId": "241852",
"Score": "2"
}
},
{
"body": "<p>I tried a different approach to solve the problem based on the test of the question and obtaining the same output using what could be considered a brutal approach to the problem:\nthe map I'm using is like @Gilbert Le Blanc's answer a <code>Map<Integer, List<String>></code>; you can construct the values of the map of two types:</p>\n\n<ol>\n<li>a sequence [\"In\", \"In\", ... \"In\", \"Out\", \"Out\", ... \"Out\"]</li>\n<li>a sequence [\"Out\", \"Out\", ... \"Out\", \"In\", \"In\", ..., \"In\"]</li>\n</ol>\n\n<p>So if you have your method <code>findTime</code>, you can create your <code>map</code> in the following way:</p>\n\n<pre><code>private void findTime(int[] times, String[] dirs) {\n //maxTime will be used after in the code while iterating over the map\n int maxTime = 0;\n\n Map<Integer, List<String>> map = new TreeMap<>();\n for (int i = 0; i < times.length; ++i) {\n int time = times[i];\n if (time > maxTime) { maxTime = time; } \n String dir = dirs[i];\n if (map.containsKey(time)) {\n List<String> list = map.get(time);\n int index = list.indexOf(dir);\n if (index == -1) {\n list.add(dir);\n } else {\n list.add(index, dir);\n }\n } else {\n map.put(time, new ArrayList<>(Arrays.asList(dir)));\n }\n }\n\n //other lines of code \n}\n</code></pre>\n\n<p>So every value of the <code>map</code> will be a sequence of one of the two types [\"In\", \"In\", ... \"In\", \"Out\", \"Out\", ..., \"Out\"] or [\"Out\", \"Out\", ... \"Out\", \"In\", \"In\", ..., \"In\"]</p>\n\n<p>Once you created your <code>map</code> you can iterate over it obtaining your same output:</p>\n\n<pre><code>String currentDir = \"In\";\nfor (int i = 0; i <= maxTime; ++i) {\n if (map.containsKey(i)) {\n List<String> list = map.get(i);\n if (!list.get(0).equals(currentDir)) {\n //reverse list so all elements equals to currentDir go in the first positions\n Collections.reverse(list); \n }\n for (String s : list) {\n System.out.println(i + \" : \" + s);\n }\n int size = list.size();\n currentDir = list.get(size - 1); \n } else {\n currentDir = \"In\"; //<-- no time, door everts back to the starting ‘in’ position\n }\n</code></pre>\n\n<p>Below the full code of the method <code>findTime</code>:</p>\n\n<pre><code>private void findTime(int[] times, String[] dirs) {\n int maxTime = 0;\n Map<Integer, List<String>> map = new TreeMap<>();\n for (int i = 0; i < times.length; ++i) {\n int time = times[i];\n if (time > maxTime) { maxTime = time; }\n String dir = dirs[i];\n if (map.containsKey(time)) {\n List<String> list = map.get(time);\n int index = list.indexOf(dir);\n if (index == -1) {\n list.add(dir);\n } else {\n list.add(index, dir);\n }\n } else {\n map.put(time, new ArrayList<>(Arrays.asList(dir)));\n }\n }\n\n\n String currentDir = \"In\";\n\n for (int i = 0; i <= maxTime; ++i) {\n if (map.containsKey(i)) {\n List<String> list = map.get(i);\n if (!list.get(0).equals(currentDir)) {\n Collections.reverse(list);\n }\n for (String s : list) {\n System.out.println(i + \" : \" + s);\n }\n int size = list.size();\n currentDir = list.get(size - 1); \n } else {\n currentDir = \"In\";\n }\n } \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T19:08:16.327",
"Id": "241897",
"ParentId": "241852",
"Score": "1"
}
},
{
"body": "<p>Since this site is not so much focused on clever solutions and algorithms but on code quality I'd like to give some comments on this.</p>\n\n<blockquote>\n <p><strong>Disclaimer</strong> this is <em>my personal view</em> and it might differ from what others may think.\n Never the less this would be <em>my criteria</em> if I'd be the interviewer. \n I'm also aware that some of my thoughts are easy to make when sitting on my couch having plenty of time.</p>\n</blockquote>\n\n<h1>Naming</h1>\n\n<p>I'm aware that an interview situation is quite stressing, but there are some basic rules violated in your code, that even a stress situation cannot excuse:</p>\n\n<h2>Conventions</h2>\n\n<ul>\n<li>Class names start <em>upper case</em>, so should your inner class <code>visitor</code> </li>\n<li>Class names are <em>singular form</em>, so should your class <code>Dors</code></li>\n</ul>\n\n<p>For me this would be a major issue, worse then not finishing the task...</p>\n\n<p>Similar is with the names of the input arrays. Since they are some kind of <em>collection</em> their names should have a <em>plural 's'</em>. \nI assume that this names where given my the interviewer, but I for myself would have renamed them even then.</p>\n\n<h2>Avoid technical name parts</h2>\n\n<p>What if you change your mind an <code>visitorMap</code> becomes some other kind of collection?</p>\n\n<p>You might argue that this will not happen in an interview task, but the interviewer wants to find out how you usually code. Omitting good code criteria under pressure is not a benefit here.</p>\n\n<h2>Choose names from the problem domain</h2>\n\n<p>You have some variables with randomly picked names (<code>obj</code>, <code>myMap</code>, <code>myList</code>). \nThis is a special case from the previous point and would show that you, when under pressure, create code that needs lots of refactoring afterwards. </p>\n\n<h1>Know the standard lib</h1>\n\n<p>When you initialize the map you use a rather complex <code>if/else</code> construct. But the <code>computeIfAbsent()</code> method was introduced long time ago with java-8, so that it should be known by any Java developer. </p>\n\n<pre><code>for (int i = 0; i < time.length; i++) {\n myMap.computeIfAbsent(time[i], HashMap::new)\n .computeIfAbsent(dir[i], ArrayList:new)\n .add(new Visitor(time[i], dir[i]));\n}\n</code></pre>\n\n<h1>Separate <em>user interaction</em> from <em>processing</em></h1>\n\n<p>Your code outputs results in between the processing. I'd rather expect <code>findTime()</code> to return a <code>List<Visitors></code> that has the desired order and have that that print out in <code>main()</code>.</p>\n\n<h1>Mighty method</h1>\n\n<p>You do all the processing in a single method although is obviously consists of at least two blocks that your be extracted to separate private methods applying the <em>Single Responsibility Pattern</em></p>\n\n<h1>Unnecessary special handling</h1>\n\n<p>In your methods second part you handle the case of only <em>one person arrives</em> differently then the case <em>multiple persons arrive</em>. The first case would be implicitly handled correctly by the latter. </p>\n\n<h1>Failed Requirements</h1>\n\n<p>I think this wouldn't be \"NoGos\" but bonuses, if done correctly...</p>\n\n<ul>\n<li><p>Your code does not handle the case of </p>\n\n<blockquote>\n <p>Also if no one uses the door, it reverts back to the starting ‘in’ position.</p>\n</blockquote>\n\n<p>You simple ignore the time gaps.</p></li>\n<li><p>The code is not of <em>linear complexity</em></p>\n\n<p>I believe this is a trick question since the requirements involves sorting which simply cannot be done in <em>linear complexity</em>.</p></li>\n</ul>\n\n<hr>\n\n<p>Finally: if you'd be interviewed by me and not writing <em>unit tests</em> you wouldn't get a call from me anyway...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:12:43.693",
"Id": "241998",
"ParentId": "241852",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241890",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T05:18:09.363",
"Id": "241852",
"Score": "1",
"Tags": [
"java",
"interview-questions",
"complexity"
],
"Title": "Refactor Java code"
}
|
241852
|
<p>I have a code, which does the following:</p>
<ul>
<li>Get data from the <code>HrAttLogs</code> Table</li>
<li>Input data from the <code>HrAttLogs</code> Table to the <code>HrAttLogsFormatted</code> Table</li>
</ul>
<p>I would like to know whether the query below, which I will provide, can be improved? In terms of <code>Performance</code> and Speed.</p>
<pre><code>SELECT
FingerId,
ShiftId,
DateIn,
DateOut,
ScanIn,
ScanOut,
WorkhourIn,
WorkhourOut,
TIME_IN,
TIME_OUT
FROM
(
SELECT
i.FingerId,
i.ShiftId,
i.Date AS 'DateIn',
o.Date AS 'DateOut',
i.Time AS 'ScanIn',
CASE WHEN o.Time != i.Time THEN o.Time END AS 'ScanOut',
CASE
WHEN i.Time < i.ShiftIn_2 THEN i.WorkhourIn_1
WHEN i.Time < i.ShiftIn_3 THEN i.WorkhourIn_2
WHEN i.Time > i.ShiftIn_1 THEN i.WorkhourIn_3
END AS WorkhourIn,
/* Added check for Date too.. the last checking is for any overlapping Date */
CASE WHEN i.Status = 'Rolling' THEN
CASE
WHEN i.DateOut = i.Date AND i.Time > i.ShiftOut_1 THEN i.WorkhourOut_2
WHEN i.DateOut = i.Date AND i.Time > i.ShiftOut_2 THEN i.WorkhourOut_3
WHEN i.DateOut = i.Date AND i.Time > i.ShiftOut_3 THEN i.WorkhourOut_1
WHEN i.DateOut > i.Date THEN i.WorkhourOut_3
END
ELSE
CASE WHEN i.ShiftId != 'Rolling' THEN
CASE WHEN i.DateOut = i.Date AND o.Time > i.ShiftOut_2 THEN i.WorkhourOut_3
ELSE i.WorkhourOut_2
END
WHEN i.DateOut = i.Date AND o.Time > i.ShiftOut_3 THEN i.WorkhourOut_1
END
END AS WorkhourOut,
CASE
WHEN i.Time < i.ShiftIn_2 THEN TIMEDIFF(i.Time, i.WorkhourIn_1)
WHEN i.Time < i.ShiftIn_3 THEN TIMEDIFF(i.Time, i.WorkhourIn_2)
WHEN i.Time > i.ShiftIn_1 THEN TIMEDIFF(i.Time, i.WorkhourIn_3)
END AS 'TIME_IN',
CASE WHEN o.Time != i.Time THEN
CASE WHEN i.Status = 'Rolling' THEN
CASE WHEN o.Time > i.ShiftOut_3 THEN
CASE WHEN o.Time > i.ShiftOut_1 THEN
CASE WHEN o.Time > i.ShiftOut_2 THEN TIMEDIFF(o.Time, i.WorkhourOut_2)
ELSE TIMEDIFF(o.Time, i.WorkhourOut_1)
END
ELSE TIMEDIFF(o.Time, i.WorkhourOut_1)
END
ELSE TIMEDIFF(o.Time, i.WorkhourOut_3)
END
ELSE
CASE WHEN i.Status != 'Rolling' THEN
CASE WHEN o.Time > i.ShiftOut_1 THEN
CASE WHEN o.Time > i.ShiftOut_2 THEN TIMEDIFF(o.Time, i.WorkhourOut_1)
ELSE TIMEDIFF(o.Time, i.WorkhourOut_2)
END
END
END
END
END AS 'TIME_OUT',
i.ShiftIn_1,
i.ShiftIn_2,
i.ShiftIn_3,
i.ShiftOut_1,
i.ShiftOut_2,
i.ShiftOut_3,
i.WorkhourIn_2,
i.WorkhourIn_3,
i.WorkhourOut_2,
i.WorkhourOut_3,
i.Status
FROM
( /* INSERT here */
SELECT
i.FingerId,
fs.ShiftId,
CASE WHEN i.Status = 0 THEN
MIN(i.Date)
END AS 'Date',
-- MIN(i.Date) AS 'Date',
/* Added CASE expression to deal with overlapping attendance Date */
CASE WHEN i.Status = 0 AND MIN(i.Time) >= '19:00:00'
THEN DATE(DATE_ADD(i.Date, INTERVAL + 1 DAY))
ELSE
DATE(DATE_ADD(i.Date, INTERVAL + s.DayOut DAY))
END AS 'DateOut',
CASE WHEN i.Status = 0 THEN
i.Time
END AS 'Time',
-- MIN(i.Time) AS 'Time',
i.Status,
s.ShiftIn_1,
s.ShiftIn_2,
s.ShiftIn_3,
s.ShiftOut_1,
s.ShiftOut_2,
s.ShiftOut_3,
s.WorkhourIn_1,
s.WorkhourIn_2,
s.WorkhourIn_3,
s.WorkhourOut_1,
s.WorkhourOut_2,
s.WorkhourOut_3
FROM HrAttLogs AS i
INNER JOIN HrEmployee AS fs ON fs.FingerId = i.FingerId
INNER JOIN HrEmployeeShift AS s ON s.Id = fs.ShiftId
WHERE
i.Time >= s.ShiftIn_1
AND i.Date >= '2020-04-07'
AND i.Date <= '2020-04-09'
AND i.MachineIp = '10.20.20.73'
GROUP BY
i.Id,
i.FingerId,
i.Date
) AS i
LEFT JOIN (
SELECT
o.FingerId,
CASE WHEN o.Status = 1 THEN
MAX(o.Date)
END AS 'Date',
CASE WHEN o.Status = 1 THEN
MAX(o.Time)
END AS 'Time',
o.Status
FROM
HrAttLogs AS o
WHERE
o.Date >= '2020-04-07'
AND o.Date <= '2020-04-09'
AND o.MachineIp = '10.20.20.73'
GROUP BY
o.Id,
o.FingerId,
o.Date
ORDER BY
Date ASC,
Status ASC
) AS o ON i.FingerId = o.FingerId
AND o.Date = i.DateOut
AND o.Time >= '00:00:00'
) AS q
WHERE
FingerId = 61
AND FingerId IS NOT NULL
AND ShiftId IS NOT NULL
AND DateIn IS NOT NULL
AND DateOut IS NOT NULL
AND ScanIn IS NOT NULL
AND WorkhourIn IS NOT NULL
AND WorkhourOut IS NOT NULL
AND TIME_IN IS NOT NULL
AND TIME_OUT IS NOT NULL
ORDER BY
q.FingerId ASC,
DateIn ASC
</code></pre>
<p>For more details, I save it <a href="https://www.db-fiddle.com/f/vhJQ1tFyzWitnJn4cDnarW/2" rel="nofollow noreferrer">here</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T05:37:41.993",
"Id": "241853",
"Score": "2",
"Tags": [
"mysql"
],
"Title": "Shorten Query Retrieving Time Attendance Data"
}
|
241853
|
<p>This is my code for a 15 puzzle.</p>
<p>The basic gist is to get a grid of equal width and height (size) and number them in ascending order, with the exception of the last square getting a 0 value ('0' integer not shown on the tile so it looks like a blank tile). The grid is scrambled and then the user has to click tiles either next to or above the 'blank tile' to swap their places. The grid goes green when it is reordered in ascending order with the 'blank tile' being at last spot on the grid.</p>
<p>The default size is 4, hence the 15 puzzle name, but my 15 puzzle accepts any size (within reason).</p>
<p>FifteenPuzzle</p>
<pre><code>import java.util.Arrays;
public class FifteenPuzzle
{
private int[][] grid;
private int xspace; // xspace,yspace are the current coordinates of the space
private int yspace;
private final int size; // the number of tiles across and down
private final int[][] goal; // the tile positions in the goal state
private int movecount = 1000;
//sets up the grid using initialGrid
public FifteenPuzzle (int[][] initialGrid)
{
size = initialGrid.length;
goal = setGoal();
grid = initialGrid;
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
if (grid[x][y] == 0) {
xspace = x;
yspace = y;
}
}
}
}
// sets up the grid by copying goal and then making random moves.
public FifteenPuzzle (int size)
{
if (size < 2 || size > 10) {
throw new IllegalArgumentException("Invalid size");
}
this.size = size;
goal = setGoal();
grid = new int[size][size];
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
grid[x][y] = goal[x][y];
if(goal[x][y] == 0) {
xspace = x;
yspace = y;
}
}
}
scramble();
}
public void scramble() {
for(int moves = 1; moves <= movecount; moves++){
//do a set amount of random moves.
boolean done = false;
while (!done) {
double num = Math.random();
if (num <= 0.25) {
if(legalClick(xspace + 1, yspace)) {
moveTile(xspace + 1, yspace);
done = true;
}
}
if (num > 0.25 && num <= 0.5) {
if(legalClick(xspace - 1, yspace)) {
moveTile(xspace - 1, yspace);
done = true;
}
}
if (num > 0.5 && num <= 0.75) {
if(legalClick(xspace, yspace + 1)) {
moveTile(xspace, yspace + 1);
done = true;
}
}
if (num > 0.75) {
if(legalClick(xspace, yspace - 1)) {
moveTile(xspace, yspace - 1);
done = true;
}
}
}
}
}
public int[][] setGoal() {
int[][] goal = new int[size][size];
for (int a = 1; a <= size; a++) {
for (int b = 1; b <= size; b++) {
goal[a-1][b-1] = a + size*(b-1);
}
}
goal[size-1][size-1] = 0;
return goal;
}
public int[][] getGrid()
{
return grid;
}
public int getSize()
{
return size;
}
// Returns true if x,y is on the board and adjacent to the blank space.
public boolean legalClick(int x, int y)
{
if (x < 0 || y < 0 || x > size-1 || y > size-1) {
return false;
}
return ( (x == xspace && (y == yspace - 1 || y == yspace + 1)) || (y == yspace && (x == xspace - 1 || x == xspace + 1)) );
}
public boolean finished()
{
return Arrays.deepEquals(grid, goal);
}
// swaps the tile at x,y with the space;
public void moveTile (int x, int y)
{
if (!legalClick(x, y)) {
return;
}
grid[xspace][yspace] = grid[x][y];
xspace = x;
yspace = y;
grid[xspace][yspace] = 0;
}
}
</code></pre>
<p>SimpleCanvas</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCanvas {
private JFrame frame;
private CanvasPane canvas;
private Graphics2D graphic;
private Image canvasImage;
private boolean autoRepaint;
public SimpleCanvas(String title, int width, int height, Color bgColour) {
frame = new JFrame();
canvas = new CanvasPane();
frame.setContentPane(canvas);
frame.setTitle(title);
canvas.setPreferredSize(new Dimension(width, height));
frame.pack();
Dimension size = canvas.getSize();
canvasImage = canvas.createImage(size.width, size.height);
graphic = (Graphics2D) canvasImage.getGraphics();
graphic.setColor(bgColour);
graphic.fillRect(0, 0, size.width, size.height);
graphic.setColor(Color.black);
frame.setVisible(true);
this.autoRepaint = true;
}
public void drawLine(int x1, int y1, int x2, int y2, Color c) {
setForegroundColour(c);
graphic.drawLine(x1, y1, x2, y2);
}
public void drawRectangle(int x1, int y1, int x2, int y2, Color c) {
setForegroundColour(c);
graphic.fillRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2));
}
public void drawString(String text, int x, int y, Color c) {
setForegroundColour(c);
graphic.drawString(text, x, y);
graphic.setFont(new Font("TimesRoman", Font.BOLD, 20));
if (autoRepaint)
canvas.repaint();
}
public void drawString(int n, int x, int y, Color c) {
drawString(n + "", x, y, c);
}
public void setForegroundColour(Color newColour) {
graphic.setColor(newColour);
}
public Color getForegroundColour() {
return graphic.getColor();
}
public void setAutoRepaint(boolean autoRepaint) {
this.autoRepaint = autoRepaint;
}
public void repaint() {
canvas.repaint();
}
public void addMouseListener(MouseListener ml) {
canvas.addMouseListener(ml);
}
public void addMouseMotionListener(MouseMotionListener mml) {
canvas.addMouseMotionListener(mml);
}
class CanvasPane extends JPanel {
public void paint(Graphics g) {
g.drawImage(canvasImage, 0, 0, null);
}
}
}
</code></pre>
<p>FifteenPuzzleViewer</p>
<pre><code>import java.awt.event.*;
import java.awt.*;
public class FifteenPuzzleViewer implements MouseListener
{
private FifteenPuzzle puzzle;
private int size;
private SimpleCanvas sc;
public FifteenPuzzleViewer(FifteenPuzzle puzzle)
{
this.puzzle = puzzle;
size = puzzle.getSize();
sc = new SimpleCanvas(size*size-1 + " Puzzle", 100*size, 100*size + 100, Color.white);
sc.addMouseListener(this);
if(puzzle.finished()) {
drawGreenGrid();
} else {
drawGrid();
drawGrid();
}
}
private void drawGrid()
{
int[][] grid = puzzle.getGrid();
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
drawTile(x*100, y*100, Color.RED);
if(grid[x][y] != 0 && grid[x][y] < 10) {
sc.drawString(grid[x][y], x*100+45, y*100+55, Color.BLACK);
} else if (grid[x][y] != 0) {
sc.drawString(grid[x][y], x*100+40, y*100+55, Color.BLACK);
}
}
}
for (int y = 0; y < size + 1; y++) {
sc.drawLine(0,y*100,size*100,y*100, Color.BLACK);
}
for (int x = 0; x < size; x++) {
sc.drawLine(x*100,0,x*100,size*100, Color.BLACK);
}
}
private void drawGreenGrid()
{
int[][] grid = puzzle.getGrid();
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
drawTile(x*100, y*100, Color.GREEN);
if(grid[x][y] != 0 && grid[x][y] < 10) {
sc.drawString(grid[x][y], x*100+45, y*100+55, Color.BLACK);
} else if (grid[x][y] != 0) {
sc.drawString(grid[x][y], x*100+40, y*100+55, Color.BLACK);
}
}
}
for (int y = 0; y < size + 1; y++) {
sc.drawLine(0,y*100,size*100,y*100, Color.BLACK);
}
for (int x = 0; x < size + 1; x++) {
sc.drawLine(x*100,0,x*100,size*100, Color.BLACK);
}
}
private void drawTile(int x, int y, Color c)
{
sc.drawRectangle(x, y, x+100, y+100, c);
}
public void mousePressed(MouseEvent e)
{
puzzle.moveTile(e.getX()/100, e.getY()/100);
if(puzzle.finished()) {
drawGreenGrid();
} else {
drawGrid();
}
}
public void mouseReleased(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public static void main(String[] args) {
FifteenPuzzle p = new FifteenPuzzle(3);
FifteenPuzzleViewer fpv = new FifteenPuzzleViewer(p);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T15:53:17.913",
"Id": "474677",
"Score": "0",
"body": "`setForegroundColor` is missing in action for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T17:11:00.103",
"Id": "474685",
"Score": "0",
"body": "fixed it now, sorry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:37:54.347",
"Id": "474706",
"Score": "0",
"body": "Now it compiles but it doesn't run, I don't see any window / JFrame being shown. Do you have a main method or is this partial code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T01:56:37.500",
"Id": "474726",
"Score": "0",
"body": "ahh, I'm using blueJ so I dont need a main method, I just simulate instances and run them from the main blueJ page, but I'll add a main method in puzzleViewer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T02:11:44.693",
"Id": "474729",
"Score": "0",
"body": "also autopaint was missing for some reason so i put that back in the SimpleCanvas class"
}
] |
[
{
"body": "<h2>Design</h2>\n\n<p>I'd create a separate class for <code>Grid</code> and <code>Position</code> at the very least. Especially when separating out the <code>Grid</code> the game code will be significantly reduced. Smaller classes should generally be preferred when they make sense.</p>\n\n<p>With the removal of <code>movecount</code> (see below), you'd have just two fields: <code>currentGrid</code> and <code>goalGrid</code>, both of type <code>Grid</code>.</p>\n\n<h2>Code review</h2>\n\n<p>I'll handle the lines in order, skipping many, with the remarks below the code.</p>\n\n<pre><code>import java.util.Arrays;\npublic class FifteenPuzzle\n{ \n</code></pre>\n\n<p>Please use at least a white line between import statements and the class declaration.</p>\n\n<p>The class should probably be made <code>final</code> unless you create it for extension.</p>\n\n<p>Using <code>{</code> on a new line instead of \"Egyptian braces\" is often acceptable, but it is not very much used for Java. If they are used, then use them <strong>consistently</strong> (which is not the case here). Most IDE's contain code formatting nowadays, use that if you don't like doing it yourself.</p>\n\n<pre><code>private int xspace; // xspace,yspace are the current coordinates of the space\nprivate int yspace;\n</code></pre>\n\n<p>What space? The empty space? Please be precise. If two variables are needed for one thing, try and aggregate them together, e.g. into a <code>Position</code> class (immutable with <code>equals</code> and <code>hashCode</code> please).</p>\n\n<pre><code>private final int size; // the number of tiles across and down \n</code></pre>\n\n<p>Not required, <code>grid.length</code> will do that. Generally, try to minimize the amount of fields. However, for readability reasons I guess this is kinda OK.</p>\n\n<pre><code>private int movecount = 1000;\n</code></pre>\n\n<p>The field <code>movecount</code> (or rather <code>moveCount</code>) should be a constant; it doesn't change within the game logic.</p>\n\n<p>I'm a bit worried about the naming though, what about, say, <code>edgeSize</code> or <code>dimension</code>?</p>\n\n<pre><code>grid = initialGrid;\n</code></pre>\n\n<p>Why isn't the size of the grid checked here? It is not symmetric with the constructor that just takes the grid size. Furthermore, there is no check that the width and height are identical.</p>\n\n<pre><code>public void scramble() {\n</code></pre>\n\n<p>Hey, is the user allowed to call <code>scramble</code>? If not, then why is the method <code>public</code> instead of <code>private</code>? Same for other methods.</p>\n\n<pre><code>done = true;\n</code></pre>\n\n<p>Use <code>while (true)</code> or <code>for(;;)</code> and <code>break</code> / <code>continue</code> instead. May look weird initially, but it removes one variable from the equation, and you can remove redundant checks.</p>\n\n<pre><code>for (int a = 1; a <= size; a++) {\n</code></pre>\n\n<p>No, no, no. Always use zero based indexing:</p>\n\n<pre><code>for (int a = 0; a < size; a++) {\n</code></pre>\n\n<p>unless there are specific reasons not to. It seems OK for the move counter (as you're doing move 1 initially, not move 0 I suppose).</p>\n\n<p>And what about that naming, why <code>a</code> and <code>b</code> for coordinates? <code>x</code> and <code>y</code> is used correctly in the rest of the code.</p>\n\n<pre><code>public int[][] setGoal() {\n</code></pre>\n\n<p>A \"setter\" is a specific function that sets a field to a given value. It takes a single argument and returns <code>void</code>. <code>createGoal</code> is probably a better name.</p>\n\n<pre><code>public int[][] getGrid()\n</code></pre>\n\n<p>This is a correct \"getter\" declaration. No arguments, single return of a field.</p>\n\n<pre><code>return grid;\n</code></pre>\n\n<p>Never ever return a mutable reference to something that makes up the internal state of a class, violating encapsulation principles. Copy or clone the data instead, or provide read only access (iterator, lambda).</p>\n\n<pre><code>if (x < 0 || y < 0 || x > size-1 || y > size-1) {\n</code></pre>\n\n<p>This I can read somewhat.</p>\n\n<pre><code>return ( (x == xspace && (y == yspace - 1 || y == yspace + 1)) || (y == yspace && (x == xspace - 1 || x == xspace + 1)) );\n</code></pre>\n\n<p>This I cannot. The line size is too large as well. Compare to reading this:</p>\n\n<pre><code>return insideGrid(x, y) && nextToEmpty(x, y);\n</code></pre>\n\n<p>and then implementing those functions. With a bit of help of the IDE that's not even that much work.</p>\n\n<pre><code>if (!legalClick(x, y)) {\n return;\n}\n</code></pre>\n\n<p>Just returning (or worse, just returning <code>null</code> or <code>0</code> for methods that return data) is almost always a bad decision. In this case an exception should be thrown.</p>\n\n<p>If the calling code first wants to check if the move is valid, it can call <code>legalClick</code> itself. You may be calling <code>legalClick</code> twice that way, but the JIT compiler will probably notice if it starts to take too much time.</p>\n\n<h2>GUI code</h2>\n\n<p>There was some time required to get the GUI running. However, when I did the game ran, but there were some issues. For instance, you can scale the window containing puzzle, but that just mucks up the contents. The puzzle is not scaled well initially either, and a line seems to be missing on the right hand side.</p>\n\n<p>I don't expect to interact with a <code>Viewer</code>. Maybe with a <code>View</code>, but a <code>Viewer</code> sounds rather passive.</p>\n\n<p>There are dual calls to <code>drawGrid</code> that aren't explained at all. I don't see why those are necessary.</p>\n\n<p>I presume the squares are 100 pixels in size or so, but there is a lot of repetition of the value 100. The value 100 should probably be a constant, but generally I'd already use a <code>squareEdgeSize</code> variable for that. At least you did make sure that the value is not repeated in the canvas code, so that's OK.</p>\n\n<p>You are using a <code>MouseListener</code> with unimplemented methods. However, in that case you might want to have a look at a <code>MouseAdapter</code> instead that provides default implementations, cleaning up your listener interface.</p>\n\n<p>When you look at the <code>drawRectangle</code> you can see that you specifically have to calculate <code>x + 100</code>, while the original method of drawing in Java uses a <code>width</code>. So you are calculating a second <code>x</code> using the width only to reverse that later.</p>\n\n<p>Your methods are not symmetric. You have a <code>drawGrid()</code> that doesn't take any arguments, and many other <code>draw</code> methods that do. That kind of inconsistencies are also seen in the whitespace and such. It makes the code less clean and harder to read.</p>\n\n<p>Both the constructor of the viewer and another method draw the grid, and make the same decision which one to draw. This goes against DRY principles.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:22:05.187",
"Id": "241910",
"ParentId": "241868",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T08:55:40.427",
"Id": "241868",
"Score": "4",
"Tags": [
"java",
"sliding-tile-puzzle"
],
"Title": "programmed 15 puzzle in java"
}
|
241868
|
<p>I'm a beginner in Java programming. At the start, I wanted to make something easy and then develope it more and more. I chose to do TicTacToe game. At this point I added some menu, playing with bot, bigger map. This is my first bigger OOP project, so I'm the most curious ,if I did it correctly. Could You tell me some advice how to improve my skills. Thank you in advance.</p>
<p>Code is anable in my github: <a href="https://github.com/NeverGiveUPek/TicTacToe" rel="noreferrer">https://github.com/NeverGiveUPek/TicTacToe</a></p>
<p>I will also copy it below:</p>
<pre><code>public class Game {
public static void main(String[] args) {
Play game1 = new Play();
game1.do_game();
}
}
</code></pre>
<p>*</p>
<pre><code>public class Play {
private Map board;
private Settings settings = new Settings();
private Player player1;
private Player player2;
private byte play_state = 0;
private char tmp_icon;
public void set_game() {
if(play_state == 0) {
GameSettings menu = new GameSettings();
menu.select_settings();
set_board(menu.get_board_size());
set_game_mode(menu.get_number_game_mode(),menu.get_bot_lvl());
set_icons(menu.get_player1_icon());
set_starting_icon(menu.get_number_starting_icon());
save_game(menu.get_board_size(), menu.get_number_game_mode(), menu.get_number_starting_icon(), menu.get_player1_icon());
}
else if(play_state == 1){
board.clean();
set_starting_icon(settings.get_last_starting_icon());
}
}
private void set_starting_icon(int starting_icon){
if(starting_icon==1){
tmp_icon = 'X';
}
else if(starting_icon==2){
tmp_icon = 'o';
}
}
private void set_game_mode(int game_mode, int bot_lvl){
player1 = new PlayerHuman(settings.get_standart_data_style(),board.get_map_size());
if(game_mode==1) {
player2 = new PlayerHuman(settings.get_standart_data_style(),board.get_map_size());
System.out.println("PvsP");
}
else if(game_mode==2) {
player2 = new Bot(bot_lvl);
System.out.println("PvsB");
}
}
public void set_icons(int player1_icon) {
if(player1_icon == 1){
player1.set_icon('X');
player2.set_icon('o');
}
else if(player1_icon == 2) {
player1.set_icon('o');
player2.set_icon('X');
}
}
public void set_board(int board_size) {
int winning_length = 3;
if(board_size == 4) winning_length = 4;
else if(board_size > 4) winning_length = 5;
board = new Map(board_size,winning_length);
board.clean();
}
public void change_player(){
if(tmp_icon == 'X') tmp_icon = 'o';
else if(tmp_icon == 'o') tmp_icon = 'X';
}
public void make_move(Player player){
player.do_move(board);
if(board.check_cell_empty(player.x,player.y)){
System.out.println(player.x + " " + player.y);
board.set_cell_icon(player.x,player.y,player.icon);
}
else{
board.print_map();
System.out.println("You wrote wrong cords, do it again");
make_move(player);
}
}
public void annouce_game_ending(int game_condition){
if(game_condition == 0) System.out.println("It's TIE !");
else if(game_condition == 10) {
System.out.println("'X' is a WINNER !");
}
else {
System.out.println("'o' is a WINNER !");
}
}
public void save_game(int map_size,int game_mode,int starting_icon, int player1_icon){
settings.set_last_board_size(map_size);
PlayerHuman human_player1 = (PlayerHuman) player1;
settings.set_last_data_style(human_player1.get_data_style());
settings.set_last_game_mode(game_mode);
settings.set_last_starting_icon(starting_icon);
settings.set_last_player1_icon(player1_icon);
}
public void do_game(){
while(true) {
Menu start = new Menu(settings, play_state);
start.run_menu();
play_state = start.get_play_state();
set_game();
board.print_map();
while (board.check_game_condtion() == 2) {
System.out.println("Teraz kolej: " + tmp_icon);
if (tmp_icon == player1.icon) {
make_move(player1);
} else if (tmp_icon == player2.icon) {
make_move(player2);
}
board.print_map();
change_player();
}
annouce_game_ending(board.check_game_condtion());
play_state = 1;
}
}
}
</code></pre>
<p>*</p>
<pre><code>public abstract class Player {
char icon = 'P';
int x = -1, y = -1;
public void set_icon(char icon) {
this.icon = icon;
}
public char get_icon() {
return icon;
}
protected boolean check_cords(int x, int y, int map_size){
return x >= 0 && x < map_size && y >= 0 && y < map_size;
}
public abstract void do_move(Map map);
}
</code></pre>
<p>*</p>
<pre><code>import java.util.InputMismatchException;
import java.util.Scanner;
public class PlayerHuman extends Player {
private byte data_style;
public PlayerHuman(byte data_style, int board_size){
if(data_style == 2 && board_size > 3) this.data_style = 1;
else this.data_style = data_style;
}
@Override
public void do_move(Map map) {
int map_size = map.get_map_size();
get_cords(data_style);
if (!check_cords(x,y,map_size)) {
System.out.println("Your cords should be beetween 0-" + (map_size-1));
map.print_map();
do_move(map);
} else if (map.check_cell_empty(x, y) == false) {
System.out.println("This cell is already occupied");
map.print_map();
do_move(map);
}
}
public byte get_data_style(){return data_style;}
private void get_cords(byte data_style){
if(data_style == 1) get_cords_in_seq();
else if(data_style == 2) get_cords_as_board();
}
private void get_cords_in_seq(){
boolean good = false;
while(!good) {
try {
Scanner input = new Scanner(System.in);
System.out.println("x: ");
x = input.nextInt();
System.out.println("y: ");
y = input.nextInt();
good = true;
} catch (InputMismatchException e) {
System.out.println("Wrong input");
}
}
}
private void get_cords_as_board(){
boolean good = false;
while(!good) {
try {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
x = (number-1) % 3;
y = 2 - ((number-1)/3);
System.out.println("x: " + x + "y: " + y);
good = true;
} catch (InputMismatchException e) {
System.out.println("Wrong input");
}
}
}
}
</code></pre>
<p>*</p>
<pre><code>import java.util.LinkedList;
import java.util.Random;
import java.util.List;
public class Bot extends Player {
private int[] move = new int[2];// {x , y}
private byte best_score = -10;
private int bot_lvl;
public Bot(int bot_lvl){
this.bot_lvl = bot_lvl;
}
@Override
public void do_move(Map map) {
if(bot_lvl == 1){ //worst bot
get_random_move(map);
}
else if(bot_lvl == 2){ // average bot
get_average_move(map);
}
else { // unbeatable bot
get_best_move(map);
}
set_cords(move);
}
private void get_best_move(Map map){
byte score;
int map_size = map.get_map_size();
first:
for (int i = 0; i < map_size; i++) {
for (int j = 0; j < map_size; j++) {
if (map.check_cell_empty(j, i)) {
map.set_cell_icon(j, i, icon);
score = minimax(map, (byte) 0, false, false);
map.set_cell_icon(j, i, ' ');
if (score > best_score) {
move[0] = j;
move[1] = i;
best_score = score;
if (best_score == 10) {
break first;
}
}
}
}
}
best_score = -10;
}
private void get_random_move(Map map) {
int map_size = map.get_map_size();
List<Integer> possible_moves = new LinkedList<>();
int counter=0;
for (int i = 0; i < map_size; i++) {
for (int j = 0; j < map_size; j++) {
if (!map.check_map_full()) {
if (map.check_cell_empty(j, i)) {
possible_moves.add(i*10 + j);//y * 10 + x
counter++;
}
}
}
}
int rand_number;
Random rand = new Random();
rand_number = rand.nextInt(counter); //getting random move which won't end in next 2 rounds
int score_move = possible_moves.get(rand_number);
move[0] = score_move%10; // x
move[1] = score_move/10; // y
}
private void get_average_move(Map map){
byte counter = 0;
List<Integer> possible_moves = new LinkedList<>();
byte score;
int map_size = map.get_map_size();
for (int i = 0; i < map_size; i++) {
for (int j = 0; j < map_size; j++) {
if (map.check_cell_empty(j, i)) {
map.set_cell_icon(j, i, icon);
score = minimax(map, (byte) 0, false, true);
map.set_cell_icon(j, i, ' ');
if (score >= 5) {
counter++;
possible_moves.add(i*10 + j);//y * 10 + x
}
}
}
}
if(counter == 0) {
get_random_move(map);
}
else {
int rand_number;
Random rand = new Random();
rand_number = rand.nextInt(counter); //getting random move which won't end in next 2 rounds
int score_move = possible_moves.get(rand_number);
move[0] = score_move%10; // x
move[1] = score_move/10; // y
}
best_score = -10;
}
protected byte minimax(Map map, byte depth, boolean isMaximazing, boolean isAverage) { //isAverage needed to get_average_move
byte result = map.check_game_condtion();
if (result != 2) {
return (byte) (adapt_game_condition(result) - depth);
}
if(depth == 2 && isAverage == true){ // return 5 when bot can't lose in next 2 moves
return 5;
}
int map_size = map.get_map_size();
byte number = get_isMaximazing_number(isMaximazing);
for (int i = 0; i < map_size; i++) {
for (int j = 0; j < map_size; j++) {
if (map.check_cell_empty(j, i)) {
if (!isMaximazing) map.set_cell_icon(j, i, another_icon());
else map.set_cell_icon(j, i, icon);
byte score = minimax(map, (byte) (depth + 1), !isMaximazing, isAverage);
map.set_cell_icon(j, i, ' ');
if (!isMaximazing) {
if (score < number) {
number = score;
}
} else {
if (score > number) {
number = score;
}
}
}
}
}
return number;
}
private byte get_isMaximazing_number(boolean isMaximazing) {
if (isMaximazing) return -20;
return 20;
}
private void set_cords(int[] best_move) {
x = best_move[0];
y = best_move[1];
}
private byte adapt_game_condition(byte score) {
if (icon == 'o') score = (byte) (-1 * score);
return score;
}
private char another_icon() {
if (icon == 'X') return 'o';
else return 'X';
}
}
</code></pre>
<p>*</p>
<pre><code>import java.util.InputMismatchException;
import java.util.Scanner;
public class Menu {
private Settings settings;
private byte play_state = 0; //before first game or after {0;1}
public Menu(Settings settings,byte play_state){
this.settings = settings;
this.play_state = play_state;
}
public byte get_play_state() {
return play_state;
}
private void print_menu(){
System.out.println("---MENU---");
System.out.println("1. New Game");
System.out.println("2. Settings");
System.out.println("3. Scoreboard");//not working yet
System.out.println("4. Exit");
}
private void print_end_menu(){ //after game lose
System.out.println("---MENU---");
System.out.println("1. Play Again");
System.out.println("2. New Game");
System.out.println("3. Settings");
System.out.println("4. Scoreboard");//not working yet
System.out.println("5. Exit");
}
public void run_menu(){
if(play_state == 0) {
print_menu();
}
else{
print_end_menu();
}
boolean flag=true;
boolean exception_flag=false;
int value;
do {
do {
try {
Scanner input = new Scanner(System.in);
value = input.nextInt() - play_state;
exception_flag = true;
}catch(InputMismatchException e){
value = -1;
}
if (value < (1 - play_state)|| value > 4 || !exception_flag) {
System.out.println("You wrote wrong input. Do it again: ");
}
} while (value < (1 - play_state) || value > 4);
if(value == 2) { //enters game settings
settings.change_settings();
}
else if(value == 3){ //enters scoarboard
System.out.println("SCOREBOARD");
}
else if(value == 4){
System.exit(1);
}
if(play_state == 0){
if(value == 1) flag = false;
else print_menu();
}
else if(play_state == 1){
if(value == 0 || value == 1) {
flag = false;
if(value == 1) play_state = 0; //changing play_state to execute right set_game function
}
else print_end_menu();
}
}while(flag);//player must select game or exit
}
}
</code></pre>
<p>*</p>
<pre><code>import java.util.InputMismatchException;
import java.util.Scanner;
public class Settings {
private byte standart_data_style=1;//data_style --> way of getting icons position from players
private String[] data_styles = new String [2];
private byte last_data_style;
//datas required to make option "play again" with last set settings
private int last_board_size;
private int last_game_mode;
private int last_starting_icon;
private int last_player1_icon;
public Settings(){
data_styles[0] = "sequence";
data_styles[1] = "numberpad (works only with board size 3)";
}
public byte get_standart_data_style() {
return standart_data_style;
}
public void set_last_data_style(byte last_data_style) {
this.last_data_style = last_data_style;
}
public void set_last_board_size(int last_board_size) {
this.last_board_size = last_board_size;
}
public void set_last_game_mode(int last_game_mode) {
this.last_game_mode = last_game_mode;
}
public int get_last_starting_icon() {
return last_starting_icon;
}
public void set_last_starting_icon(int last_starting_icon) {
this.last_starting_icon = last_starting_icon;
}
public void set_last_player1_icon(int last_player1_icon) {
this.last_player1_icon = last_player1_icon;
}
public void print_settings(){
System.out.println("---SETTINGS---");
System.out.println("1. Data_style: " + data_styles[standart_data_style-1]);
System.out.println("2. Exit");
System.out.println("");
System.out.println("If you want to change them. Write a number of chosen setting and then write another value");
}
public void print_data_styles(){
System.out.println("---DATA STYLES---");
System.out.println("1. " + data_styles[0]);
System.out.println("2. " + data_styles[1]);
}
private int get_valu_2(){
int value;
do {
System.out.println("Write new value");
try {
Scanner input = new Scanner(System.in);
value = input.nextInt();
}catch(InputMismatchException e){
value = -1;
}
if(value!=1 && value!=2) {
System.out.println("You wrote wrong number. Do it again: ");
}
}while(value != 1 && value != 2);
return value;
}
private int get_value(int min, int max){
int value = -1;
boolean flag = false;
boolean exception_flag = false;
while(!flag){
try{
Scanner input = new Scanner(System.in);
value = input.nextInt();
exception_flag = true;
}catch(InputMismatchException e){
System.out.println("Wrog input!");
}
if(exception_flag && value >= min && value <= max) flag = true;
if(value < min || value > max){
System.out.println("Number should be between " + min +" and " + max);
}
}
return value;
}
public void change_settings(){
int value;
do {
print_settings();
value = get_value(1,2);
if(value == 1) {
print_data_styles();
standart_data_style = (byte)get_value(1,2);
}
}while(value!=2);
}
}
</code></pre>
<p>*</p>
<pre><code>import java.util.Scanner;
import java.util.InputMismatchException;
public class GameSettings {
private int number_game_mode;
private int number_starting_icon;
private int player1_icon; //1. X 2. o
private int board_size;
private int bot_lvl=0;
public int get_board_size(){
return board_size;
}
public int get_player1_icon(){
return player1_icon;
}
public int get_number_game_mode(){
return number_game_mode;
}
public int get_number_starting_icon(){
return number_starting_icon;
}
public int get_bot_lvl(){return bot_lvl;}
private void print_game_mode(){
System.out.println("Set your game mode");
System.out.println("1. Player vs Player");
System.out.println("2. Player vs bot");
}
private void print_starting_icon() {
System.out.println("Who starts?");
System.out.println("1. X");
System.out.println("2. o");
}
private void print_player1_icon(){
System.out.println("Select icon for P1: ");
System.out.println("1. 'X'");
System.out.println("2. 'o'");
}
private void print_bot_lvl(){
System.out.println("Choose bot difficulty: ");
System.out.println("1. 'God' ");
System.out.println("2. 'Average' ");
System.out.println("3. 'Easy' ");
}
private void print_board_size(){
System.out.println("Board is always a square");
System.out.println("Enter a size of side <3-10> : ");
System.out.println("Playing with bot is anable only with board size 3");
}
private int get_value(int min, int max){
int value = -1;
boolean flag = false;
boolean exception_flag = false;
while(!flag){
try{
Scanner input = new Scanner(System.in);
value = input.nextInt();
exception_flag = true;
}catch(InputMismatchException e){
System.out.println("Wrog input!");
}
if(exception_flag && value >= min && value <= max) flag = true;
if(value < min || value > max){
System.out.println("Number should be between " + min +" and " + max);
}
}
return value;
}
public void select_settings() {
print_board_size();
board_size = get_value(3,10);
if(board_size==3){
print_game_mode();
number_game_mode = get_value(1,2);
}
else{
number_game_mode = 1;
}
if(number_game_mode == 2){
print_bot_lvl();
bot_lvl = get_value(1,3);
}
print_starting_icon();
number_starting_icon = get_value(1,2);
print_player1_icon();
player1_icon = get_value(1,2);
}
}
</code></pre>
<p>*</p>
<pre><code>public class Map {
private int size;
private int winning_length;
private char[][] board;
Map(int size, int winning_length){
this.size = size;
this.winning_length = winning_length;
board = new char[size][size];
}
public void print_map() {
{
System.out.println("WINNING LENGTH: " + winning_length);
//drawing first row
for(int j=0; j<size-1;j++){
System.out.print(board[0][j] + "|");
}
System.out.println(board[0][size-1]);
//drawing all middle rows
for(int i=1; i<size-1;i++){
for(int l=0;l<size-1;l++){
System.out.print("-+");
}
System.out.println("-");
for(int k=0;k<size-1;k++){
System.out.print(board[i][k] + "|");
}
System.out.println(board[i][size-1]);
}
for(int l=0;l<size-1;l++){
System.out.print("-+");
}
System.out.println("-");
//drawing last row
for (int j=0; j<size-1;j++){
System.out.print(board[size-1][j] + "|");
}
System.out.println(board[size-1][size-1]);
}
}
public void clean(){
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
board[i][j] = ' ';
}
}
}
public boolean check_cell_empty(int x,int y){
if(board[y][x]=='X') return false;
else if(board[y][x]=='o')return false;
return true;
}
public int get_map_size(){return size;}
public void set_cell_icon(int x, int y, char icon) {
board[y][x] = icon;
}
public char get_cell_icon(int x, int y) { return board[y][x]; }
public boolean check_map_full(){
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
if(board[i][j]!='X'&&board[i][j]!='o') return false;
}
}
return true;
}
public boolean check_horizontal(int x,int y, char given_icon){
for(int i=0;i<winning_length;i++)
{
if(board[y][x+i]!=given_icon) return false;
}
return true;
}
public boolean check_vertical(int x, int y, char given_icon){
for(int i=0;i<winning_length;i++)
{
if(board[y+i][x]!=given_icon) return false;
}
return true;
}
public boolean check_diagonally_right(int x, int y, char given_icon){
for(int i=0;i<winning_length;i++)
{
if(board[y+i][x+i]!=given_icon) return false;
}
return true;
}
public boolean check_diagonally_left(int x, int y, char given_icon){
for(int i=0;i<winning_length;i++)
{
if(board[y+i][x-i]!=given_icon) return false;
}
return true;
}
public boolean check_win(char icon){
boolean flag = false;
for(int i=0;i<size;i++) {
for(int j=0;j<size;j++){
if(j<=size-winning_length) {
if(check_horizontal(j,i,icon)) flag = true;
}
if(i<=size-winning_length) {
if(check_vertical(j,i,icon)) flag = true;
}
if(j<=size-winning_length && i<=size-winning_length) {
if(check_diagonally_right(j,i,icon)) flag = true;
}
if(j>=winning_length-1 && i<=size-winning_length) {
if(check_diagonally_left(j,i,icon)) flag = true;
}
}
}
return flag;
}
public byte check_game_condtion(){
if(check_win('X')) return 10;//X won
if(check_win('o')) return -10;//o won
if(check_map_full()) return 0; //tie
return 2; //still playing
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T10:47:48.120",
"Id": "474620",
"Score": "1",
"body": "... so much to review, so little time ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T10:56:00.267",
"Id": "475557",
"Score": "0",
"body": "thank you very much for sharing your project!!! happy Coding!"
}
] |
[
{
"body": "<p>Building the application structure for your project was a challenge.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8IrhH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8IrhH.png\" alt=\"Project\"></a></p>\n\n<p>After I copied your classes into a Java project I created on my Eclipse IDE, your code has 11 compiler warnings.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iu3p6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iu3p6.png\" alt=\"Compiler warnings\"></a></p>\n\n<p>When I tried to move the <code>Player</code>, <code>PlayerHuman</code>, and <code>Bot</code> classes into their own package to organize the code better, I got 9 compiler errors in the <code>Play</code> class. This tells me that you're referencing package-private variables. This is not a good practice. Keep all class variables private and use getters to get the values.</p>\n\n<p>You named one of your classes <code>Map</code>. This confused me because I thought you were referring to a <code>java.util.Map</code> interface. Don't name your classes the same as standard Java classes. <code>GameMap</code> might be a better class name.</p>\n\n<p>Hyphenated field names and method names like <code>play_state</code> aren't the Java coding convention. Generally, Java field names and method names are camelCase, like <code>playState</code>.</p>\n\n<p>I ran your code once. I wasn't sure how to input a move. Fortunately, I let the bot go first, so I saw that you typed coordinates. It would be easier for the player to enter one number, 1 - 9 for a 3x3 board, 1 - 16 for a 4x4 board, and so on. The code would translate that into two coordinates. </p>\n\n<p>I liked that you separated the concerns of the application into individual classes. I liked the <code>Game</code> class. I liked that you created an abstract <code>Player</code> class, and extended it to create the <code>PlayerHuman</code> and <code>Bot</code> classes.</p>\n\n<p>In your Menu class, you have two separate menus. It would have been easier on your part and more consistent for the players if you combined them into one menu. Something like this.</p>\n\n<pre><code>private void printMenu(boolean endMenu) {\n System.out.println(\"---MENU---\");\n System.out.println(\"1. New Game\");\n System.out.println(\"2. Settings\");\n System.out.println(\"3. Scoreboard\");// not working yet\n if (endMenu) {\n System.out.println(\"4. Play Again\");\n }\n System.out.println(\"9. Exit\");\n}\n</code></pre>\n\n<p>Overall, a really good effort at separation of concerns. Keep it up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T15:16:26.660",
"Id": "474674",
"Score": "0",
"body": "Hello ! I really appreciate your comment. Firstly I know I need to focus on a package in java. I just don't want anyone to have problem with opening my project. About java.util.Map interface I haven't heard before. I will keep it in mind. The mistake with calling variables and function etc. I read when I was in the middle of doing it. I didn't want to change every name, so I continue to do my own convention (Of course I will change it in next work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T15:16:45.237",
"Id": "474675",
"Score": "0",
"body": "There are 2 way of inputing moves. I didn't explain it (that's why it might be confusing). In settings it's possible to enter a moves as a number pad(simmilar what You mention), but it only works with 3x3 map. Once more I want to thank you. That was my first code share, I didn't know what should I expect. I will keep in mind every advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T18:58:34.430",
"Id": "474691",
"Score": "0",
"body": "`Board` would be an obvious choice of name for something that represents that state of the Tic Tac Toe game board. And yes, agreed, move entry should be set up so you can play using the num pad, whose shape matches a 3x3 TTT board."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:18:50.033",
"Id": "241877",
"ParentId": "241871",
"Score": "9"
}
},
{
"body": "<h2>Coding style guide</h2>\n\n<p>well, simply one: Java <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">uses CamelCase</a> for methods not underlines eg. <code>game1.do_game();</code> would be <code>game1.doGame();</code></p>\n\n<h2>naming</h2>\n\n<ul>\n<li>i have a little problem with your namings, see for example <code>Play game1 = new Play();</code> is it a game or is it a play? </li>\n<li>same applies here: <code>private Map board;</code> - should the class be renamed? or is the name of the variable chosen poorly?</li>\n<li>same applies here: <code>Menu start = new Menu;</code> - since it's the only menu in this context</li>\n<li><code>Menu.run_menu();</code> should be renamed into <code>Menu.printRunMenu</code> as all other methods have such an suffix - and: It is far more precise than a mere <code>runMenu()</code></li>\n<li><code>Play.do_game()</code> is misleading, you play a party, so why don't you name it this way? <code>Play.playParty()</code> - but now it's obvious that <code>Play</code> should be renamed into <code>Game</code> as you realized on your own, when you named the instance of <code>Play</code> <code>game1</code></li>\n<li>naming pun: <code>Play.make_move(Player player)</code> vs <code>Player.do_move(...);</code> - they should share the same name because they do (technically) the same thing!</li>\n<li><code>Player.check_coords(x,y);</code> is misleading since it's not clear WHAT you check. maybe it should be renamed into <code>Player.isInside(x,y);</code> which leads to the next question: Why is it on <code>Player</code> and not on the <code>Board</code> ?</li>\n<li>in your loops you could use the proper names for your variables - instead of <code>for (int i = 0; i < map_size; i++)</code> and <code>for (int j = 0; j < map_size; j++)</code> you could use <code>for (int x = 0; x < map_size; x++)</code> and <code>for (int y = 0; y < map_size; y++)</code> </li>\n</ul>\n\n<h2>primitive obssesion</h2>\n\n<ul>\n<li><code>private byte play_state = 0;</code> instead of using cryptic bytes as states use an <code>Enum</code> - such an enum contains cleary readable state names, that anyone can handle... what is <code>state 0</code>?</li>\n<li>why not se a class for your <code>Icon</code>? is a <code>char</code> really good enough for an icon (<code>char tmp_icon;</code>) - this also violates the <a href=\"https://blog.cleancoder.com/uncle-bob/2014/05/12/TheOpenClosedPrinciple.html\" rel=\"nofollow noreferrer\">open/closed priniciple</a></li>\n<li>further on <code>Icon</code> as class: it could replace the method <code>Bot.another_icon()</code></li>\n<li>this draws further circles where icon is mis-used: <code>int starting_icon</code> ... now it's an <code>int</code> - that confuses me further - instead use a proper class for that (an <code>Enum</code> would be sufficent here as well)</li>\n<li>same applied for <code>int bot_level</code> - instead give your bot class an enum of level - <code>Bot.Level.POOR</code> would be far more precise! </li>\n<li>same for <code>game_mode</code> (i wont <a href=\"https://clean-code-developer.com/grades/grade-1-red/#Don8217t_Repeat_Yourself_DRY\" rel=\"nofollow noreferrer\">DRY</a> here) </li>\n<li>same for <code>game_condition</code></li>\n<li>same for <code>data_style</code></li>\n</ul>\n\n<h2>segregation of concerns</h2>\n\n<ul>\n<li>the <code>HumanPlayer</code> class should not be responsible for input handling <code>get_cords_in_seq()</code>, <code>get_cords_as_board()</code> - write a class for this responsibility</li>\n<li>same for <code>Settings.get_value</code> and <code>Settings.get_valu_2</code> (also: typo here)</li>\n<li>same for <code>GameSettings.</code></li>\n</ul>\n\n<h2>program logic</h2>\n\n<p>it would be more easy to read if you reformat the condition at <code>PlayerHuman.do_move()</code> - first come the check conditions then comes the code executed (removes redundancy):</p>\n\n<pre><code>if (map.isOutside(x,y)) {//abort criteria\n System.out.println(\"Your cords should be beetween 0-\" + (map.map_size-1));\n return; //aborts as expected\n} \nif (map.isCellOccupied(x, y)) { //another abort criteria\n System.out.println(\"This cell is already occupied\");\n return; //aborts as expected\n}\n\nmap.print_map();\ndo_move(map); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T17:25:43.643",
"Id": "475728",
"Score": "1",
"body": "Thank you for all of your suggestions. I've already changed some parts of a code, which was mentioned in a previous answer. I will do the same with your advices. Once again, thank you a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T10:55:22.693",
"Id": "242331",
"ParentId": "241871",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241877",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T10:00:16.883",
"Id": "241871",
"Score": "5",
"Tags": [
"java",
"object-oriented"
],
"Title": "Developed TicTacToe game"
}
|
241871
|
<p>So, I am trying to generate a web-page template with JavaScript according to user specified values. I tested it with just <code>background-color</code> and made it working.</p>
<p>I wanted <strong>to add a bunch of new elements</strong>. Also I need <strong>to add style to each elements</strong>. I am able to do it with the current code.</p>
<p>But the problem I am having is that the code is becoming <strong>"TOO HARD TO READ"</strong>. And I don't think I'm writing clean code. So, the question I have for you fellow Dev's is that is there another way to achieve this - with just <strong>pure JavaScript (vanilla JS)</strong>. That is:-</p>
<ul>
<li>To add specific elements separately.</li>
<li>To style those elements also separately.</li>
</ul>
<p>EDIT: I have updated the finished project. It's readable. But I would like to <strong>NOT</strong> use <code>document.write</code> as it is wasting time for me to read and understand. I would get stuck if I wanted to edit it later on... Please any other way you can suggest..</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 renderForm(){
var bgc = document.getElementById("bgcolor").value;
var nc = document.getElementById("ncolor").value;
var tc = document.getElementById("tcolor").value;
var nm = document.getElementById("ntext").value;
window.alert("Confirm To NUKE!");
var generateTemplate = window.open("","_self");
generateTemplate.document.write('<!DOCTYPE html><html><head><title>Incoming Nuke!</title></head><body style="background-color:'+bgc+'">');
generateTemplate.document.write('<style>:root{ --main-nuke-color: '+nc+'; --main-text-color: '+tc+'; } .box{ position:absolute; display: block; height: 500px; width: 500px; animation-name: drop;animation-duration: 4s; animation-iteration-count: infinite;animation-direction:normal; animation-timing-function: linear; } .nhead{position: relative; display: block; height: 450px; width: 200px;border-radius: 50%; top: 20%; left: 15%; background-color:var(--main-nuke-color); transform: rotate(45deg); z-index: 9; } .nend{ position: absolute;display: block; width: 0; height: 0; border-top: 100px solid transparent;border-right: 100px solid var(--main-nuke-color); border-bottom: 100px solid transparent; top: 20%; left: 50%; transform: rotate(-45deg); } .ntailleft{position: absolute; display: block; width: 0; height: 0; border-top: 80px solid transparent; border-right: 80px solid var(--main-nuke-color);border-bottom: 80px solid transparent; top: 3%; left: 53%; transform:rotate(0deg); } .ntailright{ position: absolute; display: block; width: 0;height: 0; border-top: 80px solid transparent; border-right: 80px solid var(--main-nuke-color); border-bottom: 80px solid transparent; top: 23%; left:73%; transform: rotate(270deg); } .ntailmiddle{ position: absolute; display:block; width: 0; height: 0; border-top: 80px solid transparent; border-right:80px solid var(--main-nuke-color); border-bottom: 80px solid transparent;top: 10%; left: 65%; transform: rotate(135deg); } .text{ position: absolute;display: block; font-size: 90px; transform: rotate(-90deg); top: 35%; left:-62%; color: var(--main-text-color); word-wrap: break-word; white-space: nowrap; width: 430px; overflow: hidden; text-overflow: ellipsis; }div.text:hover { overflow: visible; }@keyframes drop{ 0%{ top: -50%; left: 100%; } 100%{ top: 100%; left: -50%; } }</style>');
generateTemplate.document.write('<div class="box"><div class="nhead"><div class="text">'+nm+'</div></div><div class="nend"></div><div class="ntailleft"></div><div class="ntailright"></div><div class="ntailmiddle"></div></div>');
generateTemplate.document.write('</body></html>');
}
function initMyEvents(){
document.getElementById("nuked").onclick = renderForm;
}
window.onload = initMyEvents;</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Geo&display=swap');
body{
text-align: center;
background-color: #cccccc;
font-family: 'Geo', sans-serif;
font-size: 30px;
}
.customizerTable{
margin: auto;
}
.button{
border: none;
align-items: center;
background-color: rgb(204,204,204);
box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.25), -2px -2px 4px 0 rgba(255, 255, 255, 0.3);
border-radius: 50px;
display: flex;
justify-content: center;
margin: auto;
margin-left: 0;
margin-top: 5%;
padding: 5%;
width: 50%;
cursor: pointer;
outline: none;
text-decoration: none;
}
.button:active{
box-shadow: -2px -2px 4px 0 rgba(255, 255, 255, 0.3) inset, 2px 2px 4px 0 rgba(0, 0, 0, 0.25) inset;
}
.card{
border: none;
align-items: center;
background-color: rgb(204,204,204);
box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.25), -2px -2px 4px 0 rgba(255, 255, 255, 0.3);
border-radius: 50px;
display: flex;
justify-content: center;
margin: auto;
padding: 10%;
width: 100%;
}
.customizeField{
/*TEST 1*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/*TEST 1*/
}
.textbutton{
border: none;
align-items: center;
background-color: rgb(204,204,204);
box-shadow: -2px -2px 4px 0 rgba(255, 255, 255, 0.3) inset, 2px 2px 4px 0 rgba(0, 0, 0, 0.25) inset;
border-radius: 50px;
display: flex;
justify-content: center;
margin: auto;
margin-left: 0;
margin-top: 5%;
padding: 5%;
width: 50%;
cursor: pointer;
outline: none;
text-decoration: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="customizeField">
<tr>
<td>
<div class="card">
<div>Customize</div>
<table class="customizerTable">
<tr>
<td>Background color:</td>
<td><input type="color" id="bgcolor" name="bgcolor" value="#80ccff" class="button"></td>
</tr>
<tr>
<td>Nuke color:</td>
<td><input type="color" id="ncolor" name="ncolor" value="#262626" class="button"></td>
</tr>
<tr>
<td>Text color:</td>
<td><input type="color" id="tcolor" name="tcolor" value="#e6e600" class="button"></td>
</tr>
<tr>
<td>Enter Nuke Code:</td>
<td><input type="text" id="ntext" name="ntext" maxlength="6" class="textbutton" value="#NUKED"></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<a type="submit" value="Submit it!" class="button" id="nuked">NUKE!</a>
</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:28:07.540",
"Id": "474634",
"Score": "0",
"body": "To me, your code looks quite short and very easy to read. There are some minor best-practices that could be implemented, but nothing stands out as in serious need of improvement. Is this the *actual* full code you're using that you find too ugly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:31:11.880",
"Id": "474635",
"Score": "0",
"body": "Actually I have to start adding a lot more elements. I really needed to understand this before I re-code my entire script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:32:13.580",
"Id": "474636",
"Score": "0",
"body": "It's good to learn first, no? So, I can choose the best way possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:33:54.697",
"Id": "474637",
"Score": "1",
"body": "Per the rules here, you should implement the code (even if it's ugly) for the multiple elements in order for it to be reviewed. It's not clear what you want with multiple elements either"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T03:03:48.817",
"Id": "474970",
"Score": "0",
"body": "Hey, sorry I'm late but. I didn't want to bother you since I actually completed this. But I would like to know if you could tell me another way to do this without using `document.write'. It really makes my code hard to edit, later. It's not a big project. But I want to know this. I don't like how I added all those CSS styles. If I wanted to change it, I might break everything. \n\nI want to share this code for any code newbie to understand. But right now it is not worth it, I guess..."
}
] |
[
{
"body": "<p>The main issue that will make your code readable is to use <em>template literals</em> instead of <code>'</code> and <code>\"</code> string literals when constructing the HTML. Template literals allow for the writing of <em>readable, multiline</em> strings, as well as easy interpolation. For example, the following line:</p>\n\n<pre><code>document.write('<style>:root{ --someVar: ' + someValue + '}</style><div>foo</div><div>bar</div>');\n</code></pre>\n\n<p>can be written as:</p>\n\n<pre><code>document.write(`\n <style>\n :root {\n --someVar: ${someValue}\n }\n </style>\n <div>foo</div>\n <div>bar</div>\n`);\n</code></pre>\n\n<p>By following this sort of pattern, your <code>document.write</code> strings become <em>much</em> nicer to read and comprehend.</p>\n\n<p>Other possible improvements:</p>\n\n<p>It's good to use informative variable names that give you a good sense of what the variable holds on sight. For example, if someone else saw the line</p>\n\n<pre><code>var tc = document.getElementById(\"tcolor\").value;\n</code></pre>\n\n<p>They probably wouldn't have any idea what <code>tc</code> is supposed to be except by examining where else the <code>tc</code> variable is referenced.</p>\n\n<p>Your current method of getting the value of each input separately is a bit WET, too. You might consider selecting <em>all</em> inputs in the document (or form) at once, somehow. One option is to use <code>querySelectorAll</code>, map each element to its value, then destructure into the variables:</p>\n\n<pre><code>const [\n backgroundColor,\n nukeColor,\n textColor,\n nukeCode,\n] = [...document.querySelectorAll('input')].map(input => input.value);\n</code></pre>\n\n<p>That's short and reasonably elegant, but not entirely maintainable if you ever decide to remove/add an input or change their order. You could iterate over the inputs and put their values into an object instead:</p>\n\n<pre><code>const inputValues = {};\nfor (const input of document.querySelectorAll('input')) {\n inputValues[input.name] = input.value;\n}\n</code></pre>\n\n<p>Once the user presses submit, they're presented \"Confirm to nuke\", but don't have any choice in the matter. Consider using <code>window.confirm</code> instead of <code>window.alert</code> to give them the option to cancel (or change the wording to \"Nuke launching...\").</p>\n\n<p>You create a window with <code>window.open</code> and put into a variable named <code>generateTemplate</code>. That's a confusingly odd name for a <code>window</code> object - consider something like <code>newWindow</code> instead.</p>\n\n<p>Creating a new window like this is a bit odd. If it's required for some reason, that's fine, but <em>usually</em> it would make more sense to stay on the current page and replace the necessary content.</p>\n\n<p>It's usually a good idea to avoid assigning to <code>onclick</code> properties, because they only permit a <em>single</em> listener - if another script assigns to the <code>onclick</code> too, the earlier listener will be lost. Best to use <code>addEventListener</code> instead - even if you don't plan on adding additional listeners, it's a good habit to get into.</p>\n\n<p>Same sort of thing for <code>window.onload</code>. Though, it'd probably be better to listen for the <code>DOMContentLoaded</code> listener, which doesn't wait for images and other media to load first - or, even better, have the initial JS run after the page is loaded to avoid having to handle any such events - either put the script in a separate file and give it the <code>defer</code> attribute:</p>\n\n<pre><code><script src=\"myscript.js\" defer>\n</code></pre>\n\n<p>Or put it at the bottom of the <code><body></code>:</p>\n\n<pre><code> ... page content\n <script src=\"myscript.js\">\n</body>\n</code></pre>\n\n<p><code>document.write</code> is weird to use nowadays. Better to use more trustworthy and modern methods of DOM manipulation, like with <code>document.createElement</code> or <code>insertAdjacentHTML</code> to insert elements. To set the document title, assign to <code>myWindow.document.title</code>.</p>\n\n<p>Inside the created window, creating so much CSS dynamically is odd. If possible, use a <em>separate file</em> for the bulky CSS and link to it. This way, all you have to do dynamically is set the CSS variables:</p>\n\n<pre><code>myWindow.document.body.insertAdjacentHTML('beforeend', '<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">');\nmyWindow.document.body.insertAdjacentHTML('beforeend', `\n <style>\n :root {\n background-color: ${inputValues.backgroundColor};\n --main-nuke-color: ${inputValues.nukeColor};\n --main-text-color: ${inputValues.textColor}\n }\n </style>\n`);\n</code></pre>\n\n<p>All together, you get:</p>\n\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>function renderNuke() {\n const inputValues = {};\n for (const input of document.querySelectorAll('input')) {\n inputValues[input.name] = input.value;\n }\n if (!window.confirm(\"Confirm To NUKE!\")) return;\n const newWindow = window.open(\"\", \"_self\");\n newWindow.document.title = 'Incoming Nuke!';\n newWindow.document.body.innerHTML = `\n <style>\n :root {\n background-color: ${inputValues.backgroundColor};\n --main-nuke-color: ${inputValues.nukeColor};\n --main-text-color: ${inputValues.textColor}\n }\n\n .box {\n position: absolute;\n display: block;\n height: 500px;\n width: 500px;\n animation-name: drop;\n animation-duration: 4s;\n animation-iteration-count: infinite;\n animation-direction: normal;\n animation-timing-function: linear;\n }\n\n .nhead {\n position: relative;\n display: block;\n height: 450px;\n width: 200px;\n border-radius: 50%;\n top: 20%;\n left: 15%;\n background-color: var(--main-nuke-color);\n transform: rotate(45deg);\n z-index: 9;\n }\n\n .nend {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-top: 100px solid transparent;\n border-right: 100px solid var(--main-nuke-color);\n border-bottom: 100px solid transparent;\n top: 20%;\n left: 50%;\n transform: rotate(-45deg);\n }\n\n .ntailleft {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-top: 80px solid transparent;\n border-right: 80px solid var(--main-nuke-color);\n border-bottom: 80px solid transparent;\n top: 3%;\n left: 53%;\n transform: rotate(0deg);\n }\n\n .ntailright {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-top: 80px solid transparent;\n border-right: 80px solid var(--main-nuke-color);\n border-bottom: 80px solid transparent;\n top: 23%;\n left: 73%;\n transform: rotate(270deg);\n }\n\n .ntailmiddle {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-top: 80px solid transparent;\n border-right: 80px solid var(--main-nuke-color);\n border-bottom: 80px solid transparent;\n top: 10%;\n left: 65%;\n transform: rotate(135deg);\n }\n\n .text {\n position: absolute;\n display: block;\n font-size: 90px;\n transform: rotate(-90deg);\n top: 35%;\n left: -62%;\n color: var(--main-text-color);\n word-wrap: break-word;\n white-space: nowrap;\n width: 430px;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n div.text:hover {\n overflow: visible;\n }\n\n @keyframes drop {\n 0% {\n top: -50%;\n left: 100%;\n }\n\n 100% {\n top: 100%;\n left: -50%;\n }\n }\n </style>\n <div class=\"box\">\n <div class=\"nhead\">\n <div class=\"text\">${inputValues.nukeCode}</div>\n </div>\n <div class=\"nend\"></div>\n <div class=\"ntailleft\"></div>\n <div class=\"ntailright\"></div>\n <div class=\"ntailmiddle\"></div>\n </div>\n `;\n}\n\ndocument.getElementById(\"nuked\").addEventListener('click', renderNuke);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@import url('https://fonts.googleapis.com/css2?family=Geo&display=swap');\nbody {\n text-align: center;\n background-color: #cccccc;\n font-family: 'Geo', sans-serif;\n font-size: 30px;\n}\n\n.customizerTable {\n margin: auto;\n}\n\n.button {\n border: none;\n align-items: center;\n background-color: rgb(204, 204, 204);\n box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.25), -2px -2px 4px 0 rgba(255, 255, 255, 0.3);\n border-radius: 50px;\n display: flex;\n justify-content: center;\n margin: auto;\n margin-left: 0;\n margin-top: 5%;\n padding: 5%;\n width: 50%;\n cursor: pointer;\n outline: none;\n text-decoration: none;\n}\n\n.button:active {\n box-shadow: -2px -2px 4px 0 rgba(255, 255, 255, 0.3) inset, 2px 2px 4px 0 rgba(0, 0, 0, 0.25) inset;\n}\n\n.card {\n border: none;\n align-items: center;\n background-color: rgb(204, 204, 204);\n box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.25), -2px -2px 4px 0 rgba(255, 255, 255, 0.3);\n border-radius: 50px;\n display: flex;\n justify-content: center;\n margin: auto;\n padding: 10%;\n width: 100%;\n}\n\n.customizeField {\n /*TEST 1*/\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n /*TEST 1*/\n}\n\n.textbutton {\n border: none;\n align-items: center;\n background-color: rgb(204, 204, 204);\n box-shadow: -2px -2px 4px 0 rgba(255, 255, 255, 0.3) inset, 2px 2px 4px 0 rgba(0, 0, 0, 0.25) inset;\n border-radius: 50px;\n display: flex;\n justify-content: center;\n margin: auto;\n margin-left: 0;\n margin-top: 5%;\n padding: 5%;\n width: 50%;\n cursor: pointer;\n outline: none;\n text-decoration: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><table class=\"customizeField\">\n <tr>\n <td>\n <div class=\"card\">\n <div>Customize</div>\n <table class=\"customizerTable\">\n <tr>\n <td>Background color:</td>\n <td><input name=\"backgroundColor\" type=\"color\" value=\"#80ccff\" class=\"button\"></td>\n </tr>\n <tr>\n <td>Nuke color:</td>\n <td><input name=\"nukeColor\" type=\"color\" value=\"#262626\" class=\"button\"></td>\n </tr>\n <tr>\n <td>Text color:</td>\n <td><input name=\"textColor\" type=\"color\" value=\"#e6e600\" class=\"button\"></td>\n </tr>\n <tr>\n <td>Enter Nuke Code:</td>\n <td><input name=\"nukeCode\" class=\"textbutton\" value=\"#NUKED\"></td>\n </tr>\n </table>\n </div>\n </td>\n </tr>\n <tr>\n <td>\n <a type=\"submit\" value=\"Submit it!\" class=\"button\" id=\"nuked\">NUKE!</a>\n </td>\n </tr>\n</table></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-05-10T14:52:29.373",
"Id": "242039",
"ParentId": "241878",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242039",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T11:24:29.427",
"Id": "241878",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"dom"
],
"Title": "Generating a new web-page template and adding multiple new elements with pure JavaScript?"
}
|
241878
|
<p>I have a API and the corresponding service method is like this:</p>
<pre><code>@Transactional
public List<Object> getData(args) {
databaseStatements;
databaseStatementsOnOtherThread();
NetworkCallStatements;
CPUBoundStatements(calculation, sorting, etc)
}
</code></pre>
<p>With this setup, each request holds a database connection as I have <code>@Transactional</code> annotation on the method. So If I have 5 connections to database, I was able to serve only 5 requests concurrently. Other requests are waiting for database connection and gets timed-out.<br/><br/>
I have refactored this method to avoid blocking of database connection during network and CPU tasks:</p>
<pre><code>public List<Object> getData(args) {
getDataFromDatabase1();
databaseStatementsOnOtherThread();
getDataFromDatabase2();
NetworkCallStatements;
CPUBoundStatements(calculation, sorting, etc)
}
/* The below methods are from different classes as @Transactional will not effect in same class */
@Transactional
public Data1 getDataFromDatabase1() {
//some statements
}
@Transactional
public Data2 getDataFromDatabase2() {
//some statements
}
</code></pre>
<p>As I have removed <code>@Transactional</code> annotation from main method and added to sub methods having only database calls, connection will not be blocked during network calls and CPU tasks. This gives a very good result as I am able to serve more no of requests with less no of connections and the failure rate also reduced.<br/><br/>
Now the problem is when there is one or two requests at a time (or very few requests), the response time has been increased from the previous version. What I feel is, earlier I was obtaining database connection one time, now obtaining 2 or more time(one for each sub methods) which may cause this slowness.<br/></p>
<ol>
<li><p>Whether my understanding is correct?</p></li>
<li><p>How can I organize the sub methods into a single method to obtain the connection only once? All these sub methods are returning different data types and also I cannot have them in the same class due to <code>@Transactional</code> limitations. Any idea to overcome the above problems?</p></li>
<li>Or can I refactor the initial version of <code>getData</code> differently?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:38:17.150",
"Id": "477392",
"Score": "0",
"body": "Please post a sample app to reproduce the problem."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:20:16.583",
"Id": "241882",
"Score": "3",
"Tags": [
"java",
"spring",
"hibernate",
"transactions"
],
"Title": "Separation of database and network calls"
}
|
241882
|
<p>As a beginner I wrote my first program (calculator) with Python and as far as functionality is concerned it just works fine but I have some concerns about one thing at the end of the code. Under <code>CalculateAgain()</code> in the <code>if</code> statement, <code>Calculate()</code> is without the <code>return</code> statement. If I used it, it would just run the function one time and then it exits the program. That's why i left it without the statement. Is this ok or should I change something?</p>
<pre><code>#Choose the operation
def OperationType():
while True:
Type = input('What type of operation do you want? +, -, *, /: \n')
if Type in ('+', '-', '*', '/'):
return Type
else:
print('Invalid input')
#Enter the first number
def InputFirstNumber():
while True:
try:
firstNumber = float(input('Enter your first number: '))
return firstNumber
except ValueError:
print ('Please enter a number')
#Enter the second number
def InputSecondNumber():
while True:
try:
secondNumber = float(input('Enter your second number: '))
return secondNumber
except ValueError:
print ('Please enter a number')
#Calculating
def Calculate():
Type = OperationType()
firstNumber = InputFirstNumber()
secondNumber = InputSecondNumber()
if Type == '+':
print('{} + {} = '.format(firstNumber, secondNumber), firstNumber + secondNumber)
elif Type == '-':
print('{} - {} = '.format(firstNumber, secondNumber), firstNumber - secondNumber)
elif Type == '*':
print('{} * {} = '.format(firstNumber, secondNumber), firstNumber * secondNumber)
elif Type == '/':
print('{} / {} = '.format(firstNumber, secondNumber), firstNumber / secondNumber)
else:
print('Input not valid')
Calculate()
#Asks if the User want to calculate again
def CalculateAgain():
while True:
calculating_again = input('Do you want to calculate again? Y/N \n')
if calculating_again in ('Y','y'):
Calculate()
elif calculating_again in ('N','n'):
print('Quitting the program')
break
else:
print('Not a valid answer')
CalculateAgain()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:44:20.830",
"Id": "474670",
"Score": "0",
"body": "Can you fix the indentation? As of right now this isn't working code, which is deemed off topic for this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:55:41.453",
"Id": "474673",
"Score": "0",
"body": "Now it should work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T04:40:54.380",
"Id": "474735",
"Score": "0",
"body": "I would suggest that you make Calculate return a boolean value -- True if the calculator should continue, false if it should exit. Then call that function in Calculate. Python does not have an explicit repeat .. until construct but you can create the equivalent by using the same pattern you have used in all your input routines. Just wrap calculate in a while True: block, and `if notCalculateAgain(): break` Your program only need call Calculate() to run."
}
] |
[
{
"body": "<p>Here's a minor modification that eliminates the need to call CalculateAgain() after Calculate().</p>\n\n<pre><code>#Choose the operation\ndef OperationType():\n\n while True:\n\n Type = input('What type of operation do you want? +, -, *, /: \\n')\n\n if Type in ('+', '-', '*', '/'):\n return Type\n else:\n print('Invalid input')\n\n\n#Enter the first number\ndef InputFirstNumber():\n\n while True:\n try:\n firstNumber = float(input('Enter your first number: '))\n return firstNumber\n except ValueError:\n print ('Please enter a number')\n\n\n#Enter the second number\ndef InputSecondNumber():\n\n while True:\n try:\n secondNumber = float(input('Enter your second number: '))\n return secondNumber\n except ValueError:\n print ('Please enter a number')\n\n\n#Asks if the User want to calculate again\ndef CalculateAgain():\n\n while True:\n\n calculating_again = input('Do you want to calculate again? Y/N \\n')\n\n\n if calculating_again in ('Y','y'):\n return True\n\n elif calculating_again in ('N','n'):\n print('Quitting the program')\n return False\n\n else:\n print('Not a valid answer')\n\n\n#Calculating\ndef Calculate():\n while True:\n Type = OperationType()\n firstNumber = InputFirstNumber()\n secondNumber = InputSecondNumber()\n\n if Type == '+':\n print('{} + {} = '.format(firstNumber, secondNumber), firstNumber + secondNumber)\n\n elif Type == '-':\n print('{} - {} = '.format(firstNumber, secondNumber), firstNumber - secondNumber)\n\n elif Type == '*':\n print('{} * {} = '.format(firstNumber, secondNumber), firstNumber * secondNumber)\n\n elif Type == '/':\n print('{} / {} = '.format(firstNumber, secondNumber), firstNumber / secondNumber)\n\n else:\n print('Input not valid')\n\n if not CalculateAgain():\n break\n\nCalculate()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T04:49:25.540",
"Id": "241919",
"ParentId": "241883",
"Score": "1"
}
},
{
"body": "<p>This code is broken into multiple unnecessary functions. Below is all thats needed:</p>\n\n<pre><code>operations = {\n \"+\": lambda x, y: x + y,\n \"-\": lambda x, y: x - y,\n \"*\": lambda x, y: x * y,\n \"/\": lambda x, y: x / y\n}\n\ndef calculate():\n\n # Get numbers #\n one, two = input(\"Enter two numbers separated by a space: \").split()\n\n while operator := input(\"Enter an operator: + - * /\"):\n if operator in [\"+\", \"-\", \"*\", \"/\"]:\n print(operations[operator](int(one), int(two)))\n return\n</code></pre>\n\n<h1>Getting multiple values from input</h1>\n\n<p>Instead of prompting for each number, simply ask for two numbers separated by a space then split the input with a given delimiter, by default a space. <code>.split</code> returns a list, and since you only anticipate two values, can assign the output to <code>one, two</code>.</p>\n\n<h1>Walrus Operator</h1>\n\n<p>If you're using <code>python-3.8</code>, you can utilize the <a href=\"https://realpython.com/lessons/assignment-expressions/\" rel=\"nofollow noreferrer\">walrus operator</a>, also called assignment expressions. It allows you to assign and return a value in an expression. This reduces the need to define a variable before the loop and use it.</p>\n\n<h1>Checking <code>in</code></h1>\n\n<p>I do believe using a list/tuple instead of a string when checking <em>in this particular case</em> because it can catch some invalid input. A catch such as <code>if operator in \"+-*/\":</code>, it will allow \"+-\" as a valid operator, which we don't want. So good job there.</p>\n\n<h1>Lambdas</h1>\n\n<p>I've decided to use lambdas here because it's much easier to store them in a dictionary and then simply retrieve the value from the dictionary with the operator. If you want to learn more about how lambdas work, this <a href=\"https://www.google.com/search?q=python%20lambda&rlz=1C5CHFA_enUS855US855&oq=python%20lambda&aqs=chrome.0.0l8.1183j0j7&sourceid=chrome&ie=UTF-8\" rel=\"nofollow noreferrer\">Google Search</a> brings up a plethora of sources that can explain the concept much better than I can.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:50:02.860",
"Id": "474876",
"Score": "0",
"body": "Great answer. With that said, the poster did state in advance that they are a beginning programmer, and had a specific request in regards to their existing code. I do think your contribution could be very valuable, but I expect that a Lambda is a challenging concept, and you could expand on your Lambda section, and better explain what a Lambda is, and how specifically this makes your code work. +1 from me though ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T01:51:09.063",
"Id": "474878",
"Score": "0",
"body": "@gview I agree, and have expanded upon my lambda section."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:19:09.740",
"Id": "241979",
"ParentId": "241883",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241919",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:20:17.837",
"Id": "241883",
"Score": "4",
"Tags": [
"python",
"calculator"
],
"Title": "Is this calculator written in Python clean/good?"
}
|
241883
|
<p>I have implemented the <a href="https://en.wikipedia.org/wiki/Modular_arithmetic#Integers_modulo_n" rel="nofollow noreferrer">integer residue ring</a> <span class="math-container">\$ \mathbb{Z}/m\mathbb{Z} \$</span> and the <a href="https://en.wikipedia.org/wiki/Multiplicative_group_of_integers_modulo_n" rel="nofollow noreferrer">integer multiplicative residue group</a> <span class="math-container">\$ (\mathbb{Z}/m\mathbb{Z})^* \$</span>. Functionalities include:</p>
<ol>
<li>In <span class="math-container">\$ \mathbb{Z}/m\mathbb{Z} \$</span> , you can do addition, subtraction, multiplication and raising elements to a nonnegative integral power.</li>
<li>In <span class="math-container">\$ (\mathbb{Z}/m\mathbb{Z})^* \$</span>, you can do multiplication, division, raising elements to any integral power and finding the multiplicative orders of elements.</li>
</ol>
<p>I don't want users to mess around with classes. So the public interface has only two functions, <code>residue_ring_modulo(m)</code> and <code>residue_group_modulo(m)</code>, which create and return <span class="math-container">\$ \mathbb{Z}/m\mathbb{Z} \$</span> and <span class="math-container">\$ (\mathbb{Z}/m\mathbb{Z})^* \$</span> respectively as subclasses of <code>Enum</code>. All other classes are pseudo-private. I choose <code>Enum</code> because all class elements were fixed upon class creation.</p>
<p>Here is the code:</p>
<pre><code>from enum import Enum
from math import gcd
class _ResidueMonoid(Enum):
"""Abstract base class to represent an integer multiplicative residue monoid.
Examples include Z/mZ (without addition) and (Z/mZ)*.
"""
@classmethod
def _validate_type_and_return_val(cls, other):
# Ensure the operands are of the same type before any binary operation
if not isinstance(other, cls):
raise TypeError("Operands' types not matched")
return other.value
def __mul__(self, other):
other_val = self._validate_type_and_return_val(other)
result_val = (self.value * other_val) % self.modulus
return self.__class__(result_val)
def __str__(self):
return f'({self.value} % {self.modulus})'
class _ResidueRing(_ResidueMonoid):
"""Abstract base class to represent an integer residue ring"""
def __neg__(self):
result_val = (-self.value) % self.modulus
return self.__class__(result_val)
def __add__(self, other):
other_val = self._validate_type_and_return_val(other)
result_val = (self.value + other_val) % self.modulus
return self.__class__(result_val)
def __sub__(self, other):
other_val = self._validate_type_and_return_val(other)
result_val = (self.value - other_val) % self.modulus
return self.__class__(result_val)
def __pow__(self, other):
# A ring element can only be raised to a nonnegative integral power
if not isinstance(other, int):
raise TypeError("exponent must be integer")
if other < 0:
raise ValueError("exponent must be nonnegative")
result_val = pow(self.value, other, self.modulus)
return self.__class__(result_val)
class _ResidueGroup(_ResidueMonoid):
"""Abstract base class to represent an integer multiplicative residue group"""
@staticmethod
def _solve_linear_congruence(a, b, m):
# solve (ax = b mod m) by recursive Euclidean algorithm
if a == 1:
return b
x = _ResidueGroup._solve_linear_congruence(m % a, (-b) % a, a)
return (m * x + b) // a
def __truediv__(self, other):
other_val = self._validate_type_and_return_val(other)
result_val = _ResidueGroup._solve_linear_congruence(other_val, self.value, self.modulus)
return self.__class__(result_val)
def __pow__(self, other):
if not isinstance(other, int):
raise TypeError("exponent must be integer")
# if the exponent is negative, first find the modular inverse
if other < 0:
self = self.__class__(1) / self
other = -other
result_val = pow(self.value, other, self.modulus)
return self.__class__(result_val)
@property
def ord(self):
exponent = 1
val = self.value
while val != 1:
exponent += 1
val = (val * self.value) % self.modulus
return exponent
def residue_ring_modulo(m):
"""Create the integer residue ring Z/mZ as a concrete class"""
ring_name = f'Z/{m}Z'
members = [str(i) for i in range(m)]
ring = Enum(ring_name, members, type=_ResidueRing, start=0)
ring.modulus = m
return ring
def residue_group_modulo(m):
"""Create the integer multiplicative residue group (Z/mZ)* as a concrete class"""
group_name = f'(Z/{m}Z)*'
members = {str(i) : i for i in range(m) if gcd(i, m) == 1}
group = Enum(group_name, members, type=_ResidueGroup)
group.modulus = m
return group
</code></pre>
<p>Test output:</p>
<pre><code>>>> Zmod9 = residue_ring_modulo(9)
>>> Zmod9(7) + Zmod9(8)
<Z/9Z.6: 6>
>>> Zmod9(3) * Zmod9(6)
<Z/9Z.0: 0>
>>> Zmod9(4) ** 2
<Z/9Z.7: 7>
>>>
>>> Zmod9_star = residue_group_modulo(9)
>>> for x in Zmod9_star:
... print(x)
(1 % 9)
(2 % 9)
(4 % 9)
(5 % 9)
(7 % 9)
(8 % 9)
>>>
>>> Zmod9_star(2) / Zmod9_star(8)
<(Z/9Z)*.7: 7>
>>> Zmod9_star(4) ** (-3)
<(Z/9Z)*.1: 1>
>>> Zmod9_star(5).ord
6
>>>
</code></pre>
<p>I would like to get advice and feedback to improve my code. Thank you.</p>
|
[] |
[
{
"body": "<p>An interesting use of <code>Enum</code>s!</p>\n\n<p>My only concern with using <code>Enum</code> would be performance -- as you note, all possible values are created when the class itself is created, so if you use a big number then you could also be using a <em>lot</em> of memory.</p>\n\n<p>Otherwise, your <code>__dunder__</code> (aka magic) methods look good, you don't need the reflected methods (e.g. <code>__radd__</code>) since only the exact same types are used in the operations, and I can see nothing wrong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:17:04.477",
"Id": "241904",
"ParentId": "241884",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241904",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:32:07.630",
"Id": "241884",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"enum"
],
"Title": "Use Python Enum to implement residue ring and multiplicative residue group"
}
|
241884
|
<p>My goal is to make a form builder class, that generates bootstrap 4 form inside a modal.
My doubt is whether I should leave it as is or if I should crate a interface and then implement that interface for all types.<br>
Also is there a better way to write html inside php?</p>
<h2>Class to generate the form</h2>
<pre class="lang-php prettyprint-override"><code>class BS4Form
{
protected $action = "";
protected $id = "";
protected $title = "";
protected $fields = array();
public function __construct($action, $id, $title)
{
$this->action = $action;
$this->id = $id;
$this->title = $title;
//$this->fields = $fields;
}
/**
* @param mixed $fields
*/
public function setFields($field): void
{
array_push($this->fields, $field);
}
public function renderForm() : void
{
?>
<div class="modal fade" id="<?= $this->id ?>" tabindex="-1" role="dialog" aria-labelledby="<?= $this->id ?>Title" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="<?= $this->id ?>Title"><?= $this->title ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form action="<?= $this->action ?>.php" method="POST" id="form_<?= $this->id ?>">
<?php foreach ($this->fields as $field ): ?>
<?php $field->renderField(); ?>
<?php endforeach; ?>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-success" form="form_<?= $this->id ?>">Guardar</button>
</div>
</div>
</div>
</div>
<?php
}
}
</code></pre>
<h2>Sub-class to generate the fields</h2>
<pre class="lang-php prettyprint-override"><code>class BS4Field
{
protected $title = "";
protected $type = "";
protected $id = "";
protected $name = "";
protected $value = "";
public function __construct($title, $type, $id, $name, $value)
{
$this->title = $title;
$this->type = $type;
$this->id = $id;
$this->name = $name;
$this->value = $value;
}
protected function renderFormGroup() : void
{
?>
<div class="form-group">
<label for="<?= $this->id ?>"><?= $this->title ?></label>
<input class="form-control" type="<?= $this->type ?>" id="<?= $this->id ?>" name="<?= $this->name ?>" placeholder="<?= $this->value ?>">
</div>
<?php
}
protected function renderFormCheck() : void
{
?>
<div class="form-check">
<input class="form-check-input" type="<?= $this->type ?>" value="<?= $this->value ?>" name="<?= $this->name ?>" id="<?= $this->id ?>">
<label class="form-check-label" for="<?= $this->id ?>"><?= $this->title ?></label>
</div>
<?php
}
public function renderField() : void
{
($this->type === "checkbox") ? $this->renderFormCheck() : $this->renderFormGroup();
}
}
</code></pre>
<h2>Example of usage</h2>
<pre class="lang-php prettyprint-override"><code>$form = new BS4Form("", "modalEditar", "Editar Utilizador");
$form->setFields(new BS4Field("Ativo", "number", "ativo", "ativo", "ex: 12"));
$form->setFields(new BS4Field("Email", "email", "emailUser", "emailUser", "example@example.com"));
$form->setFields(new BS4Field("Token", "text", "authToken", "authToken", "Token"));
$form->setFields(new BS4Field("Renovado", "number", "renovado", "renovado", "0"));
$form->setFields(new BS4Field("Admin", "checkbox", "isAdmin", "isAdmin", "0"));
$form->renderForm();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T04:17:29.147",
"Id": "474733",
"Score": "0",
"body": "BS4Field is not a subclass. A subclass inherits from a parent class. Should BS4Field implement an interface? Yes, I think it should. This is because the interface is a contract that guarantees that BS4Field will implement the required `renderField()` method that BS4Form relies on. I think you can see the direction that BS4Field is going to go, when you look at what you hardwired for renderField() for checkbox. This tells me that you should have an abstract base class for BS4Field and individual subclasses for each different form element you want to support"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T04:19:38.483",
"Id": "474734",
"Score": "0",
"body": "You can use the BS4Field interface to typehint the parameter you are passing. This will allow you to write form element specific code as you like without having to change existing working form element classes, or having to change the form class. One last thing that I would change `public function setFields($field): void`. This name does not match the actual behavior. I would call it addField(), as it adds a single field to the array of form fields at a time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T06:19:47.797",
"Id": "474741",
"Score": "0",
"body": "What version of PHP are we talking about here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:09:55.010",
"Id": "474749",
"Score": "0",
"body": "@slepic it's php 7"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T14:16:33.837",
"Id": "491128",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h1>PHP 7 features</h1>\n\n<p>I don't know exactly your PHP version. 7 is unfortunately not enough specific. A lot of useful thing were added in minor releases. But anyway you should use all those typehints and other stuff where it makes sense. In my code snippets I'll just write using 7.4.</p>\n\n<h1>Rendering inline HTML</h1>\n\n<p>If it is at least PHP 7.3, you can use indented heredoc for the inline HTML.</p>\n\n<pre><code> public function render(): string\n {\n return <<<HTML\n <div>the indent before this div is not in the output since PHP 7.3</div>\n <div>but only as long as the terminator has the same indent level</div>\n <div>these two divs will be indented on output</div>\n <div>You can also even show some $var or {$this->var} like in double quoted string literal.</div>\n <div>but remember you still have to escape it</div>\n <div>The HTML delimiter can be anything, but it must be same on start and end<div>\n <div>so after all a templating system might be better</div>\n <<<HTML\n }\n</code></pre>\n\n<p>Feel free to abstract yourself from this problem for now with this php package I wrote for that exact reason.\n<a href=\"https://packagist.org/packages/slepic/php-template\" rel=\"nofollow noreferrer\">https://packagist.org/packages/slepic/php-template</a></p>\n\n<p>(sry for the promo :))</p>\n\n<h1>Polymorphism</h1>\n\n<p>The input class has a different behaviour if it is a checkbox, and different for all other cases (It probably does not fit select input and some others too).\nYou should model this as polymorphism, in other words as separate classes with the same interface (or base class if you wish).</p>\n\n<p>You may even want a separate class for modal box, and a form.</p>\n\n<p>Let me show you some structure. I will assume we have imported the php-template library and use its TemplateInterface which looks like this:</p>\n\n<pre><code>interface TemplateInterface\n{\n public function render(array $data): string;\n}\n</code></pre>\n\n<p>We use it to separate the HTML rendering away from those classes. Making it generic, unaware of BS4 backing it up, and agnostic of any template engine used (the package includes a pure php \"no template engine\" template interface implementation called OutputBufferTemplate)</p>\n\n<p>Lets define common interface for things that can be rendered.</p>\n\n<pre><code>interface Component\n{\n public function render(): string;\n}\n</code></pre>\n\n<p>Lets define modal box component which should show another component in a modal box.</p>\n\n<pre><code>class ModalBoxComponent implements Component\n{\n private TemplateInterface $template;\n private IComponent $content;\n private int $width;\n private int $height;\n\n public function __construct(TemplateInterface $template, Component $content, int $width, int $height)\n {\n $this->template = $template;\n $this->content = $content;\n $this->width = $width;\n $this->height = $height;\n }\n\n public function render(): string\n {\n return $this->template->render([\n 'content' => $this->content->render(),\n 'width' => $this->width,\n 'height' => $this->height,\n ]);\n }\n}\n</code></pre>\n\n<p>Lets define form component that holds mutiple input components nad has action, method, etc...</p>\n\n<pre><code>class FormComponent implements Component\n{\n private TemplateInterface $template;\n private string $action;\n private array $inputs;\n // ...\n\n /**\n * @param Component[] $inputs\n */\n public function __construct(TemplateInterface $template, string $action, array $inputs)\n {\n $this->template = $template;\n $this->action = $action;\n $this->inputs = $inputs;\n }\n\n public function render(): string\n {\n return $this->template->render([\n 'inputs' => \\array_map(fn($input) => $input->render(), $this->inputs),\n 'action' => $this->action,\n ... \n ]);\n }\n}\n</code></pre>\n\n<p>Some component for common inputs</p>\n\n<pre><code>class InputComponent implements Component\n{\n private string $title;\n private string $type;\n private string $id;\n\n // constructor, template, other stf.., etc.\n}\n</code></pre>\n\n<p>checkbox maybe extra, or maybe it just needs different template?</p>\n\n<pre><code>class CheckboxComponent implements Component\n{\n // ... and so on\n}\n</code></pre>\n\n<p>Something to create templates for the form and inputs.</p>\n\n<pre><code>interface FormTemplateAbstractFactory\n{\n public function createNumberTemplate(): TemplateInterface;\n public function createCheckboxTemplate(): TemplateInterface;\n public function createFormTemplate(): TemplateInterface;\n}\n\nclass BS4FormTemplates implements FormTemplateAbstractFactory\n{\n public function createNumberTemplate(): TemplateInterface\n {\n return new OutputBufferTemplate($this->templatesDir . '/bs4input.php');\n }\n\n public function createCheckboxTemplate(): TemplateInterface\n {\n return new OutputBufferTemplate($this->templatesDir . '/bs4checkbox.php');\n }\n\n public function createFormTemplate(): TemplateInterface\n {\n return new OutputBufferTemplate($this->templatesDir . '/bs4form.php');\n }\n}\n</code></pre>\n\n<p>now something to simplify putting those things together</p>\n\n<pre><code>class FormBuilder\n{\n private FormTemplateAbstractFactory $templates;\n\n public function __construct(FormTemplateAbstractFactory $templates)\n {\n $this->templates = $templates;\n }\n\n public function addNumber(string $name, ?string $label = null): void\n {\n $this->inputs[$name] = new InputComponent(\n $this->templates->createNumberTemaplte(),\n 'number',\n $name,\n $label,\n // ...\n );\n }\n\n public function addCheckbox(string $name, ?string $label = null): void\n {\n // here Im showing the variant where checkbox is just input with different template, it is not a separate class (depends what you want from it)\n $this->inputs[$name] = new InputComponent(\n $this->templates->createCheckboTemaplte(),\n 'checkbox',\n $name,\n $label,\n // ...\n ); \n }\n\n // passwords, texts, textareas, selectboxes, and more...\n\n public function buildForm(): FormComponent\n {\n return new FormCompoennt(\n $this->templates->createFormTemaplte(),\n $this->inputs,\n );\n }\n}\n\n</code></pre>\n\n<p>And we are ready to create a form</p>\n\n<pre><code>$builder = new FormBuilder(new BS4FormTemplates());\n$builder->addText('name', \"Your name\");\n$builder->addNumber('age', \"Your age\");\n$builder->addPassword('password', \"Your secret\");\n$form = $builder->buildForm();\n\n</code></pre>\n\n<p>Put it in a modal box.</p>\n\n<pre><code>$modal = new ModalBoxComponent(\n new OutputBufferTemplate($myModalBoxTemplateFilePath),\n $form\n);\n</code></pre>\n\n<p>And show it</p>\n\n<pre><code>echo $modal->render();\n</code></pre>\n\n<p>Now OutputBufferTemplate will execute an external php file and gather its output and so it can be good old plain html with inserted php pieces.\nsome_template.php:</p>\n\n<pre><code><div>\n <div class=\"title\"><?= htmlspecialchars($title) ?></div>\n <div><?= $content ?></div>\n</div>\n</code></pre>\n\n<p>and render it with</p>\n\n<pre><code>$temaplte = new OutputBufferTemplate('some_template.php');\necho $template->render(['content' => '<div>abc</div>', 'title' => 'a<b']);\n</code></pre>\n\n<p>I'm sorry my will to write things properly gradully decreased as I wrote this, because it's already after midnight here :D So I went from writing complete code to only showing the basic structure, I hope it helps nevertheless :) I'll try to stop by to improve it..</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T23:26:13.093",
"Id": "242025",
"ParentId": "241885",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:45:01.633",
"Id": "241885",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "Should I separate the classes in types and increase decoupling?"
}
|
241885
|
<p>I am trying to implement smart pointers for our project.
We're using FreeRTOS which is written with a C API so it was quite a challenge to implement sending smart pointers around but somehow I managed it by combining casts, new calls (dont really like that..) move semantics and some other tricks.</p>
<p>On the surface it behaves as expected, but I want to be sure there is not any memory leak.
Furthermore, is there a way to use make_unique together with new? I have not really found a way yet.</p>
<p>Here is the code, it should work with an online C++ compiler (or use this <a href="http://cpp.sh/9ihry" rel="nofollow noreferrer">link</a>). It would be great if an expert could look over this. Maybe some things can be optimized, or maybe this code is not save at all and I just dont see it.</p>
<pre><code>// Example program
#include <iostream>
#include <string>
#include <memory>
#include <cstring>
class DummyHelper {
public:
DummyHelper(uint8_t someResource): someResource(someResource) {}
virtual ~DummyHelper() {
someResource = 0;
std::cout << "Dtor called" << std::endl;
}
int getResource() {
return someResource;
}
private:
int someResource = 0;
};
class CommandMessage {
public:
CommandMessage() = default;
virtual~ CommandMessage() {};
void setParameter(uint64_t parameter) {
memcpy(rawContent.data() + 4, &parameter, sizeof(parameter));
}
uint64_t getParameter() const {
uint64_t param;
memcpy(&param, rawContent.data() + 4, sizeof(param));
return param;
}
private:
std::array<uint8_t, 12> rawContent;
};
void setTestMessage(CommandMessage *testMsg,
uint8_t someResource) {
auto unique_pptr = new std::unique_ptr<DummyHelper>(new DummyHelper(someResource));
uint64_t test_ptr = reinterpret_cast<uint64_t>(unique_pptr);
testMsg->setParameter(test_ptr);
}
std::unique_ptr<DummyHelper> getUniquePtr(
CommandMessage *testMsg) {
uint64_t raw_ptr = testMsg->getParameter();
auto unique_pptr = reinterpret_cast<std::unique_ptr<DummyHelper>*>(raw_ptr);
auto unique_ptr = std::move(*unique_pptr);
delete unique_pptr;
return unique_ptr;
}
int main()
{
auto storagePtr = std::make_unique<DummyHelper>(42);
CommandMessage testMessage;
std::cout << "Setting message" << std::endl;
setTestMessage(&testMessage, 42);
// a message has been set and can be sent, e.g. via a message queue
// in another class, the pointer is retrieved.
auto unique_ptr = getUniquePtr(&testMessage);
DummyHelper & test = *unique_ptr;
std::cout << test.getResource() << std::endl;
unique_ptr.reset();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T16:54:32.760",
"Id": "474684",
"Score": "0",
"body": "Yes it leaks. SImply count the calls to new/delete and make sure they are the same. They are not. But I don't understand what you are trying to achieve. Why are you trying to create a smart pointer when you are using a smart pointer! You have a `std::unique_ptr` this is a smart pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T18:22:17.303",
"Id": "474689",
"Score": "0",
"body": "I think I am not able to send it via the message queue. If i create a simple unique_ptr and copy it into the message queue, the resource will be destroyed after going out of scope. I don't think it is possible to transfer ownership to the FreeRTOS message queue, given it was not programmed with C++ features in mind. I actually updated the code: I deleted the pointer in the getUniquePtr() call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T23:17:06.787",
"Id": "474721",
"Score": "0",
"body": "You're making a pointer. To a unique_ptr. With new. I don't think you grasp the concept of smart pointers yet."
}
] |
[
{
"body": "<h2>Overview:</h2>\n<p>In relation to the message queue:</p>\n<ul>\n<li>Since you are doing a manual <code>new</code> and <code>delete</code> that seems a bit of a waste.</li>\n<li>Also the only thing you are creating is a unique_ptr.</li>\n<li>The unique_ptr is never in stored correctly typed so it never does any work.</li>\n</ul>\n<p>So I would not store a pointer to a <code>std::unique_ptr</code> I would just store the original pointer. I like the idea of passing in and retrieving a <code>unique_ptr</code> to the access function.</p>\n<hr />\n<p>Why are you passing a pointer to <code>CommandMessage</code>? It can't be null (you never check so must be valid. To make this more formal pass by reference to indicate to the user that it should be a normal object.</p>\n<pre><code>void setTestMessage(CommandMessage *testMsg, uint8_t someResource)\nstd::unique_ptr<DummyHelper> getUniquePtr(CommandMessage *testMsg)\n\n// I would do this:\n\nvoid setTestMessage(CommandMessage& testMsg, uint8_t someResource)\nstd::unique_ptr<DummyHelper> getUniquePtr(CommandMessage& testMsg)\n</code></pre>\n<p>Note: Putting the '*' on the right by the variable is very "C" like. C++ considers this part of the type information so it is usually on the left with the type.</p>\n<hr />\n<p>Why is the input message different from the output message?</p>\n<pre><code>void setTestMessage(CommandMessage *testMsg, uint8_t someResource)\nstd::unique_ptr<DummyHelper> getUniquePtr(CommandMessage *testMsg)\n</code></pre>\n<p>So input is a <code>uint8_t</code> but the output is <code>std::unique_ptr<DummyHelper></code>? I would expect the interface to be symmetric.</p>\n<pre><code>template<typename T>\nvoid sendMessage(CommandMessage& messageStream, std::unique_ptr<T>&& msg);\n\ntemplate<typename T>\nstd::unique_ptr<T> recvMessage(CommandMessage& messageStream);\n</code></pre>\n<hr />\n<pre><code>template<typename T>\nstd::unique_ptr<T> recvMessage(CommandMessage& messageStream)\n{\n // To store pointers in an integer type you should be using `std::intptr_t`\n // This is an int type that is guaranteed large enough to store a pointer.\n // Don't make the assumption that `uint64_t` is large enough.\n // It might be but that is not guaranteed for the future.\n std::intptr_t raw_ptr = messageStream.getParameter();\n\n return reinterpret_cast<T*>(raw_ptr);\n}\n\n\ntemplate<typename T>\nvoid sendMessage(CommandMessage& messageStream, std::unique_ptr<T>&& msg)\n{\n messageStream.setParameter(msg.release());\n}\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:57:30.453",
"Id": "241914",
"ParentId": "241886",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T15:17:28.433",
"Id": "241886",
"Score": "0",
"Tags": [
"c++",
"pointers"
],
"Title": "Using unique_ptr in FreeRTOS"
}
|
241886
|
<p>I've been struggling with python OOP. I've gone through the basics but I'm struggling with implementing them. So I've decided to create something small everyday while in quarantine to get more comfortable with OOP.</p>
<p>My code simulates a simple coffee machine that makes 4 types of coffee. </p>
<p>This is the first one. What do you think of it? How can I improve it?</p>
<pre><code>import os
class Coffee:
""" A generic coffee machine """
def __init__(self, coffee, cups, water, milk, sugar):
self.coffee = coffee
self.cups = cups
self.water = water
self.milk = milk
self.sugar = sugar
def coffee_maker(self):
preferred_coffee = type_of_coffee()
sugar_intake = some_sugar()
if sugar_intake in ("Y", "y"):
self.sugar -= 5
if preferred_coffee == 1:
print("Espresso coming up!\n")
print("1 Espresso delivered!")
elif preferred_coffee == 2:
print("Filtered Coffee coming up!\n")
print("1 Filtered Coffee delivered!")
elif preferred_coffee == 3:
print("Latte coming up!\n")
print("1 Latte delivered!")
self.milk -= 30
elif preferred_coffee == 4:
print("Cappuccino coming up!\n")
print("1 Cappuccino delivered!")
self.milk -= 30
self.coffee -= 140
self.cups -= 1
self.water -= 120
def coffee_maker_report(self): # returns the amount of: coffee, sugar, water, milk, cups left
return {"Coffee": self.coffee, "Water": self.water, "Milk": self.milk, "Sugar": self.sugar, "Cups": self.cups}
def type_of_coffee(): # this function makes sure the user chooses a their coffee of choice by getting ONLY a valid
# input
print("Hi there, what would you like to drink")
coffee_list = ["1 - Espresso", "2 - Filter", "3 - Cappuccino", "4 - Latte"]
valid = False
while not valid:
try:
choice = int(input("Enter Choice: "))
if choice in (1, 2, 3, 4):
valid = True
else:
print("Please enter a valid option.")
except ValueError:
print("Please enter a valid option")
return choice
def some_sugar():
valid = False
while not valid:
try:
choice = input("Some sugar? ")
if choice in ("Y", "y", "N", "n"):
valid = True
else:
print("Please enter a valid option")
except ValueError:
print("Please enter a valid option")
return choice
def main():
os.system("cls")
new_coffee = Coffee(3500, 25, 3000, 750, 125) # mg, no., ml, ml, mg
print(new_coffee.coffee_maker_report())
new_coffee.coffee_maker()
print(new_coffee.coffee_maker_report())
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T20:36:24.507",
"Id": "474703",
"Score": "1",
"body": "Check the post https://codereview.stackexchange.com/questions/237467/decorator-visitor-pattern-in-python for an explanation of a visitor pattern, specially for the coffee_maker function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:31:42.413",
"Id": "474787",
"Score": "0",
"body": "Thank you! That was helpful, I learned something new."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T16:21:03.383",
"Id": "241889",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Coffee machine in Python 3"
}
|
241889
|
<p>I have created a program but I feel the <code>def common(friendships, person1, person2)</code> function can be more efficient, if anyone has any good idea how I can improve it I would appreciate it. </p>
<pre><code>from My_graph import Graph
def friends_of_friends(friendships, person):
"""Return the set of friends of the person's friends.
Don't return people that are already friends of person.
"""
assert person in friendships.nodes()
result = set()
people = friendships.nodes()
for person1 in people:
for person2 in people:
# the () around the whole condition are necessary to
# break the condition over multiple lines
if (friendships.has_edge(person1, person2) and
friendships.has_edge(person2, person) and
not friendships.has_edge(person1, person) and
person1 != person):
result.add(person1)
return result
def common(friendships, person1, person2):
"""Return the number of common friends of person1 and person2."""
assert person1 != person2
assert person1 in friendships.nodes()
assert person2 in friendships.nodes()
mutual = 0
for person in friendships.nodes():
if (friendships.has_edge(person, person1) and
friendships.has_edge(person, person2)):
mutual = mutual + 1
return mutual
def suggested_friends(friendships, person):
"""Return a list of suggested people for person to befriend.
Each suggestion is a friend of a friend of person but isn't person's friend.
The suggestions are ordered from most to fewest mutual friends with person.
"""
assert person in friendships.nodes()
scored_suggestions = []
for friend_of_friend in friends_of_friends(friendships, person):
score = common(friendships, person, friend_of_friend)
scored_suggestions.append((score, friend_of_friend))
scored_suggestions.sort(reverse=True)
suggestions = []
for (score, suggestion) in scored_suggestions:
suggestions.append(suggestion)
return suggestions
class Graph:
# Representation
# --------------
# We use the adjacency list representation, but with sets instead of lists.
# The graph is a dictionary where each key is a node and
# the corresponding value is the set of the node's neighbours.
# The graph being undirected, each edge is represented twice.
# For example, the dictionary {1: {2, 3}, 2: {1}, 3: {1}} represents a
# graph with three nodes and two edges connecting node 1 with the other two.
# Creator
# -------
def __init__(self):
"""Initialise the empty graph."""
self.graph = dict()
# Inspectors
# ----------
def has_node(self, node):
"""Return True if the graph contains the node, otherwise False."""
return node in self.graph
def has_edge(self, node1, node2):
"""Check if there's an edge between the two nodes.
Return False if the edge or either node don't exist, otherwise True.
"""
return self.has_node(node1) and node2 in self.graph[node1]
def neighbours(self, node):
"""Return the set of neighbours of node.
Assume the graph has the node.
"""
assert self.has_node(node)
# copy the set of neighbours, to prevent clients modifying it directly
result = set()
for neighbour in self.graph[node]:
result.add(neighbour)
return result
def nodes(self):
"""Return the set of all nodes in the graph."""
result = set()
for node in self.graph:
result.add(node)
return result
def edges(self):
"""Return the set of all edges in the graph.
An edge is a tuple (node1, node2).
Only one of (node1, node2) and (node2, node1) is included in the set.
"""
result = set()
for node1 in self.nodes():
for node2 in self.nodes():
if self.has_edge(node1, node2):
if (node2, node1) not in result:
result.add((node1, node2))
return result
def __eq__(self, other):
"""Implement == to check two graphs have the same nodes and edges."""
nodes = self.nodes()
if nodes != other.nodes():
return False
for node1 in nodes:
for node2 in nodes:
if self.has_edge(node1, node2) != other.has_edge(node1, node2):
return False
return True
# Breadth-first search
# --------------------
def bfs(self, start):
"""Do a breadth-first search of the graph, from the start node.
Return a list of nodes in visited order, the first being start.
Assume the start node exists.
"""
assert self.has_node(start)
# Initialise the list to be returned.
visited = []
# Keep the nodes yet to visit in another list, used as a queue.
# Initially, only the start node is to be visited.
to_visit = [start]
# While there are nodes to be visited:
while to_visit != []:
# Visit the next node at the front of the queue.
next_node = to_visit.pop(0)
visited.append(next_node)
# Look at its neighbours.
for neighbour in self.neighbours(next_node):
# Add node to the back of the queue if not already
# visited or not already in the queue to be visited.
if neighbour not in visited and neighbour not in to_visit:
to_visit.append(neighbour)
return visited
# Depth-first search
# ------------------
def dfs(self, start):
"""Do a depth-first search of the graph, from the start node.
Return a list of nodes in visited order, the first being start.
Assume the start node exists.
"""
assert self.has_node(start)
# Use the BFS algorithm, but keep nodes to visit in a stack.
visited = []
to_visit = [start]
while to_visit != []:
next_node = to_visit.pop()
visited.append(next_node)
for neighbour in self.neighbours(next_node):
if neighbour not in visited and neighbour not in to_visit:
to_visit.append(neighbour)
return visited
# Modifiers
# ---------
def add_node(self, node):
"""Add the node to the graph.
Do nothing if the graph already has the node.
Assume the node is of an immutable type.
"""
if not self.has_node(node):
self.graph[node] = set()
def add_edge(self, node1, node2):
"""Add to the graph an edge between the two nodes.
Add any node that doesn't exist.
Assume the two nodes are different and of an immutable type.
"""
assert node1 != node2
self.add_node(node1)
self.add_node(node2)
self.graph[node1].add(node2)
self.graph[node2].add(node1)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:00:05.523",
"Id": "474709",
"Score": "0",
"body": "It would help to add some sample code that uses the functions and Graph class. For example, create a sample `friendships` graph and call `common()`."
}
] |
[
{
"body": "<p>Generally, if a function can't handle an exception, let the exception pass up the call stack in case a higher level can handle it. For example, don't <code>assert</code> that node is in the graph. Assume it is and try the operation. If the node isn't in the graph, an IndexError will be thrown. (Some people say \"it's easier to ask forgiveness than get permission\".)</p>\n\n<p>Presuming that <code>friendships</code> is a Graph, and that <code>person1</code> and <code>person2</code> are nodes in the Graph, <code>common()</code> can be implemented using the <code>neighbors()</code> method and <code>set</code> operations:</p>\n\n<pre><code>def common(friendships, person1, person2):\n \"\"\"Return the number of common friends of person1 and person2.\"\"\"\n return friendships.neighbors(person1) & friendships.neighbors(person2)\n</code></pre>\n\n<p>A <code>neighbors()</code> and <code>nodes()</code> can be simplified:</p>\n\n<pre><code>def neighbors(self, node):\n \"\"\"Return a copy of the set of neighbors of node.\n Assume the graph has the node.\n \"\"\"\n return set(self.graph[node])\n\ndef nodes(self):\n \"\"\"Return a set of all nodes in the graph.\"\"\"\n return set(self.graph)\n</code></pre>\n\n<p>The doc-string suggests Graph is a non-directed graph, so <code>edges()</code> can be simplified:</p>\n\n<pre><code>def edges(self):\n \"\"\"Return the set of all edges in the graph.\n An edge is a tuple (node1, node2).\n Only one of (node1, node2) and (node2, node1) is included in the set.\n \"\"\"\n seen = set()\n result = set()\n for node1, neighbors in self.graph.items():\n result.union((node1, node2) for node2 in neighbors if node2 not in seen)\n seen.add(node1)\n\n return result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:20:05.520",
"Id": "474773",
"Score": "0",
"body": "What if you could only change the common() function and nothing else to make it efficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:59:51.037",
"Id": "474806",
"Score": "0",
"body": "@Hassan, the revised functions are independent of each other. So, the revised `common()` can be used without changing the other functions/methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T14:03:24.553",
"Id": "474808",
"Score": "1",
"body": "ok thank you mate"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:31:58.787",
"Id": "241911",
"ParentId": "241892",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T17:41:43.580",
"Id": "241892",
"Score": "3",
"Tags": [
"python",
"algorithm",
"graph"
],
"Title": "friendship program using graph type python/algorithm"
}
|
241892
|
<p><a href="https://www.spoj.com/problems/ADDREV/" rel="nofollow noreferrer">https://www.spoj.com/problems/ADDREV/</a></p>
<p>My answer to <strong>ADDREV challenge on SPOJ</strong> (link to the problem given above), written in <strong>JAVA</strong>, was accepted. However, the timing was 1.23 and memory used was 82M, which doesn't seem impressive/up-to-the-mark. </p>
<p>I'm new to competitive programming and want to know -<br>
a. In what ways can I <strong>optimize</strong> my code to take up lesser memory and be quicker?<br>
b. Are their any <strong>incorrect programming practices</strong> that I have unknowingly followed?<br>
c. Which <strong>better way</strong> is available to solve this problem in Java? </p>
<p>My code:- </p>
<pre><code>import java.util.*;
import java.lang.*;
import java.math.BigInteger;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner obj = new Scanner(System.in);
int t = obj.nextInt(); obj.nextLine(); //clears the buffer
for(int i=1;i<=t;++i)
{
Scanner obj1 = new Scanner(obj.nextLine());
StringBuffer b1 = new StringBuffer(obj1.next());
StringBuffer b2 = new StringBuffer(obj1.next());
b1.reverse(); b2.reverse();
BigInteger i1 = new BigInteger(b1+"");
BigInteger i2 = new BigInteger(b2+"");
i1 = i1.add(i2);
b1 = new StringBuffer(i1.toString());
b1.reverse();
String a = new String(b1.toString());
for(int j=0;;j++) //To remove leading zeroes (if any)
{
if(a.charAt(j)!='0')
{
System.out.println(a.substring(j));
break;
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have some suggestion for you.</p>\n\n<h1>Use the <code>java.lang.StringBuilder</code> instead of the older <code>java.lang.StringBuffer</code></h1>\n\n<p>The <code>java.lang.StringBuilder</code> is <a href=\"https://docs.oracle.com/javase/8/docs/api/?java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\">generally faster</a> than the older <code>java.lang.StringBuffer</code>.</p>\n\n<h1>Use the same instance of <code>java.util.Scanner</code></h1>\n\n<p>Move the <code>java.util.Scanner</code> of the loop, you can reuse it. you can use the <code>obj</code> instance and use only this instance.</p>\n\n<h1>Reuse the same <code>java.lang.StringBuilder</code> instead of creating a new one each time.</h1>\n\n<p>You can reuse the same builder by clearing it with the method <code>java.lang.AbstractStringBuilder#setLength</code> and passing zero to the method; this will prevent the object creation to be put on the stack and use less memory than creating lots of instances of the builder.</p>\n\n<h1>Extract similar code to methods.</h1>\n\n<p>In your code, you can extract some of the code to methods; this will make the code shorter and easier to read. I suggest that you create a method to read the input and revert it as a String.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T18:52:05.720",
"Id": "241895",
"ParentId": "241894",
"Score": "2"
}
},
{
"body": "<p>Welcome to Code Review, the first thing I noticed in your code is this:</p>\n\n<blockquote>\n<pre><code>public static void main (String[] args) throws java.lang.Exception {\n Scanner obj = new Scanner(System.in);\n //later in your code in a for cycle\n Scanner obj1 = new Scanner(obj.nextLine());\n}\n</code></pre>\n</blockquote>\n\n<p>You don't need to declare <code>main</code> method throws <code>Exception</code> and you have to avoid the resource leak created by not closing the scanner <code>obj</code> and creation of a new scanner for every iteration of the loop. You can rewrite your code in this way using <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a>:</p>\n\n<pre><code>public static void main (String[] args) {\n try (Scanner sc = new Scanner(System.in)) {\n int t = sc.nextInt();\n for(int i = 0;i < t;++i) {\n //here the core code\n }\n }\n}\n</code></pre>\n\n<p>You are using <code>StringBuffer reverse</code> to reverse a <code>BigInteger</code> converted to a <code>String</code>; to reverse an <code>int</code> or a <code>BigInteger</code> you can rely on mod and division by 10 knowing that division by 10 always returns the last digit of the number:</p>\n\n<pre><code>val = 24 //I want to reverse it to number 42\nvariables val = 24 reverse = 0;\n\nremainder = 24 % 10 , reverse = reverse * 10 + remainder equal to 0 * 10 + 4 = 4,\nval = val / 10 equal to 2\n\nremainder = 2 % 10 , reverse = reverse * 10 + remainder equal to 4 * 10 + 2 = 42,\nval = val / 10 equal to 0\n</code></pre>\n\n<p>This can be converted in code with the method <code>reverseBigInteger(BigInteger val)</code>:</p>\n\n<pre><code>private static BigInteger reverseBigInteger(BigInteger val) {\n BigInteger reverse = BigInteger.ZERO;\n while (val.compareTo(BigInteger.ZERO) == 1) {\n BigInteger remainder = val.mod(BigInteger.TEN);\n reverse = reverse.multiply(BigInteger.TEN);\n reverse = reverse.add(remainder);\n val = val.divide(BigInteger.TEN);\n }\n return reverse;\n}\n</code></pre>\n\n<p>Then you can rewrite the code of your class in the following way:</p>\n\n<pre><code>public class Main {\n\n public static void main (String[] args) {\n try (Scanner sc = new Scanner(System.in)) {\n int t = sc.nextInt();\n for(int i = 0; i < t; ++i) {\n BigInteger i1 = sc.nextBigInteger();\n BigInteger i2 = sc.nextBigInteger();\n BigInteger reverse1 = reverseBigInteger(i1);\n BigInteger reverse2 = reverseBigInteger(i2);\n BigInteger sum = reverse1.add(reverse2);\n BigInteger reverseSum = reverseBigInteger(sum);\n System.out.println(reverseSum);\n }\n }\n }\n\n private static BigInteger reverseBigInteger(BigInteger val) {\n BigInteger reverse = BigInteger.ZERO;\n while (val.compareTo(BigInteger.ZERO) == 1) {\n BigInteger remainder = val.mod(BigInteger.TEN);\n reverse = reverse.multiply(BigInteger.TEN);\n reverse = reverse.add(remainder);\n val = val.divide(BigInteger.TEN);\n }\n return reverse;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T16:11:43.327",
"Id": "474943",
"Score": "0",
"body": "This helped reduce time to 0.68 and memory to 75M. However, could you explain what is meant by 'you have to avoid the **resource leak** created by not closing the scanner obj'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T06:22:27.653",
"Id": "474980",
"Score": "1",
"body": "@NEBI4 From [try with resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) : a resource is an object that must be closed after the program is finished with it. When you create a scanner object you have to close it otherwise the memory associated with it will be not released until the termination of the program, so if you are creating more instances of scanner (it should be a lot of them) you could risk to consume all the memory (see for details JVM heap)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:41:44.850",
"Id": "241935",
"ParentId": "241894",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241935",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T18:05:05.453",
"Id": "241894",
"Score": "4",
"Tags": [
"java",
"performance",
"beginner",
"memory-optimization",
"bigint"
],
"Title": "SPOJ - ADDREV (Adding Reversed Numbers)"
}
|
241894
|
<p>I was working on a project recently that had a good amount of business logic associated with status codes. To better understand the flow of logic in the domain layer, I created an enum representation of the statuses and overloaded the equality operator in the status domain model to check against the enum. </p>
<p>Is this good practice, or does this an unnecessary abstraction? Also seeing if I should implement the GetHashCode() and Equal() methods or perhaps just make them just return</p>
<pre><code>() => throw new InvalidOperationException();
</code></pre>
<p><strong><em>Implementation</em></strong></p>
<pre><code>public class StatusDm
{
public StatusDm() { }
public StatusDm(Models.Database.Status status)
{
Id = status.Id;
Name = status.Name;
}
public int Id { get; set; }
public string Name { get; set; }
public void DatabaseTransfer(ref Models.Database.Status status)
{
status.Name = Name;
}
public static bool operator ==(StatusDm domainStatus, Models.Constants.StatusEnum status)
{
return domainStatus?.Id == (int)status;
}
public static bool operator !=(StatusDm domainStatus, Models.Constants.StatusEnum status)
{
return !(domainStatus?.Id == (int)status);
}
}
</code></pre>
<p><strong><em>Usage</em></strong></p>
<pre><code>if(individual.StatusModel == StatusEnum.Submitted || individual.StatusModel == StatusEnum.Disqualified)
{
...
}
</code></pre>
<p>Appreciate any feedback or critic. Thanks!</p>
<p>Edit: There was a question in regards to how it would normally be done in this application. Here was the evolution of the usage statement</p>
<p><strong>First Implementation</strong></p>
<pre><code>if (storedIndividual.Status == (int)IndividualStatus.InProgress &&
(individual.StatusModel.Id == (int)IndividualStatus.Submitted ||
individual.StatusModel.Id == (int)IndividualStatus.Disqualified))
{
SetFinishedIndividualFormValues(ref individual);
if (individual.StatusModel.Id == (int)IndividualStatus.Submitted)
{
SendSubmittedFileEmail(individual);
}
}
else if (individual.StatusModel.Id != (int)IndividualStatus.Disqualified)
{
SendStatusChange(individual);
}
</code></pre>
<p><strong>Revised Implementation</strong></p>
<pre><code>private void HandleStatusChanges(Models.Database.Individual storedIndividual, ref Models.Domain.IndividualDm individual)
{
if (storedIndividual.Status == (int)IndividualStatus.InProgress &&
(individual.Status == IndividualStatus.Submitted ||
individual.Status == IndividualStatus.Disqualified))
{
SetFinishedIndividualFormValues(ref individual);
if (individual.Status == IndividualStatus.Submitted)
{
SendSubmittedFileEmail(individual);
}
}
else if (individual.Status != IndividualStatus.Disqualified)
{
SendStatusChange(individual);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T20:17:49.760",
"Id": "474699",
"Score": "0",
"body": "Interesting. I'm not sure it's a good idea to even consider overloading `==`, but it's definitely interesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T20:19:11.617",
"Id": "474700",
"Score": "1",
"body": "Unfortunately your question seems to attract downvotes. This is probably due to the usage being a very small example, one that isn't doing much. However, in this case, I wouldn't know what else it should be showing to indicate how it's used. Do you perhaps have a project in which you've used this implementation? That usually works better on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T20:36:16.857",
"Id": "474702",
"Score": "1",
"body": "@Mast I've update the question to showcase the changes in implementation. Hopefully it makes it clearer what I am trying to ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T05:55:21.673",
"Id": "474738",
"Score": "1",
"body": "Absolutely, welcome to Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T18:17:28.003",
"Id": "475000",
"Score": "0",
"body": "Could you post both models `Models.Database.Individual` and `Models.Domain.IndividualDm` ?"
}
] |
[
{
"body": "<p>It is difficult to judge without full code, but while keeping things mutable (please use a more descriptive names, a future you will thank you):</p>\n\n<pre><code>public class StatusModel\n{\n public IndividualStatus Status { get; set; }\n public int StatusId { get => (int)Status; set => Status = (IndividualStatus)value; } \n public bool InProgressStatus => Status == IndividualStatus.InProgress;\n public bool SubmittedStatus => Status == IndividualStatus.Submitted;\n public bool DisqualifiedStatus => Status == IndividualStatus.Disqualified;\n public bool DisqualifiedOrSubmittedStatus => DisqualifiedStatus || SubmittedStatus;\n public bool JustFinished(StatusModel stored) =>\n stored.InProgressStatus && DisqualifiedOrSubmittedStatus;\n public bool JustSubmitted(StatusModel stored) =>\n JustFinished(stored) && SubmittedStatus;\n public bool StillInProgress(StatusModel stored) =>\n !JustFinished(stored) && !DisqualifiedStatus;\n}\n</code></pre>\n\n<p>As a next step you could also define an implicit conversion operators from/to int/enum types and make this class immutable.</p>\n\n<pre><code>public class StatusModel\n{\n public static implicit operator StatusModel(IndividualStatus status) => new StatusModel(status);\n public static implicit operator IndividualStatus(StatusModel model) => model.Status;\n public static implicit operator StatusModel(int id) => (IndividualStatus)id;\n public static implicit operator int(StatusModel model) => (int)model.Status;\n StatusModel(IndividualStatus status) => Status = status;\n public IndividualStatus Status { get; set; }\n public bool InProgressStatus => Status == IndividualStatus.InProgress;\n public bool SubmittedStatus => Status == IndividualStatus.Submitted;\n public bool DisqualifiedStatus => Status == IndividualStatus.Disqualified;\n public bool DisqualifiedOrSubmittedStatus => DisqualifiedStatus || SubmittedStatus;\n public bool JustFinished(StatusModel stored) =>\n stored.InProgressStatus && DisqualifiedOrSubmittedStatus;\n public bool JustSubmitted(StatusModel stored) =>\n JustFinished(stored) && SubmittedStatus;\n public bool StillInProgress(StatusModel stored) =>\n !JustFinished(stored) && !DisqualifiedStatus;\n}\n</code></pre>\n\n<p>It is a bunch of code (C# is a ridiculously verbose language), but it would be very easy to have more logic here, adding anything status related would be a very cheap operation.</p>\n\n<pre><code>private void HandleStatusChanges(\n Models.Database.Individual storedIndividual, \n ref Models.Domain.IndividualDm individual)\n{\n if (individual.Status.JustFinished(storedIndividual.Status))\n SetFinishedIndividualFormValues(ref individual);\n if (individual.Status.JustSubmitted(storedIndividual.Status))\n SendSubmittedFileEmail(individual);\n if (individual.Status.StillInProgress(storedIndividual.Status))\n SendStatusChange(individual);\n}\n</code></pre>\n\n<p>I would also define and associate custom <code>JsonConverter</code> and <code>TypeConverter</code> with <code>StatusModel</code>, so it will look like a status integer ID for asp.net (see an example <a href=\"https://codereview.stackexchange.com/questions/117657/static-typed-ids-integers-in-c/117771#117771\">here</a>).</p>\n\n<p>P.S. Generally speaking, data entity types should never be visible in the business core:\n<a href=\"https://blog.cleancoder.com/uncle-bob/2016/01/04/ALittleArchitecture.html\" rel=\"nofollow noreferrer\">https://blog.cleancoder.com/uncle-bob/2016/01/04/ALittleArchitecture.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:06:13.050",
"Id": "241966",
"ParentId": "241898",
"Score": "1"
}
},
{
"body": "<p>Avoid overloading the == operator (and other operators) as this is a tricky business, and best avoided - so I wouldn't go down that route.</p>\n\n<hr>\n\n<p>OK next the code.</p>\n\n<h1>Enums and Integer representations</h1>\n\n<p>If you can alter the Individual and IndividualDm classes.</p>\n\n<p>Add something that returns the integer value as the Enum...</p>\n\n<p>Simple version: Models.Database.Individual</p>\n\n<pre><code>public int Status {get; set;} // Assume this is the integer status value already implemented.\n\npublic IndividualStatus StatusType => (IndividualStatus)Status;\n</code></pre>\n\n<p>Simple version: Models.Domain.IndividualDm</p>\n\n<pre><code>public StatusModel Status {get;set;}\n\npublic IndividualStatus StatusType => (IndividualStatus)Status.Id;\n\n</code></pre>\n\n<p>If don't have the control (or any change the Status int may not exist as an Enum), then an Extension method or a simple conversion factory, would do. Happy to expand on this, if you want.</p>\n\n<hr>\n\n<h1>Design-Patterns</h1>\n\n<p>Your business logic is asking a bunch of questions, that I feel should be better represented in your domain models, and logical flow (e.g. Services)</p>\n\n<p>For me, there is a lot of missing business logic information, and so this is just a earlier opinion, and based on a lot of assumptions.</p>\n\n<p>Basic Rules / Model Questions</p>\n\n<ol>\n<li>The storedIndividual.StatusType must be InProgress to be allowed to continue? (This is an assumption, as the code doesn't actually say this).</li>\n<li>Has the Status changed?</li>\n<li>Act on the change, with different processes.</li>\n<li>Store the change / send an event of the change</li>\n</ol>\n\n<p>Services type logic that runs the code...</p>\n\n<pre><code>var storedIndividual = _individualStore.GetById(request.Id);\n\n// This is just a simple inversion of InProgress to make it a bit more flexible, see implementation in class\nif (storedIndividual.IsClosed()) {\n return; // Or throw, or some specific error code\n}\n\n// Assumption, no action is need if the status hasn't changed.\nvar hasStatusChanged = storedIndividual.HasStatusChanged(individual.StatusType );\nif (!hasStatusChanged) {\n return; // Or throw, or some specific error code\n}\n\nif (individual.StatusType == IndividualStatus.Submitted) {\n // SetFinishedIndividualFormValues\n // SendSubmittedFileEmail\n return;\n}\n\nif (individual.StatusType == IndividualStatus.Disqualified) {\n // SetFinishedIndividualFormValues\n return;\n}\n\n// SendStatusChange\n// NB. It feels natural to me to call storedIndividual.SetStatus(individual.StatusType), here - but it really depends.\n\n</code></pre>\n\n<pre><code>namespace Models.Database{\n\n public class Individual {\n ...\n // Assumption, Individual represents a record case, such as a mortgage application (?)\n // This could be expand further if there are other status that could allow it to be open.\n public bool IsClosed => this.StatusType!= IndividualStatus.InProgress; \n\n public bool HasStatusChanged(IndividualStatus newStatus) {\n return this.StatusType != newStatus;\n }\n } \n\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T16:34:03.173",
"Id": "474994",
"Score": "0",
"body": "I think the `storedIndividual.Status` stores the old status while the `individual.StatusModel.Id` stores the new status, and if that's true, then your example would return different results. since the OP logic is tighten to `InProgress` status."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T16:41:08.073",
"Id": "474995",
"Score": "0",
"body": "Well the Individual class should also implement the StatusType and use the Status.Id - though this depends on the implementation. But that was a good spot, will update in second"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T16:52:14.727",
"Id": "474996",
"Score": "0",
"body": "Changed to use StatusType, thanks for comments from @iSR5. Note, I made an assumption about the Logic being tightened to `InProgress`, this may not be the case. In which case, we can re-evaluate."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T16:18:18.413",
"Id": "242042",
"ParentId": "241898",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T19:33:59.853",
"Id": "241898",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"overloading"
],
"Title": "Overloading == for better readability"
}
|
241898
|
<p>I would like to ask you to point me some good direction with writing clean code with Spring framework and Java in general.</p>
<p>I am creating a simple app, which has two main features: searching for beers and being able to comment on those beers.</p>
<p>So on the page user is presented with search form:</p>
<pre><code><div class="container">
<br/>
<div class="row justify-content-center">
<div class="col-12 col-md-10 col-lg-8">
<form class="card card-sm" method="get" th:action="@{/search}" th:object="${beerFormObject}">
<div class="card-body row no-gutters align-items-center">
<div class="col-auto">
<i class="fas fa-search h4 text-body"></i>
</div>
<!--end of col-->
<div class="col">
<input class="form-control form-control-lg form-control-borderless" placeholder="Search beer"
th:field="*{beerName}" type="search">
</div>
<!--end of col-->
<div class="col-auto">
<button class="btn btn-lg btn-success" type="submit">Search</button>
</div>
<!--end of col-->
</div>
</form>
</div>
<!--end of col-->
</div>
</div>
</code></pre>
<p>BeerFormObject is simple dto </p>
<pre><code>public class BeerFormObject {
@NotEmpty
private String beerName;
</code></pre>
<p>and controller which is responsible for searching</p>
<pre><code>@Controller
public class SearchController {
@Autowired
BeerService beerService;
@GetMapping("/search")
public ModelAndView searchBeer(@ModelAttribute("beerFormObject") @Valid BeerFormObject beerFormObject,
@ModelAttribute("reviewFormObject") ReviewFormObject reviewFormObject,
BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("/index");
}
Beer beer = beerService.findByName(beerFormObject.getBeerName());
ModelAndView modelAndView = new ModelAndView("/beer-search-result");
modelAndView.addObject("beer", beer);
return modelAndView;
}
}
</code></pre>
<p>If everything is ok, it will show following view (beer-search-result.html):</p>
<pre><code><div class="container" th:if="${beer}">
<br/>
<div class="card mb-3">
<div class="row">
<div class="col-md-4" style="margin: auto; display: block;">
<img class="card-img img-responsive mx-auto d-block"
style=" display: block; max-width:200px; max-height:250px; width: auto; height: auto;"
th:src="${beer.getImageUrl()}"/>
</div>
<div class="col-md-8" style="margin: auto; display: block;">
<div class="card-block px-2">
<h4 th:text="${beer.getName()}">Name</h4>
<p th:text="${beer.getDescription()}">Description</p>
<p th:text="${beer.getFirstBrewed()}">First Brewed</p>
<p th:text="${beer.getAbv()}">Abv</p>
<p th:text="${beer.getIbu()}">Ibu</p>
</div>
</div>
</div>
</div>
<!-- user comment form -->
<div sec:authorize="isAuthenticated()" th:block>
<div class="row" id="post-review-box">
<div class="col-md-12">
<form method="post" th:action="@{/review}" th:object="${reviewFormObject}">
<input id="beer-id" th:field="*{beerName}" th:value="${beer.getName()}" type="hidden">
<textarea class="form-control animated" cols="50" id="new-review" name="comment"
placeholder="Enter your review here..." rows="5" th:field="*{reviewText}"></textarea>
<div class="text-right">
<button class="btn btn-success btn-lg" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
<span sec:authorize="isAnonymous()"> Please <a th:href="@{/login}">Login</a> to post review</span>
<!--Beer comments-->
<div class="container">
<h2 class="text-center">Comments</h2>
<div th:if="${beer.getReviews()}">
<div class="card" th:each="review : ${beer.getReviews()}">
<div class="card-body">
<div class="row">
<div>
<!-- Add rating system-->
<p>
<a class="float-left" href="#">
<strong th:text="${review.getCreated()}">Created Date</strong>
by
<strong th:text="${review.getAuthor().getFirstName()}">Name</strong>
</a>
</p>
<div class="clearfix"></div>
<p th:text="${review.getText()}">Comment Content</p>
</div>
</div>
</div>
</div>
</div>
<p th:unless="${beer.getReviews()}">This product does not have any comments</p>
</div>
</div>
<div th:unless="${beer}">
<p>Nothing here</p>
</div>
</code></pre>
<p>This view has three separate views, one of them is Beer description, one is comment form and last one is displaying all comments.
As you can see I have another form, which this time is post, because it is creating new entry in database. And the controller for posting review looks like that</p>
<pre><code>@Controller
public class ReviewController {
@Autowired
BeerService beerService;
@Autowired
UserService userService;
@PostMapping("/review")
public ModelAndView postReview(@ModelAttribute("reviewFormObject") @Valid ReviewFormObject reviewFormObject, BindingResult result){
Beer beer = beerService.findByName(reviewFormObject.getBeerName());
beerService.addReview(beer, reviewFormObject.getReviewText());
ModelAndView modelAndView = new ModelAndView("redirect:/search?beerName="+beer.getName());
modelAndView.addObject("beer", beer);
return modelAndView;
}
}
</code></pre>
<p>Here are the things I would like to improve:</p>
<ol>
<li><p>In <code>ReviewController</code> I am doing query to database to find beer with given name, but when I am posting new comment I am already displaying this beer, so I am wodering how could I avoid doing another query.</p></li>
<li><p>In <code>SearchController</code> as a parameter of method I am passing two different form objects which one of them is needed and second one is not. This is probably because I am using <code>ReviewFormObject</code> in the same fragment, right? What I would like to do is not have this second parameter. But I am not sure how to achieve this.</p></li>
</ol>
<p>I am adding some images to visualize better what I am talking about. Cheers.</p>
<p><a href="https://i.stack.imgur.com/aHZaT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHZaT.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/Cfii9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cfii9.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/oftPW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oftPW.jpg" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T08:26:54.897",
"Id": "475135",
"Score": "2",
"body": "In order to understand how to avoid the query to the DB, I need to see the code of Beer and BeerService."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T08:35:55.147",
"Id": "475136",
"Score": "1",
"body": "I don't understand why `reviewFormObject` is a parameter in `searchBeer` if you don't need it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T17:08:56.483",
"Id": "475201",
"Score": "0",
"body": "@shanif after removing `reviewFormObject` parameter I am `getting Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'reviewFormObject' available as request attribute`. If you want to check those classes https://github.com/pkwiecienJ8/beer-app please look into this repo. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T19:53:14.733",
"Id": "241899",
"Score": "3",
"Tags": [
"java",
"spring",
"thymeleaf"
],
"Title": "Learning Spring framework with Thymeleaf"
}
|
241899
|
<p>This is my first time using Boost and templates in general, so I'm mostly looking for a style critique on my C++. In particular, I'd like feedback on:</p>
<ul>
<li><code>state_type</code>, is there a good way to do this such that consumers of the library and the private members of the class can use this type? Other than making two separate types</li>
<li>Location and style of the constants in the code. The intent is to make it entirely compliant to how the original model was written (referenced at the top)</li>
<li>Templating the container class? It would be nice if we could abstract out <code>std::vector<U></code> to some sort of <code>typename container C, C<U></code> so the users could specify their own containers that implement <code>operator[]</code>.</li>
<li>Style critique on using enums to access specific functions within the model's state</li>
<li>Other C++11/C++17/C++20 ways to do the same things I do in the code</li>
<li><p>A nicer way to do initialization than <code>static_cast<U>(constant_value)</code>, that's more correct than <code>const U = constant_value;</code></p>
<pre><code>#include <vector> /* representing state */
#include <algorithm> /* for numeric min/max */
#include <cmath> /* log, exp, fmod */
#include <boost/numeric/odeint.hpp>
#include <ios>
using namespace boost::numeric::odeint;
typedef double icing_float;
// [1] - Reference Paper: TBME-01160-2016
// [2] - Reference Paper: computer methods and programs in biomedicine 102 (2011) 192–205
template<typename U = icing_float>
class ChaseIcing {
// Each enum maps to an index within the state vector for accessing that
// function's value.
enum Function { fn_G = 0
, fn_Q
, fn_I
, fn_P1
, fn_P2
, fn_P
, fn_u_en
};
using _state_type = std::vector<U>;
/* a bunch of constants that should be in the namespace */
const U n_I = 0.0075; // 1/min, Table II, [1]
const U d1 = -std::log(0.5)/20.0; // 1/min, Table II, [1]
const U d2 = -std::log(0.5)/100.0; // 1/min, Table II, [1]
const U P_max = 6.11; // mmol/min, Table II, [1]
auto P_min(const _state_type &x)
{
return std::min(d2 * x[fn_P2], P_max);
}
auto alpha_decay(const U variable, const U decay_parameter)
{
return variable / (1.0 + decay_parameter * variable);
}
auto Q_frac(const _state_type &x)
{
const U a_G = 1.0 / 65.0; // Table II, [1]
const U Q = x[fn_Q];
return alpha_decay(Q, a_G);
}
// PN(t) -> Parenteral nutrition input, eg IV dextrose
auto _P(const _state_type &x)
{
const U _PN_ext = dextrose_rate; // TODO -> derive this over the network
return P_min(x) + _PN_ext;
}
auto _u_en(const _state_type &x)
{
const U k1 = 14.9; // mU * l / mmol/min, Table II, [1]
const U k2 = -49.9; // mU/min, Table II, [1]
const U u_min = 16.7; // mU/min, Table II, [1]
const U u_max = 266.7; // mU/min, Table II, [1]
const U G = x[fn_G];
return std::min(std::max(u_min, k1 * G + k2), u_max);
}
auto G_dot(const _state_type &x)
{
const U p_G = 0.006; // End of section 4.1, in [2]
const U S_I = 0.5e-3; // TODO: patient specific
const U G = x[fn_G];
const U Q = x[fn_Q];
const U P = _P(x);
const U EGP = 1.16; // mmol/min Table II, [1]
const U CNS = 0.3; // mmol/min Table II, [1]
const U V_G = 13.3; // L, Table II, [1]
U dGdt = 0.0;
// G' = -p_G G(t)
// - S_I G(t) (Q(t) / (1 + a_G Q(t)))
// + (P(t) + EGP -CNS)/V_G
dGdt += -p_G * G;
dGdt += -S_I*G * Q_frac(x);
dGdt += (P + EGP - CNS)/V_G;
return dGdt;
}
auto Q_dot(const _state_type &x)
{
const U I = x[fn_I];
const U Q = x[fn_Q];
const U n_C = 0.0075; // 1/min, Table II, [1]
return n_I * (I - Q) - n_C * Q_frac(x);
}
auto I_dot(const _state_type &x)
{
const U n_K = 0.0542; // 1/min, Table II, [1]
const U n_L = 0.1578; // 1/min, Table II, [1]
const U a_I = 1.7e-3; // 1/mU, Table II, [1]
const U V_I = 4.0; // L, Table II, [1]
const U x_L = 0.67; // unitless, Table II, [1]
const U u_ex = insulin_rate; // TODO: get this over the network
const U Q = x[fn_Q];
const U I = x[fn_I];
const U u_en = _u_en(x);
auto dIdt = U(0.0);
// I' = - n_K I(t)
// - n_L (I(t)/(1+a_I I(t)))
// - n_I (I(t) - Q(t))
// + u_ex(t) / V_I
// + (1 - x_L) u_en / V_I
dIdt += -n_K * I;
dIdt += -n_L * alpha_decay(I, a_I);
dIdt += -n_I * (I - Q);
dIdt += u_ex / V_I;
dIdt += (1.0 - x_L) * u_en / V_I;
return dIdt;
}
auto P1_dot(const _state_type &x)
{
const auto D = U(0.0); // enteral feed rate TODO: get from network
return -d1 * x[fn_P1] + D;
}
auto P2_dot(const _state_type &x)
{
return -P_min(x) + d1 * x[fn_P1];
}
void copy(const ChaseIcing &other)
{
data = other.data;
insulin_rate = other.insulin_rate;
dextrose_rate = other.dextrose_rate;
}
/* data is the container which contains the most up to date representation of the model's state
*
* Should only be accessed using the enum Function data type
*/
_state_type data;
public:
using state_type = _state_type;
void operator() (const state_type &x, state_type &dxdt, const U t)
{
dxdt[fn_G] = G_dot(x);
dxdt[fn_Q] = Q_dot(x);
dxdt[fn_I] = I_dot(x);
dxdt[fn_P1] = P1_dot(x);
dxdt[fn_P2] = P2_dot(x);
}
auto glucose()
{
return data[fn_G];
}
auto q()
{
return data[fn_Q];
}
auto i()
{
return data[fn_I];
}
auto p1()
{
return data[fn_P1];
}
auto p2()
{
return data[fn_P2];
}
int run(U time_start
, U time_end
, U dt
, U insulin_rate_mUpermin
, U dextrose_rate_mmolpermin)
{
insulin_rate = insulin_rate_mUpermin;
dextrose_rate = dextrose_rate_mmolpermin;
/* model doesnt modify inplace, so we make copies of its data
* for integration */
auto x = data;
auto step = stepper;
integrate_const(step, *this, x, time_start, time_end, dt);
data = x;
stepper = step;
return 0;
}
/* run the model until time_end using default rates and time step
*/
int run(U time_end)
{
return run(0.0, time_end, 0.1, insulin_rate, dextrose_rate);
}
/* run the model with implicitly provided rates
*/
int run(U time_start, U time_end, U dt)
{
return run(time_start, time_end, dt, insulin_rate, dextrose_rate);
}
/* insulin_rate is the exogenous IV insulin rate, in mU/min (not mmol/min as listed in [1])
*
* Available for public modification, but use run() for most purposes.
*/
U insulin_rate;
/* dextrose_rate is the exogenous IV dextrose rate, in mmol/min
*
* Available for public modification, but use run() for most purposes.
*/
U dextrose_rate;
/* stepper is the Boost integration type, we use RK4 but you may use any you like
*/
runge_kutta4<state_type> stepper;
/* public constructor
*/
ChaseIcing(state_type _data) : data(_data) {};
/* copy constructor
*/
ChaseIcing(const ChaseIcing &other)
{
copy(other);
}
/* assignment operator
*/
ChaseIcing& operator=(const ChaseIcing &other)
{
copy(other);
return *this;
}
};
</code></pre></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:03:57.957",
"Id": "241901",
"Score": "2",
"Tags": [
"c++",
"template-meta-programming",
"boost"
],
"Title": "Using Boost's Runge-Kutta integration capability in a templated mathematical model"
}
|
241901
|
<p>Best way to initialize <code>rr</code> and <code>cc</code> depending on cycle number to pre-defined values in <code>r</code> and <code>c</code>.</p>
<pre><code>int func(int cycle, int index, int i) {
char *rr;
char *cc;
if (cycle % 2 == 0) {
char r[4] = { 0, -1, 0, 1 };
char c[4] = { 1, 0, -1, 0 };
rr = r;
cc = c;
}
else {
char r[4] = { -1, -1, 1, 1 };
char c[4] = { 1, -1, -1, 1 };
rr = r;
cc = c;
}
return(index + rr[i] + cc[i]);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:34:33.600",
"Id": "474705",
"Score": "0",
"body": "@πάνταῥεῖ thanks, but my use case requires C arrays, I have updated the title"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T06:42:14.833",
"Id": "474745",
"Score": "0",
"body": "The code shown does not show effect before cause. It does show runtime selection between multiple arrays initialised at declaration, *with a **very** questionable scope*: Please show the intended use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T14:05:47.553",
"Id": "474809",
"Score": "0",
"body": "Where is the rest of the code, this is not even a complete function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T14:19:06.803",
"Id": "474811",
"Score": "0",
"body": "updated based on input"
}
] |
[
{
"body": "<p><strike>This code is not correct. The <code>r[4]</code> and <code>c[4]</code> arrays you have are stored on the stack, which means that as soon as they go out of scope the data is no longer valid and you get undefined behavior because <code>rr</code> and <code>cc</code> now point to unused (and possibly overwritten) areas on the stack.</p>\n\n<p>If you wanted to do this correctly, you could ensure that the arrays are kept alive either by storing on the heap, static memory, or high enough on the stack that they will live as long as <code>rr</code> and <code>cc</code> are used.</strike></p>\n\n<p>After reading it again, I realized I made a mistake. While the temporary <code>r</code> and <code>c</code> arrays are initialized in their own scopes that are immediately exited, the arrays themselves live on the same stack with the rest of the function. Still, it's definitely a bad habit to have use variables after they've left the scope even if they're technically still on the stack, so I would make the same changes anyway.</p>\n\n<p>For example, you could do:</p>\n\n<pre><code>// Somewhere in a high enough scope (possibly the current one) or static\nchar r_1[4] = { 0, -1, 0, 1 };\nchar c_1[4] = { 1, 0, -1, 0 };\n\nchar r_2[4] = { -1, -1, 1, 1 };\nchar c_2[4] = { 1, -1, -1, 1 };\n\n// In the current scope\nchar *rr;\nchar *cc;\n\nif (cycle % 2 == 0) {\n rr = r_1;\n cc = c_1;\n}\nelse {\n rr = r_2;\n cc = c_2;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:44:12.857",
"Id": "474707",
"Score": "0",
"body": "Wow, I did not realize that. For some reason it runs as expected without errors (billions of cycles), but this is compiled to run on GPU so maybe there is a slight difference how static memory is handled?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:58:22.460",
"Id": "474708",
"Score": "0",
"body": "I was a bit wrong in my first post, see the update. Basically, as long as you don't use the rr and cc pointers after leaving this function, your original code is functionally correct. Still, I would make the changes because otherwise it looks pretty weird. Also, is this in CUDA? I'm not entirely sure if it would be handled differently there, but I suspect it would work the same as running on a CPU."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:06:26.990",
"Id": "474711",
"Score": "0",
"body": "CUDA and yes, all use is in scope, but my code is definitely uglier! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:09:12.763",
"Id": "474712",
"Score": "2",
"body": "Sounds good. Just an FYI, but your original code worked because arrays leaving scope without leaving the stack frame doesn't destroy them. However, if you did this with an object like a vector, it would call the destructor and wouldn't end up working."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:38:16.020",
"Id": "241907",
"ParentId": "241903",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241907",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:07:50.287",
"Id": "241903",
"Score": "0",
"Tags": [
"c",
"array"
],
"Title": "Initialize C array at definition depending on runtime input"
}
|
241903
|
<p>I have a StudentSchedule class that contains schedules of a student, the student may switch between rooms over time. There's no overlap with the date ranges so if a student stops at 2020-01-01 the next record would be 2020-01-02.</p>
<p>Given the StudentSchedule, I want a ProgramEnrollment which disregards room changes and coalesces contiguous StudentSchedules.</p>
<p>So given the following StudentSchedules</p>
<pre><code> new StudentSchedule("A", "1", parse("2020-01-01"), parse("2020-01-02")),
new StudentSchedule("B", "1", parse("2020-01-06"), parse("2020-01-10")),
new StudentSchedule("B", "2", parse("2020-01-11"), null),
new StudentSchedule("A", "2", parse("2020-01-03"), parse("2020-01-04"))
</code></pre>
<p>I want a result like</p>
<pre><code>A 2020-01-01 - 2020-01-04
B 2020-01-06 - null
</code></pre>
<p>I have extracted the relevant code below. What I want to do is see if I can change the computeProgramEnrollments() to use more functions or streaming API including groupBy then flatmap then collect to a new list. Assuming it is possible.</p>
<pre class="lang-java prettyprint-override"><code>import java.time.*;
import java.util.*;
import java.util.stream.*;
import static java.time.LocalDate.*;
class Main {
public static void main(String[] args) {
System.out.println(computeProgramEnrollments());
}
static Stream<StudentSchedule> schedules() {
return Stream.of(
new StudentSchedule("A", "1", parse("2020-01-01"), parse("2020-01-02")),
new StudentSchedule("B", "1", parse("2020-01-06"), parse("2020-01-10")),
new StudentSchedule("B", "2", parse("2020-01-11"), null),
new StudentSchedule("A", "2", parse("2020-01-03"), parse("2020-01-04"))
);
}
public static List<ProgramEnrollment> computeProgramEnrollments() {
List<ProgramEnrollment> ret = new ArrayList<>();
String currentProgram = null;
LocalDate currentStartDate = null;
LocalDate currentStopDate = null;
boolean newEnrollmentRequired = false;
for (final StudentSchedule schedule : schedules().sorted(Comparator.comparing(StudentSchedule::getStartDate)).collect(Collectors.toList())) {
if (Objects.equals(currentProgram, schedule.getProgram())) {
if (currentStopDate != null && currentStopDate.plusDays(1).isEqual(schedule.getStartDate())) {
// continuation
currentStopDate = schedule.getStopDate();
} else {
newEnrollmentRequired = true;
}
} else {
newEnrollmentRequired = true;
}
if (newEnrollmentRequired) {
if (currentProgram != null) {
final ProgramEnrollment e =
new ProgramEnrollment(currentProgram,
currentStartDate,
currentStopDate
);
ret.add(e);
}
currentProgram = schedule.getProgram();
currentStartDate = schedule.getStartDate();
currentStopDate = schedule.getStopDate();
newEnrollmentRequired = false;
}
}
if (currentProgram != null) {
final ProgramEnrollment e =
new ProgramEnrollment(currentProgram,
currentStartDate,
currentStopDate
);
ret.add(e);
}
return ret;
}
}
class StudentSchedule {
String program;
String room;
LocalDate start;
LocalDate stop;
public StudentSchedule(String program, String room, LocalDate start, LocalDate stop) {
this.program = program;
this.room = room;
this.start = start;
this.stop = stop;
}
public String getProgram() { return program; }
public String getRoom() { return room; }
public LocalDate getStartDate() { return start; }
public LocalDate getStopDate() { return stop; }
}
class ProgramEnrollment {
String program;
LocalDate start;
LocalDate stop;
public ProgramEnrollment(String program, LocalDate start, LocalDate stop) {
this.program = program;
this.start = start;
this.stop = stop;
}
public String getProgram() { return program; }
public LocalDate getStartDate() { return start; }
public LocalDate getStopDate() { return stop; }
public String toString() {
return program + " " + start + "-" + stop + "\n";
}
}
</code></pre>
<p><a href="https://repl.it/@trajano/StupendousBetterEngines" rel="nofollow noreferrer">https://repl.it/@trajano/StupendousBetterEngines</a></p>
|
[] |
[
{
"body": "<p>This is a nice candidate for group-by/map-reduce! </p>\n\n<p>(we need an additional stream with map to get rid of the optional that is standard in reducing)</p>\n\n<h2>Idea</h2>\n\n<p>The idea is to <strong>group</strong> each <code>StudentSchedule</code> by program, <strong>map</strong> them to a small <code>ProgramEnrollment</code>, then to <strong>reduce</strong> the values of each key by merge or <em>coalesce</em> these ProgramEnrollments and finally return a list of the reduced values. </p>\n\n<p>Note that the <code>reducing</code> requires at least one entry in the stream to prevent <code>Optional.empty()</code></p>\n\n<p>You could even improve by returning a <code>Stream<ProgramEnrollment></code>.</p>\n\n<p>Note that it is possible to inline the <code>reductor</code> and <code>mapper</code>, but for clarity I introduced some local values.</p>\n\n<h2>Code</h2>\n\n<pre><code>public static List<ProgramEnrollment> computeProgramEnrollments() {\n\n\n Collector<ProgramEnrollment, ?, Optional<ProgramEnrollment>> reductor = Collectors.reducing(ProgramEnrollment::merge);\n Collector<StudentSchedule, ?, Optional<ProgramEnrollment>> mapper = Collectors.mapping(ProgramEnrollment::from, reductor);\n\n return\n schedules()\n .sorted(Comparator.comparing(StudentSchedule::getStartDate))\n .collect(Collectors.groupingBy(StudentSchedule::getProgram, mapper))\n .values()\n .stream()\n .map(Optional::get).collect(Collectors.toList());\n}\n</code></pre>\n\n<h2>Code - using toMap</h2>\n\n<p><code>toMap</code> allows for easier reducing and helps to get rid of the <code>Optional</code>.</p>\n\n<pre><code>public static List<ProgramEnrollment> computeProgramEnrollments() {\n\n return schedules()\n .sorted(Comparator.comparing(StudentSchedule::getStartDate))\n .collect(Collectors.toMap(StudentSchedule::getProgram,\n ProgramEnrollment::from,\n ProgramEnrollment::merge))\n .values()\n .stream()\n .collect(Collectors.toList());\n}\n</code></pre>\n\n<p>With some additional methods here (they could also be extracted to a util / converted to static methods on <code>Main</code>) :</p>\n\n<pre><code>static class ProgramEnrollment {\n ...\n\n public static ProgramEnrollment from(StudentSchedule s) {\n return new ProgramEnrollment(s.getProgram(), s.getStartDate(), s.getStopDate());\n }\n\n public ProgramEnrollment merge(ProgramEnrollment e) {\n LocalDate minStart = this.start == null ? e.start : e.start == null ? this.start : e.start.isBefore(this.start) ? e.start : this.start;\n LocalDate maxStop = this.stop == null ? null : e.stop == null ? null : e.stop.isAfter(this.stop) ? e.stop : this.stop;\n\n return new ProgramEnrollment(this.program, minStart, maxStop);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:53:19.237",
"Id": "474804",
"Score": "0",
"body": "Not sure but I think your reducer does not handle the `plusDays(1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T14:47:56.843",
"Id": "474813",
"Score": "0",
"body": "It does not seem to handle the gaps\n\ne.g. StudentSchdule(A, 2020-01-01, 2020-01-02), StudentSchdule(A, 2020-01-05, 2020-01-10) should have two resulting entries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T15:53:57.077",
"Id": "474816",
"Score": "1",
"body": "Oh I see. Good point! I didn't get that straight from the requirements. In that case, the reduce step should be replaced by a merge step that merges all the periods in one go, not too hard because the are sorted. If I find time I will fix it "
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:17:34.463",
"Id": "241937",
"ParentId": "241908",
"Score": "2"
}
},
{
"body": "<p>This uses <code>collect</code> since <code>reduce</code> is meant for collecting with an immutable result and this is validated to use with <em>parallel</em> streams.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>return schedules()\n .map(s->ProgramEnrollment.from(s)) // same as @RobAu\n .sorted(Comparator.comparing(ProgramEnrollment::getStartDate)) \n .collect(\n ArrayList::new,\n (c, e)->{ \n if (c.isEmpty()) {\n c.add(e);\n } else {\n var top = c.get(c.size() - 1);\n if (!top.getProgram().equals(e.getProgram())) {\n // Program changed\n c.add(e); \n }\n else if (top.getStopDate() != null &&\n top.getStopDate().plusDays(1).isBefore(e.getStartDate())) {\n // At this point there is a gap with the program\n c.add(e); \n }\n else if (top.getStopDate() != null && \n top.getStopDate().plusDays(1).isEqual(e.getStartDate())) {\n // update the stop date with the new stop date\n top.setStopDate(e.getStopDate());\n }\n else {\n throw new IllegalStateException();\n }\n }\n },\n (c1, c2) -> {\n var topC1 = c1.get(c1.size() - 1);\n var botC2 = c2.get(0);\n\n if (!topC1.getProgram().equals(botC2.getProgram()) ||\n topC1.getStopDate() != null &&\n topC1.getStopDate().plusDays(1).isBefore(botC2.getStartDate())) {\n // Program changed or there is a gap with the program\n c1.addAll(c2);\n } else if (topC1.getStopDate() != null &&\n topC1.getStopDate().plusDays(1).isEqual(botC2.getStartDate())) {\n // update the stop date with the new stop date\n botC2.setStartDate(topC1.getStartDate());\n c1.remove(c1.size() - 1);\n c1.addAll(c2);\n } else {\n // handle cases when the data does not match the preconditions\n throw new IllegalStateException();\n }\n }\n );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T20:20:22.307",
"Id": "242094",
"ParentId": "241908",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242094",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T21:52:23.913",
"Id": "241908",
"Score": "3",
"Tags": [
"java",
"functional-programming"
],
"Title": "Creating a new list using a stream"
}
|
241908
|
<p>Today I learnt the basics of OOP. I have tried to apply them to this Rock-Paper-Scissors project. However I'm still a beginner, and so I feel my code can be improved. Are there any tips, trick or other other advice I can follow to improve the look, runtime, readability or take full advantage of OOP?</p>
<p>The program is a flexible rock paper scissors game, with a rating system, as long the number of possible choices are odd like rock,paper, scissors which is 3.</p>
<ol>
<li>Program will ask for your name and update in a text file named <code>rating.txt</code> located in the current working directory
with your name and a score of 0.</li>
<li>Program will ask for the choices
from rock,paper,scissors to
rock,gun,lightning,devil,dragon,water,air,paper,sponge,wolf,tree,human,snake,scissors,fire.</li>
<li>After the following, you can do these options: !rating to get your current rating, and !exit to exit the game.</li>
<li>you can also do any of the options you've chosen and receive an appropriate prompt on how the results went.</li>
<li>!rating changes based on your results of matches, you are playing with a computer.</li>
<li>after each round, the results are saved in a text file, and if you start the game again, the rating you had with a name previously also gets transfered.</li>
<li>Oh Forgot to mention, but wins increase your rating by 100 points, a draw increases it by 50, and nothing changes when you lose.</li>
</ol>
<p>For more information, on for example, how i decided what of the choices is superior, and inferior to a given choice, check this <a href="https://hyperskill.org/projects/78/stages/435/implement#solutions" rel="nofollow noreferrer">link</a></p>
<p>Basically this program goes as follows:</p>
<pre><code>Enter your name: Tom
Hello, Tom
Enter an Odd Number of Options: rock,gun,lightning,devil,dragon,water,air,paper,sponge,wolf,tree,human,snake,scissors,fire
Okay, let's start
!rating
Your rating: 0
rock
Well done. Computer chose snake and failed
!rating
Your rating: 100
rock
Well done. Computer chose human and failed
rock
Well done. Computer chose fire and failed
rock
Sorry, but computer chose air
!rating
Your rating: 300
paper
Sorry, but computer chose sponge
wolf
Well done. Computer chose sponge and failed
!rating
Your rating: 400
!exit
Bye!
</code></pre>
<pre class="lang-py prettyprint-override"><code>from random import choice
class Rock_Paper_Scissors:
def __init__(self):
self.name = self.getname()
self.choices = self.getchoices()
self.options = self.getoptions()
self.current_score = 0
self.running = True
self.main()
def getname(self):
name = input('Enter your name: ')
print(f'Hello, {name}')
return name
def getchoices(self):
choices = input('Enter an Odd Number of Options: ')
print("Okay, let's start")
return choices
def getoptions(self):
choices = self.choices
default_options = ('rock', 'paper', 'scissors')
return choices.split(',') if choices != "" else default_options
def SearchForPlayer(self):
scores = open('rating.txt', 'r')
for line in scores:
score = line.split()
if score[0] == self.name:
self.current_score = int(score[1])
self.UserFound = True
scores.close()
return
self.UserFound = False
def CreateNewUser(self):
scores = open('rating.txt', 'a')
print(f'\n{self.name} 0', file=scores, flush=True)
scores.close()
def check_choice(self, human):
if human == '!exit':
print('Bye!')
self.running = False
return True
elif human == '!rating':
print(f'Your rating: {self.current_score}')
return False
elif human in self.options:
return True
print('Invalid input')
return False
def check_result(self, human, computer):
human_winning = []
board = self.options*2
each_side = int((len(board)/2)//2)
start = int(board.index(human) + 1)
for i in range(start, start+each_side):
human_winning.append(board[i])
if human == computer: # Draw
print(f'There is a draw ({computer})')
_round = 'Draw'
elif computer not in human_winning: # Win
print(f'Well done. Computer chose {computer} and failed')
_round = 'Win'
else: # Lose
print(f'Sorry, but computer chose {computer}')
_round = 'Lose'
return _round
def update_score(self, match_result):
match_results = ['Win', 'Lose', 'Draw']
points = [100, 0, 50]
for i in range(len(match_results)):
if match_result == match_results[i]:
self.current_score += points[i]
break
if points[i] != 0:
scores = open('rating.txt', 'r')
list_of_scores = scores.readlines()
for index, line in enumerate(list_of_scores):
if line.split()[0] == self.name:
list_of_scores[index] = f'{self.name} {self.current_score}'
break
scores = open('rating.txt', 'w')
scores.writelines(list_of_scores)
scores.close()
def main(self):
self.SearchForPlayer()
if self.UserFound is False:
self.CreateNewUser()
while self.running:
response = False
while response is False:
computer = choice(self.options)
human = input()
response = self.check_choice(human)
if self.running and response:
_round = self.check_result(human, computer)
self.update_score(_round)
Rock_Paper_Scissors()
</code></pre>
|
[] |
[
{
"body": "<p>Well, the first thing I can see is it's good you have been exposed to the concept of OOP, but you're needing a bit more understanding, which will come with experience.\nPrimarily, OOP is really around objects and their data or the actions which they do - for instance <code>Dog(\"Spot\").bark()</code> as an action or <code>Dog(\"Spot\").name</code> as a property/value. </p>\n\n<p>I mention that because for Rock, Paper, Scissors - you're folding everything into one class, which is not what you should do. That would be like all the dogs in the world being inside one big 'dog' blob which barks - doesn't make sense, right? Don't worry - you'll improve with learning and experience.</p>\n\n<p>Now, your code has a lot of functionality in it, and this is going to be difficult to change and verify, so we're going to go down the Test Driven Development (TDD) road. This is going to be new for you, so hold on.</p>\n\n<p>We'll save your code as <code>rockpaper.py</code>, and create our testing file <code>test_rockpaper.py</code>.\nThe first thing is to disable your class from executing straight away. So <code>.getname()</code> <code>.getchoices()</code> <code>.getoptions()</code> <code>.main()</code> and the <code>Rock_Paper_Scissors()</code> call will be commented out from <code>rockpaper.py</code> - and we'll write our first test:</p>\n\n<pre><code>import pytest\nfrom .rockpaper import RockPaperScissors\n\ndef test_class_create():\n game = RockPaperScissors()\n assert game\n</code></pre>\n\n<p>Let's run the test:</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>pytest tests_rockpaper.py\n========== test session starts ==========\nplatform win32 -- Python 3.6.9[pypy-7.3.0-final], pytest-5.4.1, py-1.8.1, pluggy-0.13.1\nrootdir: C:\\Users\\user\\Documents\\dev\\tests\nplugins: dash-1.9.1\ncollected 1 item\n\ntests_rockpaper.py . [100%]\n\n========== 1 passed in 0.05s ==========\n</code></pre>\n\n<p>Great. Now, you might be thinking \"why test creating the class? it's pointless\" - and it's a good question. You're not actually testing the class itself (well, obviously you are), but what you <strong>are</strong> testing is that your testing harness/setup works properly.</p>\n\n<p>Let's test the Player's name - from the <code>.getname()</code> function we disabled before. Now, as we're doing input, we need to fake the input. Here is the test function for that -</p>\n\n<pre><code>import io\n\ndef test_get_name(monkeypatch):\n game = RockPaperScissors()\n monkeypatch.setattr('sys.stdin', io.StringIO('myname'))\n game.getname()\n assert game.name == \"myname\"\n</code></pre>\n\n<p>and we run the test again:</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>pytest tests_rockpaper.py\n========== test session starts ==========\nplatform win32 -- Python 3.6.9[pypy-7.3.0-final], pytest-5.4.1, py-1.8.1, pluggy-0.13.1\nrootdir: C:\\Users\\user\\Documents\\dev\\tests\nplugins: dash-1.9.1\ncollected 2 items\n\ntests_rockpaper.py .F [100%]\n\n========== FAILURES ==========\n_____ test_get_name _____\n\nmonkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x06a27c30>\n\n def test_get_name(monkeypatch):\n game = RockPaperScissors()\n monkeypatch.setattr('sys.stdin', io.StringIO('myname'))\n game.getname()\n> assert game.name == \"myname\"\nE AttributeError: 'RockPaperScissors' object has no attribute 'name'\n\ntests_rockpaper.py:13: AttributeError\n----- Captured stdout call -----\nEnter your name: Hello, myname\n========== short test summary info ==========\nFAILED tests_rockpaper.py::test_get_name - AttributeError: 'RockPaperScissors' object has no attribute 'name'\n========== 1 failed, 1 passed in 0.27s ==========\n</code></pre>\n\n<p>Here we can see that it recognises <code>myname</code> as the player's name - but we can see that the class doesn't have an attribute \"name\". Remember <code>Dog(\"Spot\").name</code>? Each class should have properties/attributes that you can query externally, if you need to. For instance, <code>name</code> is a public attribute/property, but perhaps \"magical_name\" is only known to the player themselves and not exposed - this is called a private property/attribute.\nMaybe that makes sense? If not, read up on public verses private attributes.</p>\n\n<p>Inside <code>RockPaperScissors</code>, we need to add the getter and setter for the public attribute name, as well as fix up <code>getname(self)</code> to make it cleaner:</p>\n\n<pre><code>class RockPaperScissors:\n def __init__(self):\n self._name = \"\"\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n print(f'Hello, {value}')\n self._name = value\n\n def getname(self):\n self.name = input('Enter your name: ')\n</code></pre>\n\n<p>What we have done is introduce a private variable, <code>_name</code>, initialise it inside the class, and set it initially to an empty string (this is important to define variables in your classes before using them). Now <code>RockPaperScissors</code> has a public <code>.name</code> property (get, and set) and the <code>getname</code> function/method refers to that public property.</p>\n\n<p>The reason why you use the public property in your class methods/functions is that you can add validation (or other modifiers) inside the setter, before the value is placed in the private variable. This is something you can read about further. The point is not to cheat by changing the private variable <code>self._name</code> anywhere else in your program - <em>except in the setter</em> - this is because many bugs in coding come from changing values of the variables at different points in the code. \nIf you only ever change variable data in <strong>one place</strong>, then bugs are very easy to track down.</p>\n\n<p>Now, if we re-run the pytest, we see: </p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>pytest tests_rockpaper.py\n========= test session starts =========\nplatform win32 -- Python 3.6.9[pypy-7.3.0-final], pytest-5.4.1, py-1.8.1, pluggy-0.13.1\nrootdir: C:\\Users\\user\\Documents\\dev\\tests\nplugins: dash-1.9.1\ncollected 2 items\n\ntests_rockpaper.py .. [100%]\n\n========== 2 passed in 0.07s ==========\n</code></pre>\n\n<p>Great! 2 passing tests. Now, before we can look at <code>getchoices()</code>, we can see there is a dependency between it and <code>getoptions()</code>.\nThe <code>default_options</code> should be moved to the <code>__init__</code> - and really for <code>getoptions()</code> - what we're looking at is a validation function - not a \"<strong>get</strong>\" at all. Let's integrate both functions into one. Firstly, let's create our test and see it fail.</p>\n\n<pre><code>def test_get_choices(monkeypatch):\n game = RockPaperScissors()\n monkeypatch.setattr('sys.stdin', io.StringIO('rock,paper,scissors'))\n game.getchoices()\n assert game.choices == [\"rock\",\"paper\",\"scissors\"]\n</code></pre>\n\n<p>and the failure (chopped to save space):</p>\n\n<pre><code> monkeypatch.setattr('sys.stdin', io.StringIO('rock,paper,scissors'))\n game.getchoices()\n> assert game.choices == [\"rock\",\"paper\",\"scissors\"]\nE AttributeError: 'RockPaperScissors' object has no attribute 'choices'\n\ntests_rockpaper.py:19: AttributeError\n---------- Captured stdout call ---------\nEnter an Odd Number of Options: Okay, let's start\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_get_choices - AttributeError: 'RockPaperScissors' object has no attribute 'choices'\n===== 1 failed, 2 passed in 0.29s =====\n</code></pre>\n\n<p>This is the same as what we had for the <code>.name</code> property - again with OOP, we need properties (expose public properties, and hide the private properties). The details we can see below in the final code, but you can see that we have incorporated the validation into the getter for the game choices.</p>\n\n<p>So - that takes care of fixing the class <code>__init__</code> issues and making those properties proper for Python.\nLet's move onto the operation you have for <code>main()</code>. Talking further about OOP, objects aren't a program. \nAnother analogy - you could have a class <code>Key</code> - and create a <code>key = Key()</code>. Does that key automatically insert and turn? No. A person puts the key into a lock and turns. The program is the one to create the key, and the program should insert the key (<em>or fails inserting the key</em>) and if successful, turns the key.</p>\n\n<p>It is the program which will create your <code>RockPaperScissors</code> object, which contains data, and contains functions which act on that internal data.</p>\n\n<p>What this means for your class, is that the code in <code>main()</code> must be removed from the class and placed into the program.</p>\n\n<p>The program, for Python, starts with a statement at the bottom (I call it the entry point). It is necessary we have this, first because it tells your readers where your code starts \"here\", and second - if your code employs automated documentors, like Sphinx, it instantiates all the objects in your code before performing reflection to document your code. If you are missing the entry point, your code would be executed immediately, which would break things like Sphinx. So, we have your entry point like this so far:</p>\n\n<pre><code>if __name__ == \"__main__\":\n game = RockPaperScissors()\n game.getname()\n game.getchoices()\n</code></pre>\n\n<p>and if I re-run the tests again - the tests work perfectly - because they don't interact (like Sphinx) with the entry point - because the tests only want the class <code>RockPaperScissors()</code> - and not the program. I hope it's starting to make a little more sense now? If not, keep at it, it should become clear in time.</p>\n\n<p>So, the first few lines of your <code>main()</code> are:</p>\n\n<pre><code>def main(self):\n self.search_for_player()\n if self.user_found is False:\n self.create_new_user()\n</code></pre>\n\n<p>So we will create a test for <code>search_for_player()</code>. As you can see, I have \"pythonised\" the function and property names - we use <strong>snake_case</strong> for everything except classes. This is part of the <strong>PEP8</strong> naming standard which Python uses. I recommend spending a little time reading about PEP8 - it will help make your Python code better. Okay, so first, as is the method in TDD, we create a failing test.</p>\n\n<pre><code>def test_search_for_player():\n game = RockPaperScissors()\n game.search_for_player()\n assert game.user_found is False\n</code></pre>\n\n<p>That looks very similar to your code above, right? I'm rushing a bit, but if the code is valid, it should pass easily - but it fails -</p>\n\n<pre><code> def test_search_for_player():\n game = RockPaperScissors()\n> game.search_for_player()\n\ntests_rockpaper.py:23:\n _ _ _\n\nself = <tests.rockpaper.RockPaperScissors object at 0x0649dfd0>\n\n def search_for_player(self):\n> scores = open('rating.txt', 'r')\nE FileNotFoundError: [Errno 2] No such file or directory: 'rating.txt'\n\nrockpaper.py:42: FileNotFoundError\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_search_for_player - FileNotFoundError: [Errno 2] No such file or directory: 'rating.txt'\n===== 1 failed, 3 passed in 0.31s =====\n</code></pre>\n\n<p>It looks like we've encountered a hidden bug in your code. I'm guessing you created the <code>rating.txt</code> file when you were first creating your program? \nHowever, as I'm running it on my system, and as the file doesn't exist, the program should naturally crash (or perhaps continue on silently?). This TDD processes allows us to test parts of the code independently without \"prior states\" affecting the outcome. Let's look at the function -</p>\n\n<pre><code>def search_for_player(self):\n scores = open('rating.txt', 'r')\n for line in scores:\n score = line.split()\n if score[0] == self.name:\n self.current_score = int(score[1])\n self.user_found = True\n scores.close()\n return\n self.user_found = False\n</code></pre>\n\n<p>There are some issues with this function that jump out at me. Firstly, you don't check for the file existing (as we just found out) on the first line of code, and the last line is creating <code>self.user_found</code> - we should put that variable inside the class <code>__init__</code> (and you were creating a class variable inside the class instead of initialising it at the start). \nI can also see there will be other issues, like not validating each line of data found in the file, and the forced function exit with return, but we can leave that for an exercise for you to handle at your leisure.</p>\n\n<p>So a minor change, the user_found is placed in the <code>__init__</code>, and we come out with:</p>\n\n<pre><code>def search_for_player(self):\n try:\n scores = open('rating.txt', 'r')\n for line in scores:\n score = line.split()\n if score[0] == self.name:\n self.current_score = int(score[1])\n self.user_found = True\n scores.close()\n except FileNotFoundError:\n pass\n</code></pre>\n\n<p>The test now passes, but as the code from <code>main()</code> says:</p>\n\n<pre><code>game.search_for_player()\nif game.user_found is False:\n game.create_new_user()\n</code></pre>\n\n<p>Let's extend the test to:</p>\n\n<pre><code>def test_search_for_player():\n game = RockPaperScissors()\n game.search_for_player()\n assert game.user_found is False\n game.name = \"myname\"\n game.create_new_user()\n assert game.user_found is True\n</code></pre>\n\n<p>And re-run the test:</p>\n\n<pre><code> assert game.user_found is False\n game.create_new_user()\n> assert game.user_found is True\nE assert False is True\nE + where False = <tests.rockpaper.RockPaperScissors object at 0x06d51e10>.user_found\n\ntests_rockpaper.py:27: AssertionError\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_search_for_player - assert False is True\n</code></pre>\n\n<p>We can see the error appears that the <code>user_found</code> flag isn't being set correctly. Of course! Let's fix that:</p>\n\n<pre><code>def create_new_user(self):\n scores = open('rating.txt', 'a')\n print(f'\\n{self.name} 0', file=scores, flush=True)\n scores.close()\n self.user_found = True\n</code></pre>\n\n<p>and let's delete the file <code>rating.txt</code> just to make sure this particular test runs properly -</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>pytest tests_rockpaper.py\n========= test session starts =========\nplatform win32 -- Python 3.6.9[pypy-7.3.0-final], pytest-5.4.1, py-1.8.1, pluggy-0.13.1\nrootdir: C:\\Users\\user\\Documents\\dev\\tests\nplugins: dash-1.9.1\ncollected 4 items\n\ntests_rockpaper.py .... [100%]\n\n========== 4 passed in 0.07s ==========\n</code></pre>\n\n<p>Perfect. However, I think there might be a problem in the code, let's run the test again:</p>\n\n<pre><code>_____ test_search_for_player ______\n\n def test_search_for_player():\n game = RockPaperScissors()\n> game.search_for_player()\n\ntests_rockpaper.py:24:\n _ _ _ _\n\nself = <tests.rockpaper.RockPaperScissors object at 0x07089030>\n\n def search_for_player(self):\n try:\n scores = open('rating.txt', 'r')\n for line in scores:\n score = line.split()\n> if score[0] == self.name:\nE IndexError: list index out of range\n\nrockpaper.py:46: IndexError\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_search_for_player - IndexError: list index out of range\n===== 1 failed, 3 passed in 0.31s =====\n</code></pre>\n\n<p>Let's look at the contents of rating.txt? It is:</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>type rating.txt\n\nmyname 0\n</code></pre>\n\n<p>that looks fine? If we delete the <code>rating.txt</code> and run the tests again - they pass - but running the tests another time (a \"post-file creation\" scenario) - the tests fail.</p>\n\n<p>I think I can see the bug - the line:</p>\n\n<pre><code>print(f'\\n{self.name} 0', file=scores, flush=True)\n</code></pre>\n\n<p>with the \"<strong>\\n</strong>\" line-feed is not being taken into consideration. Removing that, and deleting the <code>rating.txt</code> - the tests all run fine first time, a second time, and a third time. Let's look at the <code>rating.txt</code> file:</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>type rating.txt\nmyname 0\nmyname 0\nmyname 0\n</code></pre>\n\n<p>Ah, that's no good. It's continually appending the data file.</p>\n\n<p>So, let's change:</p>\n\n<pre><code>scores = open('rating.txt', 'a')\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>scores = open('rating.txt', 'w')\n</code></pre>\n\n<p>and run the tests again a few times - yes, that fixes it - we're only seeing a single line of data in the file, and all the tests still pass successfully.</p>\n\n<p>Let's complete the rest of the program into the entry point, remove <code>self.main()</code> and fix <code>game.options</code> into <code>game.choices</code>, as we merged those two earlier:</p>\n\n<pre><code>if __name__ == \"__main__\":\n game = RockPaperScissors()\n game.getname()\n game.getchoices()\n game.search_for_player()\n if game.user_found is False:\n game.create_new_user()\n while game.running:\n response = False\n while response is False:\n computer = choice(game.choices)\n human = input()\n response = game.check_choice(human)\n\n if game.running and response:\n _round = game.check_result(human, computer)\n game.update_score(_round)\n</code></pre>\n\n<p>My IDE, PyCharm, highlights <code>_round = game.check_result(human, computer)</code> - it says human and computer are being referenced before being used. \nThis is true because of \"variable scope\" - <code>human</code> and <code>computer</code> are defined and used inside the while loop - but once we leave the while loop - they are \"lost\". Python is a bit more forgiving than other languages. This code would crash in most other languages.</p>\n\n<p>Let's address that later, and test the while loop with (and later, to monkeypatch the input):</p>\n\n<pre><code>def test_input_loop():\n game = RockPaperScissors()\n game.name = \"myname\"\n game.search_for_player()\n response = False\n while response is False:\n computer = choice(game.choices)\n human = input()\n response = game.check_choice(human)\n</code></pre>\n\n<p>Do the tests run successfully? No, we get a failure -</p>\n\n<pre><code>_________ test_input_loop _________\n\n def test_input_loop():\n game = RockPaperScissors()\n game.name = \"myname\"\n> game.search_for_player()\n\ntests_rockpaper.py:35:\n_ _ _ _ _ _ _ _ _ _ _ _\n\nself = <tests.rockpaper.RockPaperScissors object at 0x06dd03b0>\n\n def search_for_player(self):\n try:\n scores = open('rating.txt', 'r')\n> for line in scores:\nE ValueError: I/O operation on closed file\n\nrockpaper.py:44: ValueError\n----- Captured stdout call --------\nHello, myname\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_input_loop - ValueError: I/O operation on closed file\n===== 1 failed, 4 passed in 0.35s =====\n</code></pre>\n\n<p>This is an interesting bug we have discovered. Usually people use a concept called a Context Manager to manage the scope of a resource. It automatically manages closing of the file, we don't need to specifically close that resource. Let's update the code to that standard pattern:</p>\n\n<pre><code>def search_for_player(self):\n try:\n scores = []\n with open('rating.txt', 'r') as score_file:\n scores = score_file.readlines()\n for line in scores:\n score = line.split()\n if score[0] == self.name:\n self.current_score = int(score[1])\n self.user_found = True\n # scores.close()\n except FileNotFoundError:\n pass\n\ndef create_new_user(self):\n with open('rating.txt', 'w') as score_file:\n score_file.write(f'{self.name} 0')\n self.user_found = True\n</code></pre>\n\n<p>And run the tests:</p>\n\n<pre><code>tests_rockpaper.py ....F [100%]\n\n============== FAILURES ===============\n_________________ test_input_loop __________________\n\n def test_input_loop():\n game = RockPaperScissors()\n game.name = \"myname\"\n game.search_for_player()\n response = False\n while response is False:\n> computer = choice(game.choices)\n\ntests_rockpaper.py:38:\n_ _ _ _ _ _ _ _ _ _ _ _ _ _\n\nself = <random.Random object at 0x03a14510>, seq = []\n\n def choice(self, seq):\n \"\"\"Choose a random element from a non-empty sequence.\"\"\"\n try:\n i = self._randbelow(len(seq))\n except ValueError:\n> raise IndexError('Cannot choose from an empty sequence') from None\nE IndexError: Cannot choose from an empty sequence\n\nc:\\pypy3.6\\lib-python\\3\\random.py:267: IndexError\n------------ Captured stdout call --------------------\nHello, myname\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_input_loop - IndexError: Cannot choose from an empty sequence\n===== 1 failed, 4 passed in 0.39s =====\n</code></pre>\n\n<p>An empty set of choices? We're not calling <code>game.getchoices()</code>, so the default set isn't being set correctly. As we're defining the default set of choices, let's force that during <code>RockPaperScissors()</code> instantiation.</p>\n\n<pre><code> self.default_options = [\"rock\", \"paper\", \"scissors\"]\n self.choices = \"\"\n</code></pre>\n\n<p>Having an empty string will ensure the default choices are set because of the validation in the game.choices setter.</p>\n\n<p>Running the tests again, we see that I forgot to add the default input - so let's do that - we'll make it the choice of \"<strong>rock</strong>\" -</p>\n\n<pre><code>def test_input_loop(monkeypatch):\n game = RockPaperScissors()\n game.name = \"myname\"\n game.search_for_player()\n response = False\n while response is False:\n computer = choice(game.choices)\n monkeypatch.setattr('sys.stdin', io.StringIO('rock'))\n human = input()\n response = game.check_choice(human)\n\n\n========= test session starts =========\nplatform win32 -- Python 3.6.9[pypy-7.3.0-final], pytest-5.4.1, py-1.8.1, pluggy-0.13.1\nrootdir: C:\\Users\\user\\Documents\\dev\\tests\nplugins: dash-1.9.1\ncollected 5 items\n\ntests_rockpaper.py ....F [100%]\n\n============== FAILURES ===============\n______________ test_input_loop ______________\n\nmonkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x06d19d70>\n\n def test_input_loop(monkeypatch):\n game = RockPaperScissors()\n game.name = \"myname\"\n game.search_for_player()\n response = False\n while response is False:\n computer = choice(game.choices)\n monkeypatch.setattr('sys.stdin', io.StringIO('rock'))\n human = input()\n> response = game.check_choice(human)\n\ntests_rockpaper.py:41:\n_ _ _ _ _ _ _ _ _ _ _\n\nself = <tests.rockpaper.RockPaperScissors object at 0x06d19d90>, human = 'rock'\n\n def check_choice(self, human):\n if human == '!exit':\n print('Bye!')\n self.running = False\n return True\n elif human == '!rating':\n print(f'Your rating: {self.current_score}')\n return False\n> elif human in self.options:\nE AttributeError: 'RockPaperScissors' object has no attribute 'options'\n\nrockpaper.py:68: AttributeError\n------------------------------- Captured stdout call -----------------------\nOkay, let's start\nHello, myname\n======= short test summary info =======\nFAILED tests_rockpaper.py::test_input_loop - AttributeError: 'RockPaperScissors' object has no attribute 'options'\n===== 1 failed, 4 passed in 0.42s =====\n</code></pre>\n\n<p>Of course, we changed that code to only look at <code>game.choices</code> - let's do a find all refactoring for <code>game.options</code> and make it <code>game.choices</code>, and re-run the tests. Result? <code>5 passed in 0.07s Great</code>.</p>\n\n<p>Being cheeky, let's fix the same test with proper-scoped values (<code>human</code> and <code>computer</code>), and see if it works:</p>\n\n<pre><code>def test_input_loop(monkeypatch):\n game = RockPaperScissors()\n game.name = \"myname\"\n game.search_for_player()\n response = False\n human = \"\"\n computer = \"\"\n while response is False:\n computer = choice(game.choices)\n monkeypatch.setattr('sys.stdin', io.StringIO('rock'))\n human = input()\n response = game.check_choice(human)\n\n if game.running and response:\n _round = game.check_result(human, computer)\n game.update_score(_round)\n</code></pre>\n\n<p>And run the tests:</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>pytest tests_rockpaper.py\n========= test session starts =========\nplatform win32 -- Python 3.6.9[pypy-7.3.0-final], pytest-5.4.1, py-1.8.1, pluggy-0.13.1\nrootdir: C:\\Users\\user\\Documents\\dev\\tests\nplugins: dash-1.9.1\ncollected 5 items\n\ntests_rockpaper.py ..... [100%]\n\n========== 5 passed in 0.09s ==========\n\nC:\\Users\\user\\Documents\\dev\\tests>type rating.txt\nmyname 50\n</code></pre>\n\n<p>Let's try running the program!</p>\n\n<pre><code>C:\\Users\\user\\Documents\\dev\\tests>pypy3 rockpaper.py\nOkay, let's start\nEnter your name: user\nHello, user\nEnter an Odd Number of Options: rock,gun,lightning,devil,dragon,water,air,paper\nOkay, let's start\nrock\nSorry, but computer chose gun\ndevil\nThere is a draw (devil)\ndragon\nWell done. Computer chose lightning and failed\n!rating\nYour rating: 150\n!exit\nBye!\n\nC:\\Users\\user\\Documents\\dev\\tests>type rating.txt\nuser 150\n</code></pre>\n\n<p>Great! Looks good. Here is the final testing file, and your program file.</p>\n\n<p>There are still some minor fixes to make, such as - lines 105-107 could be rewritten to use a Context Manager - line 97 uses i which hasn't been initialised outside of the loop, the variable _round could be returned 3 times rather than set and returned at the end of the function (lines 79, 82, 85). Please try those fixes.</p>\n\n<p>Otherwise, good effort. Keep it up!</p>\n\n<p>Listing rockpaper.py:</p>\n\n<pre><code>from random import choice\n\n\nclass RockPaperScissors:\n def __init__(self):\n self.user_found = False\n self._name = \"\"\n self._choices = []\n self.default_options = [\"rock\", \"paper\", \"scissors\"]\n self.choices = \"\"\n self.current_score = 0\n self.running = True\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n print(f'Hello, {value}')\n self._name = value\n\n def getname(self):\n self.name = input('Enter your name: ')\n\n @property\n def choices(self):\n return self._choices\n\n @choices.setter\n def choices(self, value):\n print(\"Okay, let's start\")\n self._choices = value.split(',') if value != \"\" else self.default_options\n\n def getchoices(self):\n self.choices = input('Enter an Odd Number of Options: ')\n\n def search_for_player(self):\n try:\n scores = []\n with open('rating.txt', 'r') as score_file:\n scores = score_file.readlines()\n for line in scores:\n score = line.split()\n if score[0] == self.name:\n self.current_score = int(score[1])\n self.user_found = True\n except FileNotFoundError:\n pass\n\n def create_new_user(self):\n with open('rating.txt', 'w') as score_file:\n score_file.write(f'{self.name} 0')\n self.user_found = True\n\n def check_choice(self, human):\n if human == '!exit':\n print('Bye!')\n self.running = False\n return True\n elif human == '!rating':\n print(f'Your rating: {self.current_score}')\n return False\n elif human in self.choices:\n return True\n print('Invalid input')\n return False\n\n def check_result(self, human, computer):\n human_winning = []\n board = self.choices * 2\n each_side = int((len(board) / 2) // 2)\n start = int(board.index(human) + 1)\n for i in range(start, start + each_side):\n human_winning.append(board[i])\n\n if human == computer: # Draw\n print(f'There is a draw ({computer})')\n _round = 'Draw'\n elif computer not in human_winning: # Win\n print(f'Well done. Computer chose {computer} and failed')\n _round = 'Win'\n else: # Lose\n print(f'Sorry, but computer chose {computer}')\n _round = 'Lose'\n\n return _round\n\n def update_score(self, match_result):\n match_results = ['Win', 'Lose', 'Draw']\n points = [100, 0, 50]\n for i in range(len(match_results)):\n if match_result == match_results[i]:\n self.current_score += points[i]\n break\n\n if points[i] != 0:\n scores = open('rating.txt', 'r')\n list_of_scores = scores.readlines()\n for index, line in enumerate(list_of_scores):\n if line.split()[0] == self.name:\n list_of_scores[index] = f'{self.name} {self.current_score}'\n break\n\n scores = open('rating.txt', 'w')\n scores.writelines(list_of_scores)\n scores.close()\n\n\nif __name__ == \"__main__\":\n game = RockPaperScissors()\n game.getname()\n game.getchoices()\n game.search_for_player()\n if game.user_found is False:\n game.create_new_user()\n while game.running:\n response = False\n human = \"\"\n computer = \"\"\n while response is False:\n computer = choice(game.choices)\n human = input()\n assert human\n response = game.check_choice(human)\n if game.running and response:\n _round = game.check_result(human, computer)\n game.update_score(_round)\n</code></pre>\n\n<p>Testing file <code>tests_rockpaper.py</code>:</p>\n\n<pre><code>import pytest\nimport io\nfrom .rockpaper import RockPaperScissors\nfrom random import choice\n\ndef test_class_create():\n game = RockPaperScissors()\n assert game\n\ndef test_get_name(monkeypatch):\n game = RockPaperScissors()\n monkeypatch.setattr('sys.stdin', io.StringIO('myname'))\n game.getname()\n assert game.name == \"myname\"\n\ndef test_get_choices(monkeypatch):\n game = RockPaperScissors()\n monkeypatch.setattr('sys.stdin', io.StringIO('rock,paper,scissors'))\n game.getchoices()\n assert game.choices == [\"rock\",\"paper\",\"scissors\"]\n\n\ndef test_search_for_player():\n game = RockPaperScissors()\n game.search_for_player()\n assert game.user_found is False\n game.name = \"myname\"\n game.create_new_user()\n assert game.user_found is True\n\n# @pytest.mark.skip\ndef test_input_loop(monkeypatch):\n game = RockPaperScissors()\n game.name = \"myname\"\n game.search_for_player()\n response = False\n human = \"\"\n computer = \"\"\n while response is False:\n computer = choice(game.choices)\n monkeypatch.setattr('sys.stdin', io.StringIO('rock'))\n human = input()\n response = game.check_choice(human)\n\n if game.running and response:\n _round = game.check_result(human, computer)\n game.update_score(_round)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:33:33.607",
"Id": "474921",
"Score": "0",
"body": "You're wrong about the scope of local variables. Their scope is the whole function, not the indentation level. PyCharm 2020.1 says _Local variable 'inner' might be referenced before assignment_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T14:44:14.543",
"Id": "474937",
"Score": "0",
"body": "Wow this is much more info that i expected, thanks so much for your time, I'll keep it in mind definitely. Again thank you so much for the length response."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T10:00:09.727",
"Id": "241989",
"ParentId": "241909",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241989",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:02:03.750",
"Id": "241909",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"random",
"file-system"
],
"Title": "Simulating a Rock, Paper, Scissors Game - Flexible"
}
|
241909
|
<p>I tried to make a password generator and at first it works as intended, generating a password with lowercase, uppercase and special characters but I can only generate passwords of up to 19 characters any more and the script sends an error about a string being too big or something.</p>
<pre><code>import random
generator = "qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM.!?*"
generatorLength = len(generator)
def Generator():
acc = 0
password = ''
length = int(input("How long?\n"))
if length < 6:
print("Can't be less than 6\n")
Generator()
while acc < length:
password += generator[random.randint(0, generatorLength)]
acc += 1
print("Password:", password)
Generator()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T00:18:12.773",
"Id": "474722",
"Score": "2",
"body": "Hello, this question is off-topic, since the code is not working as intended; I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T06:49:18.080",
"Id": "474746",
"Score": "1",
"body": "`and the script sends an error about a string being too big or something` a) *which* `script sends an error`? b) `or something` when asking an appropriate audience, be sure to quote any error messages verbatim."
}
] |
[
{
"body": "<p>Because string indexes start on 0 rather than 1, your upper limit for the random interger should be the length of generator minus one. That is, the last character on your generator string is given by generator[generatorLength - 1].</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:54:11.327",
"Id": "474718",
"Score": "0",
"body": "`random.randrange`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T00:38:13.647",
"Id": "474723",
"Score": "2",
"body": "Please refrain from answering questions with code that doesn't work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:49:49.430",
"Id": "241913",
"ParentId": "241912",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "241913",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T22:42:08.867",
"Id": "241912",
"Score": "-3",
"Tags": [
"python"
],
"Title": "Extremely simple python password generator"
}
|
241912
|
<p>Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format. Please review my code. Is there a cleaner way of writing the code where we have to add the 2 doubles digit by digit? </p>
<p>for example, s1 is '9.9' and s2 is '8.8', we need to return '18.7'.
The requirement is that we cannot pad zeros for cases like adding '9.9' and '7.899'. In another word, we cannot change the input into '9.900' (i.e: with padded 0's) and '7.899'. </p>
<p>we have to add the two input digit by digit. For example, if s1 = '9.9' and s2 = '7.899', then we need to do 8+9 (the digit after the decimal point in s1 and s2), 9+7 (the two digits before the decimal points in s1 and s2). In another words, please do not use internal libraries to convert the two numbers into float and add them together. </p>
<pre><code>def addDoubles(s1, s2):
s1Split = s1.find('.')
s2Split = s2.find('.')
s1Post = ''
s2Post = ''
if s1Split != -1:
s1Post = s1[s1Split+1:]
if s2Split != -1:
s2Post = s2[s2Split+1:]
s1PostLen = len(s1Post)
s2PostLen = len(s2Post)
s1PostLonger = s2PostLonger = False
postLenDiff = 0
if s1PostLen > s2PostLen:
#s2Post = s2Post + '0'*(s1PostLen-s2PostLen)
s1PostLonger = True
postLenDiff = s1PostLen - s2PostLen
elif s1PostLen < s2PostLen:
#s1Post = s1Post + '0'*(s2PostLen-s1PostLen)
s2PostLonger = True
postLenDiff = s2PostLen - s1PostLen
if s1Split != -1:
s1New = s1[:s1Split] + s1Post
else:
s1New = s1
if s2Split != -1:
s2New = s2[:s2Split] + s2Post
else:
s2New = s2
postSum = helper(s1New, s2New, postLenDiff, s1PostLonger, s2PostLonger)
print('s2PostLonger =', s2PostLonger)
if s1PostLonger or (s1PostLonger == s2PostLonger == False and s1Post != ''):
postSum = postSum[:-s1PostLen] + '.' + postSum[-s1PostLen:]
elif s2PostLonger:
postSum = postSum[:-s2PostLen] + '.' + postSum[-s2PostLen:]
return postSum
def helper(one, two, postLenDiff, s1PostLonger, s2PostLonger):
oneIdx = len(one)-1
twoIdx = len(two)-1
curSum = 0
res = ''
if s1PostLonger:
res = one[-postLenDiff:]
oneIdx = oneIdx - postLenDiff
elif s2PostLonger:
res = two[-postLenDiff:]
twoIdx = twoIdx - postLenDiff
while oneIdx >= 0 or twoIdx >= 0 or curSum>0:
if oneIdx >= 0:
curSum += int(one[oneIdx])
oneIdx -= 1
if twoIdx >= 0:
curSum += int(two[twoIdx])
twoIdx -= 1
res = str(curSum%10) + res
curSum //= 10
return res
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T07:30:11.827",
"Id": "474747",
"Score": "1",
"body": "What do you mean by *digit by digit*? Two digits ≥ 5 cannot be added like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:08:24.020",
"Id": "474765",
"Score": "0",
"body": "Would you show us an example input and your expected output? There is a lot of code here for something that sounds simple based just on your stated requirements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:42:48.803",
"Id": "474801",
"Score": "1",
"body": "Thank you for the input. I've edited the code requirement to specify what I want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T23:26:34.993",
"Id": "474871",
"Score": "0",
"body": "You said when you add '9.9' and '7.899', you start with the '9' + '8'. \n What about the '99' at the end? Do you drop it and get '17.7'? Or do you expect to get '17.799' ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:05:31.743",
"Id": "474873",
"Score": "0",
"body": "hi, I expect to get '17.799'. the '99' is concatenated to the result."
}
] |
[
{
"body": "<p>If your need is truly</p>\n\n<blockquote>\n <p>Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format.</p>\n</blockquote>\n\n<p>then it is as easy as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def add_strings(x, y):\n return str(float(x) + float(y))\n\na = add_strings(\"2.3\", \"4.5\")\n\nprint(a)\nprint(type(a))\n</code></pre>\n\n<p>which gives</p>\n\n<pre><code>6.8\n<class 'str'>\n</code></pre>\n\n<p>Note that returning a numerical string is a strange and mostly not required operation in the Python world.\nThe function should return without the <code>str</code> call, and the conversion to string will either be implicit (like <code>print</code> can do it) or explicit by the user of that function.\nIf you hand the returned string into a new function that does, say, multiplication, and that function has to convert string to float again... you see the unnecessary chain there.</p>\n\n<p>Other than that, your code can benefit from sticking to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 Style Guide</a>.\nMost of all, in this case, having all variables in <code>snake_case</code> can save you from hearing \"PEP 8\"-comments again.\nIn <code>res = ''</code>, you could issue <code>res = \"\"</code>, since those quotes are impossible to mistake.\n<code>''</code> can look like <code>\"</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:45:27.477",
"Id": "474802",
"Score": "0",
"body": "Hi, how do I make the code cleaner if I cannot just directly convert the input into float and add them together? Thank you so much for your input. I've edited my original post to make clear what I want. Can you please take a look?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:14:16.257",
"Id": "474819",
"Score": "0",
"body": "Your edit sounds like quite the other-worldly requirement. Converting to `float` is not an \"internal library\"... I guess technically, it is, but it is so much a very core language feature that forbidding it is very strange. And I still do not understand your \"digit by digit\" requirement. How do you handle addition of two digits greater equal 5 (or rather, how would you *want* to)? If this is a task from some teacher, please reassure you understood correctly. Lastly, please provide a more elaborate input/output sample."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:09:01.853",
"Id": "474874",
"Score": "0",
"body": "Hi, when both of the 2 digits are greater than 5, there is a \"carry\" of 1 to the next digits summation. so when I add \"1.6\" + \"1.5\" I do '6'+'5' = '11' and there is a 'carry' of '1' in the summation of '1'+'1'. so I do '1' + '1' + '1' = 3. I get a result of '3.1'"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T07:28:42.640",
"Id": "241924",
"ParentId": "241916",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T02:42:19.190",
"Id": "241916",
"Score": "2",
"Tags": [
"python"
],
"Title": "Add 2 doubles in string format"
}
|
241916
|
<p>Mu solution to <a href="https://leetcode.com/problems/cousins-in-binary-tree/" rel="nofollow noreferrer">Leetcode problem Cousins in Binary Tree</a> works, but the code feels bulky. Is there a better way to solve this problem, particularly to use less additional variables? I will appreciate any suggestions on how to improve this code.</p>
<p><strong>Problem:</strong></p>
<blockquote>
<p>In a binary tree, the <code>root</code> node is at depth <code>0</code>, and children of each depth <code>k</code> node are at depth <code>k+1</code>.</p>
<p>Two nodes of a binary tree are cousins if they have the same depth, but have different parents.</p>
<p>We are given the <code>root</code> of a binary tree with unique values, and the values <code>x</code> and <code>y</code> of two different nodes in the tree.</p>
<p>Return <code>true</code> if and only if the nodes corresponding to the values <code>x</code> and <code>y</code> are cousins.</p>
</blockquote>
<p><strong>My code:</strong></p>
<pre><code>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
void is_cousins(TreeNode* root, int to_find, int depth,
TreeNode* parent, pair<int, TreeNode*>& pair) {
if (!root)
return;
is_cousins(root->left, to_find, depth + 1, root, pair);
is_cousins(root->right, to_find, depth + 1, root, pair);
if (root->val == to_find) {
pair.first = depth;
pair.second = parent;
return;
}
}
public:
bool isCousins(TreeNode* root, int x, int y) {
pair<int, TreeNode*> pairx = make_pair(0, nullptr);
pair<int, TreeNode*> pairy = make_pair(0, nullptr);
is_cousins(root, x, 0, nullptr, pairx);
is_cousins(root, y, 0, nullptr, pairy);
if (pairx.first == pairy.first && pairx.second != pairy.second)
return true;
return false;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T04:36:37.023",
"Id": "474881",
"Score": "0",
"body": "Good of you to explicitly state two concerns about your code: 1) bulk 2) amount of `additional variables`. The second wouldn't enter my mind; but seems about as valid as *single assignment*."
}
] |
[
{
"body": "<p>My first issue is that this function is badly named.</p>\n\n<pre><code> void is_cousins(TreeNode* root, int to_find, int depth, \n TreeNode* parent, pair<int, TreeNode*>& pair)\n</code></pre>\n\n<p>It has nothing to do with cousins. It is simply finding the depth and parent of a particular value. You should name it appropriateely.</p>\n\n<hr>\n\n<p>I don't like passing output parameters to a function:</p>\n\n<pre><code> void is_cousins(TreeNode* root, int to_find, int depth, \n TreeNode* parent, pair<int, TreeNode*>& pair)\n</code></pre>\n\n<p>The parameter <code>pair</code> is the output of the function. Why not just return this value. That would be more logical and easier to read.</p>\n\n<hr>\n\n<p>You don't have a truth state on whether the value <code>x</code> or <code>y</code> are found. I suppose you could say that <code>nullptr</code> in <code>pair</code> is a good way to test this. But that will make things complicated down the road when you try and use this function for other things that are not <code>cousin</code> related; so I don't like that idea. You could used a depth of <code>-1</code> to indicate failure that would be better.</p>\n\n<p>Talking of default values:</p>\n\n<p>Your current default result is <code>make_pair(0, nullptr)</code> this means you found the root as the value (even if the root value does not equal left of right). This may work for your current situation out of sheer luck but you are returning a bad value.</p>\n\n<p>i.e. A value that is not found in the tree and the root node will both return the same result.</p>\n\n<hr>\n\n<p>Here is a major ineffeciency.</p>\n\n<pre><code> is_cousins(root->left, to_find, depth + 1, root, pair);\n is_cousins(root->right, to_find, depth + 1, root, pair);\n</code></pre>\n\n<p>If you find the value on the left you still search the right subtree. This means you always search the whole tree even if you find the correct node very quickly.</p>\n\n<p>You should check the result of the left search before doing the right search.</p>\n\n<hr>\n\n<p>This is an anti patten</p>\n\n<pre><code> if (pairx.first == pairy.first && pairx.second != pairy.second)\n return true;\n return false;\n</code></pre>\n\n<p>The pattern:</p>\n\n<pre><code> if (test) {\n return true;\n }\n return false;\n\n // Can always be simplified to:\n\n return test;\n</code></pre>\n\n<p>This is a long handed way of writing:</p>\n\n<pre><code> return pairx.first == pairy.first && pairx.second != pairy.second;\n</code></pre>\n\n<p>If you think that is too long for an expression to use in a reurn, then it is too long an expression for any context. In that case you should put the test in a named function so it is obvious what it is doing.</p>\n\n<pre><code> return are_cousing_nodes_from_Depth(pairx, pairy);\n\n using DepthInfo = pair<int, TreeNode*>;\n inline bool are_cousing_nodes_from_Depth(DepthInfo const& lhs, DepthInfo const& rhs)\n {\n return lhs.first == rhs.first // Same depth\n && lhs.second != rhs.second; // Not siblings\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:20:33.563",
"Id": "241952",
"ParentId": "241922",
"Score": "2"
}
},
{
"body": "<p>Remarks about <em>algorithm</em>:</p>\n\n<p>I see <code>findParentDepth()</code> (my suggestion for \"the look-for-single-value method\") doing a full traversal. Input specification is <code>tree with unique values</code>:<br>\nstop looking on first occurrence.</p>\n\n<p>(If not a single value was found there is no cousin.)</p>\n\n<p>With one value (say, <em>a</em>) found, one condition for <em>no cousins</em> would be the other child holding the other value <em>b</em>:\ncheck the right child.</p>\n\n<p>All that might still be needed is a <em>level search</em> for <em>b</em> at the level of <em>a</em>, possibly excluding the part of the tree already traversed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T04:54:24.850",
"Id": "474882",
"Score": "1",
"body": "I do not yet have an idea how to decently code *a level search for b at the level of a excluding the part of the tree already traversed*. Not sure, too, of the merits of checking for *b* in upper levels, immediately exiting when found."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T04:53:21.123",
"Id": "241982",
"ParentId": "241922",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241952",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T04:59:04.690",
"Id": "241922",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"tree",
"binary-tree"
],
"Title": "Leetcode: Cousins in Binary Tree"
}
|
241922
|
<p>Any comments, critiques or questions about this? I'm using this as the base for a few rectangular board based toy programs like Conway's life and snake. Usage includes configuration of board size at runtime, hence the type doesn't carry size info, only the instances.</p>
<pre><code>#include <utility>
template<typename type>
class Array2D {
int y;
type *data;
public:
// We can't do a copy since we don't know
// what size to allocate the array.
Array2D(const Array2D&) = delete;
Array2D& operator=(const Array2D&) = delete;
Array2D(Array2D&& move) noexcept :
y(std::exchange(move.y, 0)),
data(std::exchange(move.data, nullptr)) {}
Array2D& operator=(Array2D&& move) noexcept {
std::swap(y, move.y);
std::swap(data, move.data);
}
Array2D( int _x, int _y ) : y(_y) {
data = new type[_x*y];
}
type const *operator[](int i) const {
return data + (i * y);
}
type *operator[](int i) {
return data + (i * y);
}
~Array2D() {
delete[] data;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:45:44.927",
"Id": "474803",
"Score": "0",
"body": "Can you provide an example of usage such as a unit test case?"
}
] |
[
{
"body": "<p>I have a couple of comments here.</p>\n\n<h3>Move \"yayy\" but copy \"nay\"?</h3>\n\n<p>I do understand why you don't keep the size information as a template parameter on the type, but is there a real reason why not to keep it on the instance? I mean, why do you only have <code>int y</code> rather than <code>int x, y</code>?</p>\n\n<p>I think this:</p>\n\n<pre><code>// We can't do a copy since we don't know\n// what size to allocate the array.\n</code></pre>\n\n<p>Is quite problematic. Not having a copying mechanism is (most of the time) due to resource sharing not being practical in the context. But for matrices, it seems very intuitive to copy them. That's one thing to think of, although your design might require (or be satisfied) with uncopyable matrices.</p>\n\n<p>Another argument here is the way you want invalid access to the array to fail. Currently, it seems that you're going to access your array in the following way: <code>arr[2][5]</code>. What happens if your array has a size of 5*5 but you access it on <code>arr[6][10]</code>? That's right, a segmentation fault.</p>\n\n<p>You do want your type to \"fail safely\", whether that's by emitting an exception or returning a default value and logging the error. Maybe today you handle calls to the array in the following way</p>\n\n<pre><code>int x = 5, y = 5;\nArray2D arr(x, y);\n// ...\n\nint requiredX = ..., requiredY = ..., value = 0;\nif (requiredX < x && requiredY < y) {\n value = arr[requiredX][requiredY];\n}\n</code></pre>\n\n<p>In this case, you do have to manage your X and Y. Why not do it inside your class?</p>\n\n<p>The only other way I see to properly guarantee memory safety is using a single pair of <code>const</code> (or <code>#define</code>d) height and width for your array. And in this case, why not include it in the type anyway, right? (not really, but I'm just making a point)</p>\n\n<p>Anyway, I suggest putting the \"height\" of the matrix as a member. After all, it's just 4/8 more bytes and it's going to save you a fortune.</p>\n\n<h3>Why is your size signed?</h3>\n\n<p>Your array cannot have negative indices, right? Make your <code>x</code> and <code>y</code> members of an unsigned type (preferably the pointer type on the system, which is <code>size_t</code>)</p>\n\n<h3>Destructor may throw</h3>\n\n<p><code>delete[]</code> is not a safe operation in C++, it may throw. Now, it might be due to memory corruption around your <code>data</code> member, and it really <em>shouldn't</em> happen, but it may. Destructors shouldn't throw, says the law. So make sure it doesn't throw. You can just <code>try{} catch(...) {}</code> around the delete statement and log the error if anything happens.</p>\n\n<h3>Use a middleware type for array access?</h3>\n\n<p>As I mentioned earlier, you don't seem to restrict access to the array. The most idiomatic way, in my opinion, is to make a middleware mini-type to reference rows in the array. Have a simple implementation (ignoring any ownership discipline and move semantics):</p>\n\n<pre><code>template <class T>\nclass ArrayRow {\npublic:\n ArrayRow(T* ptr, size_t size) : .... {}\n\n T& operator[](size_t index) && {\n if (index >= row_size) throw ...\n return row[row_size];\n }\n\nprivate:\n T* row;\n size_t row_size;\n}\n</code></pre>\n\n<p>Of course, implement <code>const</code> aware access to this class, etcetera etcetera. The array should implement member access in the following way (again, ignoring many other concerns)</p>\n\n<pre><code>ArrayRow operator[](size_t index) {\n if (index >= x) throw ...\n return ArrayRow(data + y * index, y);\n}\n</code></pre>\n\n<p>The only atrocity we are afraid to commit in this case is thus:</p>\n\n<pre><code>ArrayRow row(nullptr, 0);\n{\n Array2D arr(x, y);\n // ...\n row = arr[3];\n}\n\nint x = row[2]; // This happens after arr was released\n</code></pre>\n\n<p>This can be solved by restricting assignments to ArrayRow, and having that <code>&&</code> qualifier on the <code>operator[]</code> function (that requires the ArrayRow to be an rvalue or xvalue reference, practically saying it has to be the return value of a function, such as <code>Array2D::operator[]</code>.</p>\n\n<h3>Just a couple more notes</h3>\n\n<ol>\n<li><p>I would implement the non-<code>const</code> array access in terms of the <code>const</code> one (cast <code>*this</code> to <code>const Array2D<T></code>, then call the <code>[]</code> operator, then cast the result back to non-<code>const</code>. That way you don't have code repetition and make it easier to change the way array access is implemented.</p></li>\n<li><p>I would create a non-throwing swap method and just call it from the assignment operator. Although it's not highly relevant to your case, I would still look at <a href=\"https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-throwing_swap\" rel=\"nofollow noreferrer\">Why you should create a non-throwing swap() function</a></p></li>\n<li><p>As a style note, I would put your private members in the bottom of the class declaration and not at the top (are the clients of this class really going to be interested in the private fields more than in the public interface?)</p></li>\n<li><p>Also a style note, but consider initializing stuff with uniform initialization syntax <code>{}</code> rather than default initialization syntax <code>()</code>. If your <code>Array2D<T></code>'s <code>T</code>s are not going to have a constructor which takes an <code>std::initializer_list</code>, it's not really error-prone and generally preferable.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:01:24.937",
"Id": "474779",
"Score": "0",
"body": "There is just an error on destructors. You misunderstand the meaning behind destructors': cannot-throw. They are implicitly `noexcept` - which means that it won't throw an exception. It doesn't mean that code inside must not. It can, it which case the program will terminate instead of unwinding the stack. So his destructor is perfectly fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:59:23.033",
"Id": "474791",
"Score": "0",
"body": "If you're fine with your program terminating uncleanly... Well, it's fine, and maybe on this occasion, it works fine, too. But conceptually, you don't really want your program to exit without cleaning after itself (what if it left a lock file on the file-system that needs to be deleted?). Even if it may be legal to throw an exception in a destructor, I would argue that you really really _should_ not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T12:50:57.643",
"Id": "474798",
"Score": "1",
"body": "if `delete[]` throws there then the program is already corrupted beyond recovery. Adding a-too-late try/catch doesn't help it. It might even prevent programmer from detecting bugs. Since probably program is already in UB territory - doing one thing might result in something else entirely. It is generally advisable to simply shutdown before any more harm is done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:30:00.480",
"Id": "474827",
"Score": "1",
"body": "`You do want your type to \"fail safely\", whether that's by emitting an exception or returning a default value and logging the error. ` No. The standard pattern (in C++) is that `operator[]` is not safe (but fast) and you should check before use. If you want a checking version you add the method `at(int index)` this would be a checked version. `for(int loop = 0;loop < vec.size();++loop) {std::cout << vec[loop];}` Why would you want to force a check here? You have guaranteed that loop is always in range and thus a check is inefficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:36:05.350",
"Id": "474830",
"Score": "1",
"body": "`So make sure it doesn't throw.` This is really bad advice. If the memory is corrupted and this is causign an exception then you have a much bigger problem. You should not catch the exception but allow it to propogate. If this is inside the destructor fine you will cause the application to exit but in the situation where you have corrupted memory this is the most desirable result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:37:18.017",
"Id": "474831",
"Score": "0",
"body": "`Use a middleware type for array access?` If you want checked access add the `at()` method. Leave `operator[]` unchecked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:39:33.420",
"Id": "474832",
"Score": "0",
"body": "`The only atrocity we are afraid to commit in this case is thus:` You can solve that by making the constructor private and only accessible from `Array2D`. Thus it can never be constructed incorrectly (ie nullptr)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:40:22.380",
"Id": "474834",
"Score": "0",
"body": "`I would implement the non-const array access in terms of the const one` Sure you could but in this simple case not worth it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:42:01.000",
"Id": "474835",
"Score": "0",
"body": "`As a style note, I would put your private members in the bottom of the class declaration and not at the top` Completely disagree. As a style thing put the private member **variables** at the top (so you can easily see them in conjunction with the constructor. **BUT** yes put the private member methods at the bottom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:43:11.513",
"Id": "474858",
"Score": "0",
"body": "Re 4), How would I use a uniform initializer here? The constructor muist do the real work of allocating the memory?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T21:04:41.667",
"Id": "474862",
"Score": "0",
"body": "@MartinYork Thanks for the helpful comments, some which I agree with and some which I don't. I learnt a few things anyway. Will edit my answer with some of your advice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T21:07:44.213",
"Id": "474863",
"Score": "0",
"body": "@PeteFordham If I'm not mistaken, you can initialize `data` in the constructor with `: data{new type[_x * y]}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T21:37:19.500",
"Id": "474864",
"Score": "0",
"body": "OK, I see that that works, but what makes this inherently better than braces?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T22:52:18.033",
"Id": "474870",
"Score": "2",
"body": "@PeteFordham: It's not inherently better in this case (its the same). But if you use the '{}' syntax you can use it consistently everywhere (even when you want to be explicit about using the default constructor). On the other hand the '()' syntax can not be used consistently everywhere. In a few situations (see most vexing parse) you need to do some tricks to get it working correctly. In programming consistency is considered a good thing."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:33:54.333",
"Id": "241928",
"ParentId": "241923",
"Score": "2"
}
},
{
"body": "<h2>Overall</h2>\n<p>It's fine as far as it goes.</p>\n<p>I don't see anything wrong with the implementation.</p>\n<p>Note: Since you use none checked version of <code>operator[]</code> you should have the ability to validate that your inputs are correct. So your array needs the ability to return the dimensions of the array in both the x and y dimensions so the code can validate the inputs when required.</p>\n<h2>Next Step</h2>\n<p>Currently this is not a container.</p>\n<p>There are a few more requirements to make this a standards compliant container. If you want to go this direction.</p>\n<p>see: <a href=\"https://en.cppreference.com/w/cpp/named_req/Container\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/named_req/Container</a></p>\n<h2>Some improvements:</h2>\n<p>User defined Types (and by extension template types) should always have an initial capitol letter. This is for humans so we can easily distiguish types from objects:</p>\n<pre><code>template<typename type>\n</code></pre>\n<p>I don't like this as now type looks like an object to me when I read it in the code.</p>\n<p>Put the destructor next to the constructors.<br />\nWhen code reviewing I want to make sure that your destructor releases the resources correctly as I read. Not scroll back when I find the destructor at the bottom. Also they logically group together.</p>\n<p>Why is none copy?<br />\nI don't see the logic in that.</p>\n<p>Add a swap method (noexcept) and swap free standing function. That comes in handy when interacting with the standard library functions.</p>\n<p>It would be nice to simply loop over an array:</p>\n<pre><code>Array2D<int> data = get2DArray();\n\nfor(auto const& val: data) {\n std::cout << val << " ";\n}\n</code></pre>\n<p>The ability to extract rows to loop over would also be nice (this is an alternative to the above).</p>\n<pre><code>for(auto const& row: data) {\n for(auto const& val: row) {\n std::cout << val << " "; \n }\n std::cout << "\\n";\n}\n</code></pre>\n<p>You have the none checked <code>operator[]</code> implemented fine. But sometimes it is nice to have checked versions so add the method <code>at()</code> that does the same thing but validates its input first.</p>\n<p>This is very C like <code>type const *object</code> The <code>*</code> placed next to the object is a standard C convention but in C++ the convention is the opposite and (by tradition) you put the <code>*</code> next to the type rather than the objet (as it is part of the type information).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:54:19.820",
"Id": "241957",
"ParentId": "241923",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T05:57:43.567",
"Id": "241923",
"Score": "1",
"Tags": [
"c++"
],
"Title": "RFC: Lightweight C++ 2D array template with runtime dinemsions"
}
|
241923
|
<p>Below is my function to solve the <strong>Minion Game problem</strong> on <a href="https://www.hackerrank.com/challenges/the-minion-game/problem" rel="nofollow noreferrer">HackerRank</a> along with the problem description.</p>
<p><strong>It works wonderfully with regular-length strings, like 'banana'</strong>, but when it comes to really long ones (ones that produce output counter in the vicinity of <em>7501500</em>, result in a runtime error (or memory error, depending on where you run it).</p>
<p>There must be a way to optimize the code. Can anybody advise?</p>
<pre><code>"""Kevin and Stuart want to play the 'The Minion Game'.
Game Rules
Both players are given the same string, S.
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.
Scoring
A player gets +1 point for each occurrence of the substring in the string S.
For Example:
String
S = BANANA
Kevin's vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.
"""
def minions(s):
vowels = ['A','E','I','O','U']
s = s.upper()
n = len(s)
kevin = dict()
stuart = dict()
# list all string variations using list comprehension
lst = [s[i:j+1] for i in range(n) for j in range(i,n)]
# populate dictionaries
for i in lst:
if i[0] in vowels:
if i in kevin:
kevin[i] += 1
else:
kevin[i] = 1
else:
if i in stuart:
stuart[i] += 1
else:
stuart[i] = 1
kevin_sm = 0
for x,y in kevin.items():
kevin_sm += y
stuart_sm = 0
for x,y in stuart.items():
stuart_sm += y
if kevin_sm > stuart_sm:
print("Kevin {}".format(kevin_sm))
elif kevin_sm == stuart_sm:
print("Draw")
else:
print("Stuart {}".format(stuart_sm))
</code></pre>
<p>Example of a problematic string:</p>
<pre><code>NANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANAN
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:11:04.057",
"Id": "474750",
"Score": "2",
"body": "For which exact example strings does the code run out of support? Are you sure your code is ready for review if the code doesn't complete all testcases? Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:44:15.980",
"Id": "474755",
"Score": "2",
"body": "added an example string to the problem body. The code doesn't complete all testcases precisely because of the problem I mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:31:58.950",
"Id": "474759",
"Score": "0",
"body": "Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Feel free to come back once the code passes the testcases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:45:50.320",
"Id": "474762",
"Score": "2",
"body": "The question very much is about performance and scalability. Their code *works* but is not performant enough and does not scale well. They could have just not mentioned that a test case (one that is about performance/scalability, not core functionality) is failing and the question would have been on topic, just by virtue of them asking \"Can this be made more performant?\". The code even **works for the provided test case** that OP said failed (on the HackerRank website); it just happens to take 2 minutes (recent i7) and 8GBs of RAM..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:20:31.310",
"Id": "474784",
"Score": "0",
"body": "Thanks, Alex. Noted for the future."
}
] |
[
{
"body": "<p>By storing all possible substrings in a dictionary, you require memory for all the duplicates your are creating.\nThis is probably the cause for the memory errors.</p>\n\n<p>You also iterate over two dictionaries and the (long) list, which will be slower than what is described below.\nCreating the <code>lst</code> in the first place requires two nested <code>for</code> loops; they don't have quadratic complexity, but are expensive still.</p>\n\n<hr>\n\n<p>The problem can be tackled very differently if seen like in the following.\nTake the example of <code>BANANA</code>.\nIts length is <code>word_length = 6</code>.\nYou look at the first letter, <code>B</code>; it's a consonant.\nAs such, Stuart would score for this one.</p>\n\n<p>Of course, the substring <code>BANANA</code> occurs only once in <code>BANANA</code>.\nHowever, you can count all truncations of it as their own substrings.\nOne by one, you chop off the last letter, leading you to:</p>\n\n<pre><code>BANANA\nBANAN\nBANA\nBAN\nBA\nB\n</code></pre>\n\n<p>All of these are substrings found in <code>BANANA</code>.\nRemember, we are still looking at the first letter, <code>B</code>, which is indexed as <code>0</code>.\nWe found <code>word_length - i = 6 - 0 = 6</code> valid substrings, all of which count towards Stuart's score.</p>\n\n<p>Let's see if the above pattern holds going forward.\nThe next letter is <code>A</code>, <code>i</code> becomes <code>1</code>.\n<code>word_length</code> is a constant.</p>\n\n<pre><code>ANANA\nANAN\nANA\nAN\nA\n</code></pre>\n\n<p>This makes for <code>6 - 1 = 5</code> valid substrings, counted towards Kevin's score this time.</p>\n\n<p>The third step looks like:</p>\n\n<pre><code>NANA\nNAN\nNA\nN\n</code></pre>\n\n<p>with a score of <code>word_length - i = 6 - 2 = 4</code> for Stuart.</p>\n\n<p>Note that substrings which occur more than once are counted correctly.\nFor example, the substring <code>NA</code> will be counted twice in the overall score.\nUntil now, it has been accounted for once, in the third step.\nThe next time it is counted will be in the fifth step, where the substrings looks like:</p>\n\n<pre><code>NA\nN\n</code></pre>\n\n<p>As such, <code>N</code> will also be counted correctly (twice).</p>\n\n<hr>\n\n<p>Let the input string length be <span class=\"math-container\">\\$ n \\$</span>.\nIn this case, the below approach only iterates over it once, leading to <span class=\"math-container\">\\$ \\mathcal{O}(n) \\$</span>, linear, complexity.\nThe rest is just incrementing integers, which is very cheap.\n<code>word_length</code> has to be computed once, which is <span class=\"math-container\">\\$ \\mathcal{O}(1) \\$</span> (constant/cheap).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def minion_game(word):\n # word = input()\n\n vowels = \"AEIOU\"\n\n vowel_score = 0\n consonant_score = 0\n\n word_length = len(word)\n for idx, letter in enumerate(word):\n delta = word_length - idx\n if letter in vowels:\n vowel_score += delta\n else:\n consonant_score += delta\n\n if vowel_score > consonant_score:\n print(\"Kevin\", vowel_score)\n elif vowel_score < consonant_score:\n print(\"Stuart\", consonant_score)\n else:\n print(\"Draw\")\n</code></pre>\n\n<hr>\n\n<p>Other points on your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> for x,y in kevin.items():\n kevin_sm += y\n</code></pre>\n\n<p>can just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> for y in kevin.values():\n kevin_sm += y\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>vowels = ['A','E','I','O','U']\n</code></pre>\n\n<p>can, in this context, just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>vowels = \"AEIOU\"\n</code></pre>\n\n<p>It will behave the same for the <code>in</code> lookup.\nYou will want a list if you required a mutable object.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in lst:\n</code></pre>\n\n<p>is very misleading variable naming.\n<code>lst</code> is a list of string slices, and not indices (<code>i</code>).\nIt should read something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for substring in substrings:\n</code></pre>\n\n<p>(aka, also rename the too-generic <code>lst</code> variable).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:40:41.633",
"Id": "474775",
"Score": "1",
"body": "`vowels = \"AEIOU\"` is really neat. you could omit the delta calculation altogether if you were to e.g. `enumerate( reversed( word ), 1 )` or `zip( word, range( word_length, 0, -1 ) )` switching indices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:48:47.763",
"Id": "474776",
"Score": "1",
"body": "Good point. Usually I'm not a fan of densifying code too much, but this is useful and readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:07:12.060",
"Id": "474781",
"Score": "1",
"body": "@ALexPovel, thank you very much for your elaborate answer. This really helps a lot."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:41:25.030",
"Id": "241934",
"ParentId": "241925",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241934",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T07:46:31.083",
"Id": "241925",
"Score": "3",
"Tags": [
"python"
],
"Title": "Runtime Error in Minion Game problem (HackerRank)"
}
|
241925
|
<p>I have a string "abbbbccdddd" and the function should return "a1b4c2d4".</p>
<p>This is what I have written in Scala.</p>
<h1>Iterative-version</h1>
<pre class="lang-scala prettyprint-override"><code>def compress(str: String) = {
val chars = List(str).flatten.map(_.toString) ++ List(null)
var result: String = ""
var lookBack: String = chars.head
var occurance: Int = 0
chars.foreach { c =>
if (c != lookBack) {
result = result + lookBack.toString + occurance
occurance = 0
}
occurance = occurance + 1
lookBack = c
}
result
}
</code></pre>
<h1>Recursive-version</h1>
<pre><code>def compress(str: String): String = {
def compressHandler(str: String, lookBack: String, occurance: Int, result: String): String = {
if(str.isEmpty) {
result
} else if(str.head.toString == lookBack) {
compressHandler(str.drop(1), str.head.toString, occurance + 1, result)
} else {
compressHandler(str, str.head.toString, 0, result + lookBack + occurance)
}
}
compressHandler(str + "0", str.head.toString, 0, "")
}
</code></pre>
<p>Scala — being a functional language should have much better solutions!</p>
<p>How to improve second (by somehow using map/reduce/fold) and how to do the first following concept of immutability (purely functional)? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-26T14:21:32.137",
"Id": "483381",
"Score": "0",
"body": "You can use mutable vars or collections. It is not tabu. The most important things are simplicity and sufficient speed. For speed you should not use head, tail and reverse for String in this task. For simplisity you can use simple counter var and index. In some tasks you should prefer FP, in some -- iterative, in some -- special functions. I advice you to see Scala Days with Martin Odersky for 2013 оr 2014 year"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-26T14:27:51.897",
"Id": "483384",
"Score": "0",
"body": "Scala days: Scala with style https://youtu.be/kkTFx3-duc8"
}
] |
[
{
"body": "<p>Here's my take using foldLeft:</p>\n\n<pre><code>def compress(s: String) = {\n val a : List[(Char,Int)] = List()\n s.toCharArray.foldLeft(a)((acc, elem) => acc match {\n case Nil => (elem, 1) :: Nil\n case (a, b) :: tail =>\n if (a == elem) (elem, b + 1) :: tail else (elem, 1) :: acc\n }).reverse\n .map{ case (a, b) => a.toString + b }\n .mkString(\"\")\n}\n</code></pre>\n\n<p><em>Note</em>: I have assumed that order matters. That is, <code>aabbbaa</code> will reduce to <code>a2b3a2</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:38:31.347",
"Id": "474760",
"Score": "0",
"body": "Cool stuff! However we can desugar this and get rid of `._1` and `._2` but it seems perfect to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:44:58.597",
"Id": "474761",
"Score": "0",
"body": "changed to get rid of `._1` and `._2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:53:29.233",
"Id": "474805",
"Score": "2",
"body": "Welcome to code review. This answer is an alternate solution which is fine on stackoverflow.com but is not a good answer on code review. A good answer may not contain any code at all, but it must contain at least one meaningful observation about the code posted in the the question. Code can be used as examples to support the observations about the posters code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:31:41.640",
"Id": "241932",
"ParentId": "241926",
"Score": "3"
}
},
{
"body": "<p>I would suggest omitting the allocation of extra space. Try to start with:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>object Solution:\n def compress(str: String): String =\n val (sb, _) = \n Vector.range(0, str.size + 1).foldLeft(StringBuilder(), 0) { \n case ((sb, occurance), i) =>\n if i == 0\n ???\n else if i == str.size\n ???\n else if str(i) == str(i - 1)\n ???\n else\n ???\n }\n sb.toString\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T07:48:54.200",
"Id": "245267",
"ParentId": "241926",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241932",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T07:53:52.550",
"Id": "241926",
"Score": "3",
"Tags": [
"scala"
],
"Title": "Compressing string in Scala, how to do this immutably?"
}
|
241926
|
<p>I wanted to open source some code to scrape and analyze publicly-filed stock buys and sells from U.S. senators. I'm not familiar with code style for Jupyter notebooks or pandas in general. Would it be possible for you to review my short notebook? The original can be found <a href="https://github.com/neelsomani/senator-filings/blob/eef6afd3d94ed6a948ad566816418737109534dc/notebooks/Senator%20Filings%20Analysis.ipynb" rel="nofollow noreferrer">here</a>.</p>
<p>Ideally I would get the scraping code reviewed as well, but for the sake of brevity I wanted to keep it to just the pandas and Jupyter notebook-related changes. Within scope is things like how the Jupyter notebook should be structured, general Python code style, and pandas conventions + optimizations.</p>
<p>I know that this is a larger ask, so I am also open to just high-level suggestions.</p>
<p>I have included the contents of the Jupyter notebook below. (I thought about removing the <code># In[ ]:</code> comments, but realized they indicate where each Jupyter cell begins.) Thank you in advance!</p>
<pre><code># # Senator Filings Analysis
# ***
# ## Imports
# In[ ]:
from collections import defaultdict
import datetime as dt
from functools import lru_cache
import json
from os import path
import pickle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import yfinance as yf
# ## Introduction
#
# In this notebook, we explore stock orders that were publicly filed by U.S. senators. The filings are scraped from https://efdsearch.senate.gov/search/. We calculate the returns of each senator by mimicking their buys and sells.
# ***
# ## Loading data
#
# The `senators.pickle` file is scraped using the script in the root of the repository.
# In[ ]:
with open('senators.pickle', 'rb') as f:
raw_senators_tx = pickle.load(f)
# ## Data cleaning
# ### Filling in missing tickers
# In this section, we fill in as many of the missing ticker symbols as we can.
# In[ ]:
def tokenize(asset_name):
""" Convert an asset name into useful tokens. """
token_string = asset_name
.replace('(', '')
.replace(')', '')
.replace('-', ' ')
.replace('.', '')
return token_string.split(' ')
def token_is_ticker(token, token_blacklist):
return len(token) <= 4 and token.upper() not in token_blacklist
# These generic words do not help us determine the ticker
with open('blacklist.json', 'r') as f:
blacklist = set(json.load(f))
missing_tickers = set(raw_senators_tx[
(raw_senators_tx['ticker'] == '--')
| (raw_senators_tx['ticker'] == '')
]['asset_name'])
ticker_map = {}
unmapped_tickers = set()
for m in missing_tickers:
tokens = tokenize(m)
if token_is_ticker(tokens[0], blacklist):
ticker_map[m] = tokens[0].upper()
elif token_is_ticker(tokens[-1], blacklist):
ticker_map[m] = tokens[-1].upper()
else:
unmapped_tickers.add(m)
# As a second pass, we assign tickers to asset names that have any of the specified keywords.
# In[ ]:
phrase_to_ticker = {
'FOX': 'FOX',
'AMAZON': 'AMZN',
'AARON': 'AAN',
'ALTRIA': 'MO',
'APPLE': 'AAPL',
'CHEVRON': 'CVX',
'DUPONT': 'DD',
'ALPHABET': 'GOOGL',
'GOOG': 'GOOGL',
'GENERAL ELECTRIC': 'GE',
'JOHNSON': 'JNJ',
'NEWELL': 'NWL',
'OWENS': 'OMI',
'PFIZER': 'PFE',
'TYSON': 'TSN',
'UNDER ARMOUR': 'UAA',
'VERIZON': 'VZ',
'WALT': 'DIS'
}
for m in unmapped_tickers:
for t in phrase_to_ticker:
if t in m.upper():
ticker_map[m] = phrase_to_ticker[t]
tx_with_tickers = raw_senators_tx.copy()
for a, t in ticker_map.items():
tx_with_tickers.loc[tx_with_tickers['asset_name'] == a, 'ticker'] = t
# ### Filtering rows and columns
# We filter out useless rows and missing symbols, and then add some useful columns for the final dataset.
# In[ ]:
filtered_tx = tx_with_tickers[tx_with_tickers['ticker'] != '--']
filtered_tx = filtered_tx.assign(
ticker=filtered_tx['ticker'].map(
lambda s: s.replace('--', '').replace('\n', '')))
filtered_tx = filtered_tx[filtered_tx['order_type'] != 'Exchange']
# In[ ]:
def parse_tx_amount(amt):
""" Get the lower bound for the transaction amount. """
return int(amt.replace('Over $50,000,000', '50000000')
.split(' - ')[0]
.replace(',', '')
.replace('$', ''))
senators_tx = filtered_tx.assign(
tx_estimate=filtered_tx['tx_amount'].map(parse_tx_amount))
senators_tx = senators_tx.assign(
full_name=senators_tx['first_name']
.str
.cat(senators_tx['last_name'], sep=' ')
)
useful_cols = [
'file_date',
'tx_date',
'full_name',
'order_type',
'ticker',
'tx_estimate'
]
senators_tx = senators_tx[useful_cols]
senators_tx = senators_tx.assign(
tx_date=senators_tx['tx_date'].map(
lambda v: dt.datetime.strptime(v, '%m/%d/%Y')))
senators_tx = senators_tx.assign(
file_date=senators_tx['file_date'].map(
lambda v: dt.datetime.strptime(v, '%m/%d/%Y')))
senators_tx
# ## Returns calculation
# These cells help us download the market data for the specified tickers. We store the market data in files so we don't need to repeatedly download the same information.
# In[ ]:
def download_for_ticker(ticker, check_cache=True):
""" Download a file of stock prices for this ticker to disk. """
if check_cache and path.exists('stocks/{0}.pickle'.format(ticker)):
return
d = yf.Ticker(ticker)
with open('stocks/{0}.pickle'.format(ticker), 'wb') as f:
pickle.dump({
'price': d.history(period='max').reset_index()
}, f)
def load_for_ticker(ticker):
""" Load the file of stock prices for this ticker. """
with open('stocks/{0}.pickle'.format(ticker), 'rb') as f:
dump = pickle.load(f)
raw = dump['price']
return raw[['Date', 'Close']]
.rename(columns={'Date': 'date', 'Close': 'price'})
def _price_for_date(df, date):
""" Helper function for `ticker_at_date`. """
df = df[df['date'] >= date].sort_values(by='date')
return df['price'].iloc[0]
@lru_cache(maxsize=128)
def ticker_at_date(ticker, date):
"""
Price of a ticker at a given date. Raise an IndexError if there is no
such price.
"""
try:
data = load_for_ticker(ticker)
# Sell at the next opportunity possible
return _price_for_date(data, date)
except Exception:
# If any exception occurs, refresh the cache
download_for_ticker(ticker, check_cache=False)
data = load_for_ticker(ticker)
return _price_for_date(data, date)
# In[ ]:
all_tickers = set(senators_tx['ticker'])
for i, t in enumerate(all_tickers):
if i % 100 == 0:
print('Working on ticker {0}'.format(i))
try:
download_for_ticker(t)
except Exception as e:
print('Ticker {0} failed with exception: {1}'.format(t, e))
# ### Mimicking buy + sell orders
#
# We calculate a given senator's return by calculating the return between each buy or sell order, and then solving for the cumulative return. We convert that to a CAGR given the time period the senator was investing.
#
# We keep track of how many units of each stock a senator is holding. If we ever see a filing that indicates the senator sold more than we estimated they are holding, we just sell all of the units we have on record. (We do not allow the senator to go short.)
# In[ ]:
buckets = [
(1000, 15000),
(15000, 50000),
(50000, 100000),
(100000, 250000),
(250000, 500000),
(500000, 1000000),
(1000000, 5000000),
(5000000, 25000000),
(25000000, 50000000),
(50000000, float('inf'))
]
def same_bucket(dollar_value_a, dollar_value_b):
"""
If the dollar value of the stock units is roughly the same, sell all
units.
"""
for v1, v2 in buckets:
if dollar_value_a >= v1 and dollar_value_a < v2:
return dollar_value_b >= v1 and dollar_value_b < v2
return False
def portfolio_value(stocks, date):
"""
Value of a portfolio if each ticker has the specified number of units.
"""
v = 0
for s, units in stocks.items():
if units == 0:
continue
try:
v += ticker_at_date(s, date) * units
except IndexError as e:
# Swallow missing ticker data exception
pass
return v
def calculate_return(before_values,
after_values,
begin_date,
end_date,
tx_dates):
"""
Calculate cumulative return and CAGR given the senators portfolio
value over time.
"""
before_values.pop(0)
after_values.pop(-1)
# We calculate the total return by calculating the return
# between each transaction, and solving for the cumulative
# return.
growth = np.array(before_values) / np.array(after_values)
portfolio_return = np.prod(growth[~np.isnan(growth)])
years = (end_date - begin_date).days / 365
if years == 0:
cagr = 0
else:
cagr = portfolio_return**(1 / years)
# DataFrame of cumulative return
tx_dates.pop(0)
tx_dates = np.array(tx_dates)
tx_dates = tx_dates[~np.isnan(growth)]
cumulative_growth = np.cumprod(growth[~np.isnan(growth)])
growth_df = pd.DataFrame({
'date': tx_dates,
'cumulative_growth': cumulative_growth
})
return {
'portfolio_return': portfolio_return,
'annual_cagr': cagr,
'growth': growth_df
}
def return_for_senator(rows, date_col='tx_date'):
"""
Simulate a senator's buy and sell orders, and calculate the
return.
"""
stocks = defaultdict(int)
# Value of portfolio at various timepoints to calculate return
portfolio_value_before_tx = []
portfolio_value_after_tx = []
tx_dates = []
rows = rows.sort_values(by=date_col)
for _, row in rows.iterrows():
date = row[date_col]
if date_col == 'file_date':
# We can't execute the trade the same day
date += dt.timedelta(days=1)
try:
stock_price = ticker_at_date(row['ticker'], date)
except IndexError as e:
# Skip the row if we're missing ticker data
continue
value_before_tx = portfolio_value(stocks, date)
if 'Purchase' in row['order_type']:
tx_amt = row['tx_estimate']
n_units = tx_amt / ticker_at_date(row['ticker'], date)
stocks[row['ticker']] += n_units
elif 'Sale' in row['order_type']:
current_value = stock_price * stocks[row['ticker']]
if 'Full' in row['order_type'] or \
same_bucket(row['tx_estimate'], current_value):
stocks[row['ticker']] = 0
else:
new_n_units = stocks[row['ticker']] -\
row['tx_estimate'] / stock_price
stocks[row['ticker']] = max(0, new_n_units)
portfolio_value_before_tx.append(value_before_tx)
portfolio_value_after_tx.append(portfolio_value(stocks, date))
tx_dates.append(date)
return calculate_return(
portfolio_value_before_tx,
portfolio_value_after_tx,
begin_date=min(rows[date_col]),
end_date=max(rows[date_col]),
tx_dates=tx_dates
)
# In[ ]:
senator_returns = []
senator_tx_growth = {}
senator_file_growth = {}
senator_names = set(senators_tx['full_name'])
# The following cell took my laptop about three hours to run.
# In[ ]:
failed_senators = {}
print('{} senators total'.format(len(senator_names)))
for n in senator_names:
print('Starting {}'.format(n))
if n in senator_tx_growth:
# Don't re-calculate for a given senator
continue
try:
tx_return = return_for_senator(
senators_tx[senators_tx['full_name'] == n],
date_col='tx_date')
file_return = return_for_senator(
senators_tx[senators_tx['full_name'] == n],
date_col='file_date')
senator_returns.append({
'full_name': n,
'tx_total_return': tx_return['portfolio_return'],
'tx_cagr': tx_return['annual_cagr'],
'file_total_return': file_return['portfolio_return'],
'file_cagr': file_return['annual_cagr']
})
senator_tx_growth[n] = tx_return['growth']
senator_file_growth[n] = file_return['growth']
except Exception as e:
print('Failed senator {0} with exception {1}'.format(n, e))
failed_senators[n] = e
# We look at the results to see the senators that outperformed the market.
# In[ ]:
def plot_senator_growth(growth):
""" Plot the senator's portfolio growth against the S&P 500. """
plt.plot_date(growth['date'], growth['cumulative_growth'], '-')
download_for_ticker('SPY')
spy = load_for_ticker('SPY')
spy = spy[(spy['date'] >= min(growth['date']))
& (spy['date'] <= max(growth['date']))]
spy_prices = spy['price']
spy_growth = np.cumprod(np.diff(spy_prices) / spy_prices[1:] + 1)
dates = spy['date'].iloc[1:]
plt.plot_date(dates, spy_growth, '-')
plt.show()
print('Earliest date: {}'.format(min(growth['date'])))
print('Latest date: {}'.format(max(growth['date'])))
print('Market return: {}'.format(
spy_prices.iloc[-1] / spy_prices.iloc[0]))
senator_growth = growth['cumulative_growth']
print('Senator return: {}'.format(
senator_growth.iloc[-1] / senator_growth.iloc[0]))
# In[ ]:
returns = pd.DataFrame(senator_returns)
returns = returns[(returns['tx_total_return'] > returns['tx_cagr'])
& (returns['tx_cagr'] > 0)]
returns.sort_values('tx_cagr')
# In[ ]:
plot_senator_growth(senator_tx_growth['Angus S King, Jr.'])
# ## About this notebook
#
# Author: Neel Somani, Software Engineer
#
# Email: neel@berkeley.edu
#
# Website: https://www.ocf.berkeley.edu/~neel/
#
# Updated On: 2020-05-10
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:57:28.480",
"Id": "474928",
"Score": "0",
"body": "I see that downloading the file served you well. Nice question :) I have a minor suggestion. I personally would remove the final section \"About this notebook\" to not expose your email to the public. If you don't mind that, then please ignore me :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T00:28:19.800",
"Id": "474969",
"Score": "0",
"body": "Thanks! I don't mind - think it's pretty easy for people to find my email these days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T17:12:03.747",
"Id": "474998",
"Score": "0",
"body": "A recent websiite I look at - https://senatestockwatcher.com/ - is that what you're trying to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T01:49:36.347",
"Id": "475017",
"Score": "0",
"body": "I think that site is displaying the exact information from the STOCK act filings, but it doesn't do things like calculate returns or simulate portfolios on top of it. Useful website, though - thanks for sharing!"
}
] |
[
{
"body": "<p>First thing I notice is your imports.</p>\n\n<pre><code>from collections import defaultdict\nimport datetime as dt\nfrom functools import lru_cache\nimport json\nfrom os import path\nimport pickle\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport yfinance as yf\n</code></pre>\n\n<p>The good thing about your imports is they're listed alphabetically and all imports are on their own line. Can we improve this further? Yes. <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP8</a> wants us to split it into 3 groups:</p>\n\n<ul>\n<li>Standard library imports</li>\n<li>Related third party imports</li>\n<li>Local and library-specific imports</li>\n</ul>\n\n<p>But, honestly, I'd reorder them like this:</p>\n\n<pre><code>import json\nimport pickle\n\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport yfinance as yf\n\nfrom collections import defaultdict\nfrom functools import lru_cache\nfrom os import path\n</code></pre>\n\n<p>They're still alphabetically sorted, but now also sorted by <em>how</em> they're imported. Looks cleaner to me.</p>\n\n<p>And I understand this is Jupyter, where you create functions whenever you need them and not a moment sooner, but you first open your file and define a lot of functions right after it. Then you define a function mentioning a blacklist that's only explained after that function is defined and then comes the global that actually <em>does</em> something with the content of the file we read on the start.</p>\n\n<p>That looks awkward at best.</p>\n\n<p><code>useful_cols</code> is not a useful name when in the global scope. Had it be part of a function or method, it would make more sense. Now, what columns are we referring to? It is no table, so it must be a list of column headers. From an input file? Output file? An intermediary result? Can't tell by the name. Going by the styling of the rest of your project, even <code>tx_headers</code> would've been better.</p>\n\n<p><code>calculate_return</code> is a bit of a mess, but I'm not sure how to improve it. Having to call data like</p>\n\n<pre><code>senators_tx[senators_tx['full_name'] == n]\n</code></pre>\n\n<p>and</p>\n\n<pre><code>returns = returns[(returns['tx_total_return'] > returns['tx_cagr'])\n & (returns['tx_cagr'] > 0)]\n</code></pre>\n\n<p>looks odd as well, perhaps your data structure isn't optimized for what you're doing with it. If re-arranging your data takes 10 minutes extra and cuts the execution time of all other processes in half, you already have a massive gain. I'd definitely take a look in that direction. How much data do you get, how much do you actually use and is it in an actually useful format?</p>\n\n<p>Some of the returns could be more succinct, but most of them are fine and your error handling isn't too bad either. I think it would be beneficial to you if you move more to your code into functions, but you've done most of that already. For a Jupyter project it really doesn't look that bad.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T08:41:32.027",
"Id": "242447",
"ParentId": "241927",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:31:07.437",
"Id": "241927",
"Score": "5",
"Tags": [
"python",
"numpy",
"pandas",
"matplotlib",
"jupyter"
],
"Title": "Jupyter notebook style help + code suggestions for pandas"
}
|
241927
|
<p>I made some code about solar system stimulation in C. It is working, but it looks too long.</p>
<p>So, Are there some ways to shorten my code?</p>
<p>Also this website told me your code is too full to upload this.</p>
<pre><code>#include <Windows.h>
#include <stdio.h>
#include <math.h>
#define solar_size 20
#define PI 3.141592654
#define rad angle*180/PI
int angle;
double sun_x, sun_y, earth_x, earth_y;
double x, y, px, py;
double earth_speed = 0.05;
double x2, y2, x3, y3, x4, y4, x5, y5, x6, y6;
int main(void) {
double sun;
sun = sqrt(solar_size * 10);
HWND hwnd = GetForegroundWindow();
HDC hdc = GetWindowDC(hwnd);
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Rectangle(hdc, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
TextOut(hdc, 250, 450, L"solar system Simulation", 23);
sun_x = 300 ;
sun_y = 240 ;
SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(255, 0, 0)));
Ellipse(hdc, sun_x - sun, sun_y - sun, sun_x + solar_size, sun_y + solar_size);
while (1) {
for (angle = 0;; angle++) {
x = 30 * cos(angle * earth_speed * 2.5) + sun_x;
y = 30 * sin(angle * earth_speed * 2.5) + sun_y;
x2 = 55 * cos(angle * earth_speed * 1.5) + sun_x;
y2 = 55 * sin(angle * earth_speed * 1.5) + sun_y;
x3 = 85 * cos(angle * earth_speed) + sun_x;
y3 = 85 * sin(angle * earth_speed) + sun_y;
x4 = 110 * cos(angle * earth_speed * 0.6) + sun_x;
y4 = 110 * sin(angle * earth_speed * 0.6) + sun_y;
x5 = 140 * cos(angle * earth_speed * 0.4) + sun_x;
y5 = 140 * sin(angle * earth_speed * 0.4) + sun_y;
x6 = 180 * cos(angle * earth_speed * 0.15) + sun_x;
y6 = 180 * sin(angle * earth_speed * 0.15) + sun_y;
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(120, 120, 120)));
SelectObject(hdc, CreateSolidBrush(RGB(120, 120, 120)));
Ellipse(hdc, x, y, x + 8, y + 8);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(100, 80, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(100, 80, 0)));
Ellipse(hdc, x2, y2, x2 + 12, y2 + 12);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 50, 120)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 50, 120)));
Ellipse(hdc, x3, y3, x3 + 12, y3 + 12);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(120, 20, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(120, 20, 0)));
Ellipse(hdc, x4, y4, x4 + 10, y4 + 10);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(200, 80, 20)));
SelectObject(hdc, CreateSolidBrush(RGB(200, 80, 20)));
Ellipse(hdc, x5, y5, x5 + 17, y5 + 17);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(255, 220, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(255, 220, 0)));
Ellipse(hdc, x6, y6, x6 + 21, y6 + 21);
Sleep(50);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Ellipse(hdc, x, y, x + 8, y + 8);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Ellipse(hdc, x2, y2, x2 + 12, y2 + 12);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Ellipse(hdc, x3, y3, x3 + 12, y3 + 12);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Ellipse(hdc, x4, y4, x4 + 10, y4 + 10);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Ellipse(hdc, x5, y5, x5 + 17, y5 + 17);
SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));
SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));
Ellipse(hdc, x6, y6, x6 + 21, y6 + 21);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:49:00.070",
"Id": "474756",
"Score": "0",
"body": "You could factor out the code appearing in the `for` loops body to another function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:01:08.830",
"Id": "474757",
"Score": "3",
"body": "Please title your question for what the code presented is to accomplish: Heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) `solar system stimulation` do you intend *simulation*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:12:23.883",
"Id": "474758",
"Score": "2",
"body": "Describe what your code does to yourself. For each sentence describing the program, create a method or specific construction. Works most of the time. Same with documentation, I have had people ask me what to document. I normally reply well what does the code do? They answer and I reply, right write that down (and rename your variables to the terms you just used)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T09:42:54.940",
"Id": "474912",
"Score": "1",
"body": "The current code is less than a 10th of our character limit."
}
] |
[
{
"body": "<p>Haven't tested if the code works. I've simply shortened the code that was given in the question.</p>\n\n<p>In the code given in the question, there are variables x,x2,..x6 and y,...y6. These variables are all being used in a similar manner and a lot of code is redundant. </p>\n\n<p>For instance lines like </p>\n\n<pre><code>SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 0, 0)));\nSelectObject(hdc, CreateSolidBrush(RGB(255, 0, 0)));\nEllipse(hdc, sun_x - sun, sun_y - sun, sun_x + solar_size, sun_y + solar_size);\n</code></pre>\n\n<p>are constantly occurring in the code and differ only by some constants. So instead of using 6 variables, an array would be better. You could iterate through it and set the values one by one. Also, another array can be used to store the constant values that differ for each variable.</p>\n\n<pre><code>#include <Windows.h>\n#include <stdio.h>\n#include <math.h>\n\n#define solar_size 20\n#define PI 3.141592654\n#define rad angle*180/PI\n\nint angle;\n\ndouble sun_x, sun_y, earth_x, earth_y;\ndouble px, py;\ndouble earth_speed = 0.05;\ndouble x[6],y[6];\n\nint main(void) {\n double sun;\n sun = sqrt(solar_size * 10);\n\n HWND hwnd = GetForegroundWindow();\n HDC hdc = GetWindowDC(hwnd);\n\n SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));\n Rectangle(hdc, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));\n\n TextOut(hdc, 250, 450, L\"solar system Simulation\", 23);\n sun_x = 300 ;\n sun_y = 240 ;\n\n SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 0, 0)));\n SelectObject(hdc, CreateSolidBrush(RGB(255, 0, 0)));\n Ellipse(hdc, sun_x - sun, sun_y - sun, sun_x + solar_size, sun_y + solar_size);\n\n\n\n double speedCoefficients[] = {2.5, 1.5, 1, 0.6, 0.4, 0.15};\n int trignometricCoefficients[] = {30, 55, 85, 110, 140, 180};\n int ellipseCoefficients[]={8, 12, 12, 10, 17, 21};\n int r=[120, 100, 0, 120, 200, 255];\n int g=[120, 80, 50, 20, 80, 220];\n int b=[120, 0, 120, 0, 20, 0];\n\n while (1) {\n for (angle = 0;; angle++) {\n for(int i=0;i<6;i++)\n {\n x[i] = trignometricCoefficients[i] * cos(angle * earth_speed * speedCoefficients[i]) + sun_x;\n y[i] = trignometricCoefficients[i] * sin(angle * earth_speed * speedCoefficients[i]) + sun_y;\n\n SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(r[i], g[i], b[i])));\n SelectObject(hdc, CreateSolidBrush(RGB(r[i], g[i], b[i])));\n Ellipse(hdc, x[i], y[i], x[i] + ellipseCoefficients[i], y[i] + ellipseCoefficients[i]);\n }\n\n Sleep(50);\n\n for(int i=0;i<6;i++)\n {\n SelectObject(hdc, CreatePen(PS_SOLID, 3, RGB(0, 0, 0)));\n SelectObject(hdc, CreateSolidBrush(RGB(0, 0, 0)));\n Ellipse(hdc, x[i], y[i], x[i] + ellipseCoefficients[i], y[i] + ellipseCoefficients[i]);\n }\n\n }\n }\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T09:00:44.630",
"Id": "241931",
"ParentId": "241929",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241931",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:45:05.547",
"Id": "241929",
"Score": "-3",
"Tags": [
"beginner",
"c",
"image",
"graphics",
"visual-studio"
],
"Title": "how to make 'for loop' short in C?"
}
|
241929
|
<p>I'm very new to the JavaScript, and hence I would like to get a feel on the language by writing some of the basic programs. One of those is the following visualization of the <a href="https://en.wikipedia.org/wiki/Bubble_sort" rel="nofollow noreferrer">Bubble Sort</a>: </p>
<p>Code:</p>
<pre><code><!DOCTYPE html>
<html>
<body style="background: pink">
<p id="word" style="color: black">Bubble sort: visualization</p>
<button onclick=CreateBarPlot()>Generate data</button>
<button onclick=bubble_sort()>Sort</button>
<script>
var BARS_DATA = []
function GenerateNumbers(count = 15) {
var numbers = [];
var i;
for (i = 0; i < count; i++) {
numbers.push(Math.floor(Math.random() * (70 - 1)) + 1);
}
return numbers
}
function CreateBar(index, value) {
const div = document.createElement("div");
//Set ID of the div
div.id = 'bar' + index
//Configure text properites
div.innerHTML = value;
div.style.color = 'black';
div.style.textAlign = "right";
//Configure bar properties
div.style.background = 'lightblue';
div.style.padding = '2.5px';
div.style.margin = '1px';
div.style.width = (value * 10) + 'px'
return div
}
function CreateBarPlot() {
//Refresh the BAR_DATA
BARS_DATA = []
//Refresh the barplot if one has been already generated
if (document.getElementById("bar_plot") != null) {
document.getElementById("bar_plot").remove()
}
var bar_plot = document.createElement("p");
bar_plot.id = "bar_plot"
numbers = GenerateNumbers()
var i;
for (i = 0; i < numbers.length; i++) {
var cur_bar = CreateBar(i, numbers[i]);
bar_plot.appendChild(cur_bar);
BARS_DATA.push(cur_bar)
}
document.body.append(bar_plot)
}
function bubble_sort(i = 1, switched = false) {
if (i > 1) {
BARS_DATA[i - 1].style.background = 'lightblue';
BARS_DATA[i - 2].style.background = 'lightblue';
}
if (i == BARS_DATA.length && switched == false) {
return true;
} else if (i == BARS_DATA.length && switched == true) {
i = 1;
switched = false;
}
BARS_DATA[i - 1].style.background = 'red';
BARS_DATA[i].style.background = 'red';
setTimeout(function() {
//Highlight the bars that are about to be compared
var left_val = parseInt(BARS_DATA[i - 1].innerHTML);
var right_val = parseInt(BARS_DATA[i].innerHTML);
if (left_val > right_val) {
switched = true;
switch_bars(BARS_DATA[i - 1], BARS_DATA[i])
}
bubble_sort(i + 1, switched)
}, 50);
}
function switch_bars(bar1, bar2) {
bar1_value = bar1.innerHTML
bar1_width = bar1.style.width
bar2_value = bar2.innerHTML
bar2_width = bar2.style.width
//Perform switch
bar1.innerHTML = bar2_value
bar1.style.width = bar2_width
bar2.innerHTML = bar1_value
bar2.style.width = bar1_width
}
</script>
</body>
</html>
</code></pre>
<p>To run it, see the <a href="https://jsfiddle.net/Nelver/qotfmvzh/" rel="nofollow noreferrer">JSFiddle</a></p>
<p><strong>What can be improved?</strong></p>
|
[] |
[
{
"body": "<p>Regarding</p>\n\n<pre><code><body style=\"background: pink\">\n <p id=\"word\" style=\"color: black\">Bubble sort: visualization</p>\n <button onclick=CreateBarPlot()>Generate data</button>\n <button onclick=bubble_sort()>Sort</button>\n</code></pre>\n\n<p>It's not a good idea to use inline event handlers in modern Javascript, because they require global pollution and can have some <a href=\"https://stackoverflow.com/a/59539045\">very strange behavior</a>. Leave the HTML markup to be the <em>actual content</em> of the site - keep the styling and Javascript to their own self-contained sections instead, preferably. To attach event listeners to an element, use <code>addEventListener</code>.</p>\n\n<p>In the Javascript, you have some places where you assign to different <code>.style</code> properties of an element. Consider adding CSS rules instead. Here, the bars are children of the <code>#bar_plot</code>, so all you need is the <code>#bar_plot > div</code> selector - you don't even need to add a class to the elements. Of course, when the property you want is dynamically calculated in the JS, like <code>div.style.width = (value * 10) + 'px'</code>, you need to use JS, but otherwise, better to use CSS rules.</p>\n\n<p>You use <code>div.innerHTML = value;</code>. Unless you're <em>deliberately</em> inserting HTML markup, it's faster, safer, and more predictable if you use the <code>textContent</code> property instead, if you want to put text inside an element. (Even if <em>you're</em> already sure <code>value</code> is plain text, and doesn't contain HTML markup, other readers of the code may not be as sure as you on casual inspection, which may cause worries and double-checks) Same thing for when retrieving element content - unless you need to retrieve HTML markup, use <code>textContent</code>.</p>\n\n<p>You declare a bar element with:</p>\n\n<pre><code>const div = document.createElement(\"div\");\n</code></pre>\n\n<p><code>const</code> is ES2015 syntax. ES2015 syntax is <em>great</em> - it often makes code more readable and concise. I'd highly recommend using it everywhere. If you need compatibility with completely obsolete browsers (like IE), the professional thing to do is to use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile your clean ES2015+ code into ES5 syntax.</p>\n\n<p>But whatever you decide, make sure to have a consistent style. If you really want to write in ES5 for some reason, then best to do so everywhere - otherwise, use ES2015+. (Don't mix <code>var</code> and <code>const</code> / <code>let</code>).</p>\n\n<p>Either way, also make sure to declare your variables before using them - your <code>numbers</code> variable (and <code>bar1_value</code>, and <code>bar1_width</code>, and more) are not declared, which means that when you assign to it, you're implicitly creating a global variable. Or, if you use strict mode (which you should, it turns potential bugs like these into early errors), an error will be thrown.</p>\n\n<p>Elements with IDs automatically become global variables with the name of the ID. This is weird and can cause bugs and confusion. I'd prefer to avoid IDs when possible, or at least minimize their usage to only <em>absolutely unique</em> elements. Dynamic numeric-indexed IDs <em>definitely</em> should be avoided (especially since they aren't being referenced anywhere else anyway).</p>\n\n<p>The overwhelming majority of professional Javascript uses <code>camelCase</code> for nearly all variable names (including functions). <code>PascalCase</code> is generally reserved for classes and constructor functions, which you aren't using here. You can consider whether you want to conform to the de-facto standard.</p>\n\n<p>You're sometimes putting semicolons at the end of statements, and sometimes you aren't. Omitting semicolons can <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">occasionally result in bugs</a>, especially if you're a beginner - even if you know the rules of ASI, it's best to be consistent with a code style. Consider using a linter like ESLint to automatically prompt you to fix these sorts of inconsistencies and potential bugs.</p>\n\n<p><code>BARS_DATA</code> is a confusing name. It's declared as an array, and it sounds like it holds <em>data</em>, which I would intuitively think would be the numeric data points, but it actually holds <em>elements</em>. Maybe call it <code>barElements</code> instead. Or, even better, you can avoid the global array there entirely by selecting the rows from the DOM when needed instead.</p>\n\n<p>With bubble sort, after a full initial iteration through the array, the value at the last index will be completely sorted (the final value there). After the second full iteration, the second-last value will be completely sorted, and so on. You can improve your logic by iterating one less element each time, and perhaps make the logic clearer by giving these completely-sorted elements a style change.</p>\n\n<p>Rather than <code>bubbleSort</code> recursively calling itself with index and <code>changed</code> arguments, I think the logic might be clearer if it only ran <em>once</em> instead, and added delays by <code>await</code>ing a Promise that resolves after a couple seconds.</p>\n\n<p>It's possible to click the <code>sort</code> button more than once, resulting in multiple sorts occurring simultaneously, which doesn't make sense. Perhaps disable the buttons while sorting.</p>\n\n<p>Put it all together, and you get something like:</p>\n\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>'use strict';\n\n// you could also put the whole script into an IIFE to avoid globals\n\nfunction generateNumbers(count = 15) {\n const numbers = [];\n for (let i = 0; i < count; i++) {\n numbers.push(Math.floor(Math.random() * (70 - 1)) + 1);\n }\n return numbers;\n}\n\nfunction createBar(index, value) {\n const div = document.createElement(\"div\");\n div.textContent = value;\n div.style.width = (value * 10) + 'px';\n return div;\n}\n\nfunction createBarPlot() {\n const existingPlot = document.querySelector('.bar-plot');\n if (existingPlot) {\n existingPlot.remove();\n }\n const barPlot = document.body.appendChild(document.createElement(\"p\"));\n barPlot.className = 'bar-plot';\n const numbers = generateNumbers();\n for (let i = 0; i < numbers.length; i++) {\n barPlot.appendChild(createBar(i, numbers[i]));\n }\n}\n\nconst delay = ms => new Promise(resolve => setTimeout(resolve, ms));\nasync function bubbleSort() {\n const barElements = [...document.querySelectorAll('.bar-plot > div')];\n\n // Some helper functions first:\n const getNum = i => Number(barElements[i].textContent);\n const switchBars = (i) => {\n barElements[i].insertAdjacentElement('afterend', barElements[i - 1]);\n // Swap the positions of the bars in the array of elements:\n [barElements[i], barElements[i - 1]] = [barElements[i - 1], barElements[i]];\n };\n\n for (let cyclesToGo = barElements.length - 1; cyclesToGo >= 0; cyclesToGo--) {\n // Add active class to first element:\n barElements[0].classList.add('active');\n for (let i = 1; i <= cyclesToGo; i++) {\n // Add active class to next element:\n barElements[i].classList.add('active');\n if (getNum(i - 1) > getNum(i)) {\n switchBars(i);\n }\n await delay(50);\n // Remove active class from last element:\n barElements[i - 1].classList.remove('active');\n }\n // Cycle complete; last one iterated over is in its final position\n barElements[cyclesToGo].className = 'done';\n }\n generateBtn.disabled = false;\n}\n\nconst buttons = document.querySelectorAll('button');\nconst [generateBtn, sortBtn] = buttons;\nconst setDisabled = newDisabled => {\n for (const button of buttons) {\n button.disabled = newDisabled;\n }\n};\ngenerateBtn.addEventListener('click', () => {\n setDisabled(false);\n createBarPlot();\n});\nsortBtn.addEventListener('click', () => {\n setDisabled(true);\n bubbleSort();\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n background: pink;\n}\n.bar-plot > div {\n color: black;\n text-align: right;\n background: lightblue;\n padding: 2.5px;\n margin: 1px;\n}\n.bar-plot > div.active {\n background: red;\n}\n.bar-plot > div.done {\n background: yellow;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>Bubble sort: visualization</p>\n<button>Generate data</button>\n<button>Sort</button></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-05-08T11:04:03.523",
"Id": "241939",
"ParentId": "241930",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241939",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T08:47:21.543",
"Id": "241930",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"html",
"sorting"
],
"Title": "Bubble sort visualization: JavaScript"
}
|
241930
|
<p>I was given a API project by my co-worker to work on half created a system in slim PHP. The project consists of the Models and controllers. When the route is called it calls the Controller with the necessary function in the Controller, then query data from the database in Model functions and get back the response.</p>
<p>I want to know is this the correct way to implement OOP in PHP API applications? If not what are the changes and components I have to do to make it OOP MVC app?</p>
<p><strong>User Controller -> UserController.php</strong></p>
<pre><code>public function getUser($request, $response, $args)
{
$userId= $request->getAttribute('id');
$user = $this->User->getUserById($userId);
if (!$user) {
return $response->withJSON([
"error" => true,
"message" => "cannot get user info",
"data" => null
]));
}
return $response->withJSON([
"error" => false,
"message" => "cannot get user info"
"data" => $user
]);
}
</code></pre>
<p><strong>User Model -> User.php</strong></p>
<pre><code>public function getUserById($userId)
{
$sql = "SELECT id, name, email
FROM users
WHERE id= :id";
try {
$stmt = $this->db->prepare($sql);
$result = $stmt->execute([
'id' => $userId
]);
if ($result && $stmt->rowCount() == 1) {
return $stmt->fetchAll()[0];
} else {
return false;
}
} catch (\PDOException $e) {
$this->logger->info("cannot get user by id from DB " . $e);
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:07:37.733",
"Id": "474764",
"Score": "3",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:09:55.850",
"Id": "474767",
"Score": "1",
"body": "Welcome to Code Review. Did you test this? Does it produce the correct output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:12:20.950",
"Id": "474769",
"Score": "0",
"body": "Hi I changed the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:12:43.450",
"Id": "474770",
"Score": "0",
"body": "The code works.. I'm concerning about the design"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:21:15.077",
"Id": "474774",
"Score": "0",
"body": "added the functionality in title"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:13:09.323",
"Id": "474782",
"Score": "0",
"body": "The first two lines in `getUser()` don't make much sense. In effect the first line does nothing. Also, the parameter `$args` is never used. Finally, when the user is found the message reads: \"cannot get user info\". This looks like very 'dirty' code, do you really want us to look at that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T12:13:11.783",
"Id": "474793",
"Score": "0",
"body": "$args is never used. there was a type in $user. now it is fixed. So is this not code review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T12:38:33.477",
"Id": "474795",
"Score": "0",
"body": "Well, you said; \"the code works\", before you corrected the bug, so it didn't work then, and your question is somewhat theoretical. Using a model to get data from a database seems correct, but I don't yet see why your controller needs the user information. A controller is for processing user input and getting data into the database by using the model."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:02:47.290",
"Id": "474800",
"Score": "0",
"body": "in Slim, the routes are directly connected to the controller, the data from routes are caught by the controller."
}
] |
[
{
"body": "<p>There is not much OOP to review it. Actually that's just two functions, so one can review only the code, not the object structure. All in all there is a lot of repetitive or outright useless code</p>\n\n<pre><code>public function getUser($request, $response, $args)\n{\n $userId= $request->getAttribute('id');\n $user = $this->User->getUserById($userId);\n return $response->withJSON([\n \"error\" => !$user, \n \"message\" => $user ? \"success\" : \"no such user\"\n \"data\" => $user ?: null\n ]);\n}\n</code></pre>\n\n<p>as you can see, there could be just one return statement</p>\n\n<pre><code>public function getUserById($userId)\n{\n $sql = \"SELECT id, name, email FROM users WHERE id= :id\";\n $stmt = $this->db->prepare($sql);\n $result = $stmt->execute(['id' => $userId]);\n return $stmt->fetch();\n}\n</code></pre>\n\n<p>I took out all the useless code, namely</p>\n\n<ul>\n<li>it is useless to verify $result. In case of error an exception will be thrown</li>\n<li>it is <strong>always</strong> useless to check the rowCount()</li>\n<li>why use fetchAll() if you need only one row?</li>\n<li>it is useless to add any condition because fetch() will return FALSE already if no record found.</li>\n<li>the same goes for the try-catch. There should be a site-wide error handler that will log the error and do something else like show a generic 500 error in the browser</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T15:28:43.367",
"Id": "241946",
"ParentId": "241936",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241946",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T10:00:19.160",
"Id": "241936",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"mvc",
"slim"
],
"Title": "Is this an good OOP Design in MVC PHP for getting User Details?"
}
|
241936
|
<p>I am new to Python. Amateur, enthusiast and learner.<br>
I have developed code which visits one particular website. Crawls through it to reach a certain repository, downloads the records from there to the local disk. It has too many <code>while</code>- and <code>for</code>-loops nested inside one another. It has nested functions too. How can I refactor it to increase speed and readability? Pasting the code here in hope of guidance.</p>
<pre><code>import glob
import datetime
import cv2
import base64
from PIL import Image
from io import BytesIO
import time
import selenium
import self as self
from pytesseract import pytesseract
from selenium.webdriver.common.keys import Keys
import os
from selenium.webdriver.support import expected_conditions as EC, expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException, StaleElementReferenceException, \
WebDriverException, ElementNotInteractableException, UnexpectedAlertPresentException
main_Directory = r'/home/sangharshmanuski/Documents/e_courts/mha/downloads4'
log_Directory = r'/home/sangharshmanuski/Documents/e_courts/mha/log'
driver = selenium.webdriver.Firefox()
url = r'https://districts.ecourts.gov.in/'
driver.get(url)
# create wait time variable for regular, short and mid
wait = WebDriverWait(driver, 180)
waitShort = WebDriverWait(driver, 3)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#sateist > option:nth-child(22)")))
select = Select(driver.find_element_by_css_selector('#sateist'))
options = select.options
select.select_by_visible_text('Maharashtra')
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.region')))
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#sateist')))
districtListDropdown = Select(driver.find_element_by_css_selector("#sateist"))
distOptions = districtListDropdown.options
# iterate over each district
i = 1
while i < len(distOptions):
try:
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#sateist')))
newDistDropDown = Select(driver.find_element_by_css_selector("#sateist"))
except:
continue
newDistOptions = newDistDropDown.options
distName = newDistOptions[i].text
print(distName)
newDistDropDown.select_by_index(i)
# for creating directory as per each district.
district_directory = os.path.join(
main_Directory, distName) # create new
if not os.path.exists(district_directory): # if not directory exists, create one
os.mkdir(district_directory)
district_log_directory = os.path.join(log_Directory, distName)
if not os.path.exists(district_log_directory): # if not directory exists, create one
os.mkdir(district_log_directory)
headingDist = driver.find_element_by_css_selector('.heading')
if headingDist.text.lower() == distName.lower():
wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.accordion2:nth-child(2)'))).click()
current = driver.window_handles[0]
wait.until(EC.element_to_be_clickable(
(By.CSS_SELECTOR,
'div.panel:nth-child(3) > ul:nth-child(1) > li:nth-child(6) > a:nth-child(1)'))).click()
# wait until new tab opens.
wait.until(EC.number_of_windows_to_be(2))
# define new tab by differentiating from current tab.
newWindow = [window for window in driver.window_handles if window != current][0]
# switch to the new tab. ref: https://stackoverflow.com/questions/41571217/python-3-5-selenium-how-to-handle-a-new-window-and-wait-until-it-is-fully-lo
driver.switch_to.window(newWindow)
# wait till court complex list appears.
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#court_complex_code')))
# create list of all court complex.
# 2 approaches - 1 select 2 click.
time.sleep(3)
def complex_and_act():
this = driver.current_window_handle
def imgtotxt():
elem = driver.find_element_by_id("captcha_image")
loc = elem.location
size = elem.size
left = loc['x']
top = loc['y']
width = size['width']
height = size['height']
box = (int(left), int(top), int(left + width), int(top + height))
screenshot = driver.get_screenshot_as_base64()
img = Image.open(BytesIO(base64.b64decode(screenshot)))
area = img.crop(box)
area.save('/home/sangharshmanuski/Documents/e_courts/captcha/file_trial.png', 'PNG')
fullPath = r'/home/sangharshmanuski/Documents/e_courts/captcha'
f = os.listdir(fullPath)
desPath = r"/home/sangharshmanuski/Documents/e_courts/editC"
img = cv2.imread(os.path.join(fullPath, 'file_trial.png'), 0)
ret, thresh1 = cv2.threshold(img, 111, 255, cv2.THRESH_BINARY)
cv2.imwrite('/home/sangharshmanuski/Documents/e_courts/editC/oneDisNoLoop.png', thresh1)
# know the text with pytesseract
captchaText = pytesseract.image_to_string(
Image.open('/home/sangharshmanuski/Documents/e_courts/editC/oneDisNoLoop.png'))
captcha = driver.find_element_by_id('captcha')
captcha.send_keys(captchaText)
driver.find_element_by_css_selector('input.button:nth-child(1)').click()
time.sleep(1)
def proceed():
while True:
try:
waitShort.until(EC.alert_is_present())
driver.switch_to.alert.accept()
driver.switch_to.window(this)
driver.find_element_by_css_selector(
'#captcha_container_2 > div:nth-child('
'1) > div:nth-child(1) > span:nth-child(3) > a:nth-child(7) > img:nth-child(1)').click()
log_file = open(os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('alert was present' + '\n')
print('alert was present')
imgtotxt()
except:
# if the waitmsg is on, wait for 5 sec
log_file = open(os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('no alert' + '\n')
print('no alert')
waitmsg = 0
while driver.find_element_by_css_selector('#waitmsg').is_displayed():
if waitmsg < 7:
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('wait' + '\n')
print('waitmsg')
time.sleep(1)
waitmsg += 1
else:
log_file = open(os.path.join(
log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('waiting finished' + '\n')
print('waiting finished')
break
invalidCaptcha = "Invalid Captcha"
norecord = "Record Not Found"
try:
waitShort.until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#errSpan > p:nth-child(1)')))
incorrect = driver.find_element_by_css_selector('#errSpan > p:nth-child(1)').text
if incorrect == invalidCaptcha:
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('Invalid Captcha' + '\n')
print('invalid captcha')
imgtotxt()
continue
else:
if incorrect == norecord:
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('Record not Found' + '\n')
return print('record not found')
except:
pass
def record():
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('Record Found' + '\n')
print('record fun started')
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.someclass')))
listAllView = driver.find_elements_by_css_selector(
'a.someclass')
# make new dirctory by name of Court Complex
distDir2 = os.path.join(
main_Directory, distName, nameCourtComp)
if not os.path.exists(distDir2):
os.makedirs(distDir2)
x = 0
for view in listAllView:
try:
view.click()
wait.until(EC.presence_of_element_located((By.ID, 'back_top')))
openFile = open(
os.path.join(distDir2, "file_" + str(x) + ".html"), "w")
openFile.write(driver.page_source)
openFile.close()
back = driver.find_element_by_id('back_top')
back.click()
x += 1
except (TimeoutException, ElementNotInteractableException):
driver.refresh()
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write(
'While Downloading record for '
+ nameCourtComp + ' error occured, retrying now...' + '\n')
nonlocal courtComp
courtComp -= 1
return print(
'While Downloading record for '
+ nameCourtComp + ' error occured, retrying now...')
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('record completed, ' + str(x) + ' records found' + '\n')
print('record completed, ' + str(x) + ' records found')
return
record()
return
courtComp = 1
courtComplexDownload = Select(
driver.find_element_by_css_selector('#court_complex_code'))
courtComplexDownloadList = courtComplexDownload.options
courtComplexLen = len(courtComplexDownloadList)
while courtComp < courtComplexLen:
nameCourtComp = courtComplexDownloadList[courtComp].text
log_file = open(os.path.join(log_Directory, nameCourtComp + '.txt'), 'w')
log_file.write(nameCourtComp + '\n' + '\n')
print(nameCourtComp)
courtComplexDownload.select_by_index(courtComp)
acts = Select(driver.find_element_by_css_selector('#actcode'))
actsOpt = acts.options
act = 0
while len(actsOpt) < 2:
if act < 10:
time.sleep(1)
act += 1
else:
#if there is no list to populate break out of this loop & go to next complex
raise Exception()
try:
acts.select_by_value('33')
except NoSuchElementException:
print('PoA not applicable')
log_file = open(
os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')
log_file.write('No PoA' + '\n')
courtComp += 1
continue
imgtotxt()
proceed()
courtComp += 1
complex_and_act()
driver.close()
print("all court complexes in " + distName + " completed")
driver.switch_to.window(current)
driver.back()
else:
time.sleep(5)
continue
i += 1
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#sateist > option:nth-child(22)")))
select = Select(driver.find_element_by_css_selector('#sateist'))
options = select.options
select.select_by_visible_text('Maharashtra')
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.region')))
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#sateist')))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:00:22.277",
"Id": "474855",
"Score": "1",
"body": "Technically, if it becomes faster, that's more than just refactoring. With that said, any task this thorny will probably be accomplished by rotating between refactoring & other tasks it helps you work out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:32:06.797",
"Id": "474926",
"Score": "0",
"body": "@J.G. That's not right. Refactoring can lead to speed increases. Granted that changes specifically aimed at increasing speed will probably involve more than refactoring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:46:37.437",
"Id": "474927",
"Score": "0",
"body": "@JBentley I suppose it comes down to whether you consider speed part of [\"behaviour\"](https://en.wikipedia.org/wiki/Code_refactoring). Personally, I'd prefer refactoring to mean \"primarily focus on non-functional improvements, but with maybe a bit of functional improvement along the way\", not that I'm expecting \"refactoring-oriented programming\" to ever catch on as a paradigm. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T15:05:08.283",
"Id": "474940",
"Score": "0",
"body": "@J.G. Yes I agree, but my point is that changes that don't modify behaviour (i.e. pure refactoring changes) can lead to speed changes. That's because speed is a result of compiler/interpreter output, not a result of behaviour. Compiler output won't necessarily be identical for two pieces of behaviourally equivalent code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T15:07:56.297",
"Id": "474941",
"Score": "0",
"body": "@JBentley Ah, I thought you meant more radical algorithm tweaks that get people to break out big O notation."
}
] |
[
{
"body": "<p>So a few tips:</p>\n\n<p>Generally, functions go at the top level or as object or class methods. But doing that does mean you have to pass more things to the function, and can't rely on the closure (variables defined in the scope above the function). That can also give you a lot of insight into your structure, and highlight complex functions (<em>complex</em> means dealing with a lot of different things) you might want to simplify, so it's a good exercise to move those functions to the top. If you find a lot of functions need the same variable(s), then you might want a class. Or maybe you do decide you want the function nested.</p>\n\n<p>Surprisingly though, I think you have too few functions, not too many. Some may be in the wrong places though. Most of the places you have a comment are also good places to extract a function. Don't be afraid to do that too much. More functions are usually better, and shorter functions that call other functions are great too. In fact, sometimes I extract a single line to a function just to give it a name, instead of using a comment. PyCharm makes it easy to (un)extract and move functions, so you can go hog wild pretty quickly. Anything that you can give a good function name is probably a good function.</p>\n\n<p>Those suggestions lead to a pattern though: <a href=\"https://martinfowler.com/bliki/PageObject.html\" rel=\"nofollow noreferrer\">Page Objects</a>. Basically, you make classes and objects to represent each <em>conceptual</em> element (things like <em>header</em>, <em>logo</em>, <em>article content</em>, <em>login form</em>, etc., not things like <code>div</code>, <code>span</code>, etc.) on the page, then use those objects to as your high level interface. So for example you could use that interface like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>page = Page(url)\n\npage.header.login_form.should_exist\n\npage.main_content.should_contain(\"Welcome!\")\n\nnext_page = page.header.login_form.fill_out_and_submit(name=\"J. Doe\", password=password)\n\nnext_page.main_content.should_contain(\"Welcome J. Doe!\")\n</code></pre>\n\n<p>The general idea is you want most of your code to read like a story. If you can simplify the story by using a function name that clearly describes a few lines, then that is probably a good idea. The details of how selenium works should be hidden from that story.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:45:39.360",
"Id": "241955",
"ParentId": "241940",
"Score": "4"
}
},
{
"body": "<p>You'll have to test all this, but:</p>\n\n<ul>\n<li>Your editor highlighting will guide you. When I pulled out your functions, I found a need to add <code>this</code> and <code>courtComp</code> as <code>arguments</code> to <code>proceed</code> and <code>courtComp</code> to <code>record</code>, but at least I could retire a <code>nonlocal</code>. I also found, going through your code, that some variables can be retired altogether.</li>\n<li>You can define a few more functions to <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> your code, e.g.</li>\n</ul>\n\n<p><code>def ensure_dir(dir):\n if not os.path.exists(dir): os.mkdir(dir)</code></p>\n\n<p>and</p>\n\n<p><code>def wait_():\n select = Select(driver.find_element_by_css_selector('#sateist'))\n select.select_by_visible_text('Maharashtra')\n for s in ['.region', '#sateist']:\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, s)))</code></p>\n\n<p>This also lets you retire some variable declarations.</p>\n\n<ul>\n<li>To flatten (denest) your code further, put the shorter of two if/else options first, then the rest may not need the else. For example, <code>if headingDist.text.lower() == distName.lower():</code> enters lots of code even after we pull out functions defined in it, but is followed by an <code>else:</code> that only enters two lines. The large number in that first block can each be unindented one level if you follow my advice.</li>\n<li>If a block's more than a few lines, it's worth turning that into a function too for further denesting.</li>\n<li>You should probably learn how to make code more Pythonic. For example, instead of saying <code>i=1</code> and doing a while loop ending in <code>i += 1</code>, <a href=\"https://snakify.org/en/lessons/for_loop_range/\" rel=\"nofollow noreferrer\">use a for loop with <code>range</code></a>. (It doesn't make a big difference in a long block, but that's kind of the point: the blocks will quickly become short with the above points.) You might also want to learn about <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>.</li>\n</ul>\n\n<p>None of this advice is intended to make it faster, but better understanding Selenium might.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:37:53.820",
"Id": "241967",
"ParentId": "241940",
"Score": "2"
}
},
{
"body": "<p>I will not offer a complete refactor of your script, it's too much work I'm afraid. But well done, this is not an easy project.</p>\n\n<p>I also agree that you should have more functions. Break up your code in smaller bits, to separate functionality and make it more readable. The flow is not very easy to follow.</p>\n\n<p>I haven't tried all of your code but if I understand the desired functionality you should have a few logical blocks like:</p>\n\n<ul>\n<li>open the main page</li>\n<li>pick a state</li>\n<li>pick a district</li>\n<li>collect some data</li>\n<li>then come back to the home page and repeat the process</li>\n</ul>\n\n<p>When you have a clear operating flow in mind you can start writing dedicated functions for the various tasks you've identified.\nI will give an example that retrieves the list of States/UT.<br />\nNB: tested on Linux with Firefox.<br />\nWarning: I may have changed a few options/imports from your original code.</p>\n\n<pre><code>from typing import List\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\n\n# constants\nurl = r'https://districts.ecourts.gov.in/'\n\noptions = FirefoxOptions()\n#options.add_argument(\"--headless\")\noptions.add_argument(\"--private-window\")\ndriver = webdriver.Firefox(options=options)\n\n# FUNCTIONS\ndef get_states(driver) -> List[str]:\n \"\"\"Get list of States/UT from combo box\n Return a list of strings\n \"\"\"\n\n # define the selector only once\n combo_identifier = '#sateist'\n\n try:\n # wait for combo box to be ready\n print(\"Waiting for combo box (States/UT)...\")\n WebDriverWait(driver=driver, timeout=10).until(EC.presence_of_element_located((By.CSS_SELECTOR, combo_identifier)))\n print(\"Combo box should be ready, continue\")\n except TimeoutException:\n print(\"Timed out/failed to load page\")\n sys.exit()\n\n states_combo = Select(driver.find_element_by_css_selector(combo_identifier))\n\n # return list of non-empty values from combo box\n return [o.get_attribute(\"value\") for o in states_combo.options if o.get_attribute(\"value\") != '']\n\n\n# MAIN CODE\n\n# load the main page\ndriver.get(url)\n\n# Step 1 - get the list of States/UT\nprint(\"List of States/UT:\")\nfor counter, value in enumerate(get_states(driver=driver), start=1):\n print(f'[{counter}] {value}')\n # Step 2: choose a district\n # ....\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nList of States/UT:\nWaiting for combo box (States/UT)...\nCombo box should be ready, continue\n[1] andaman\n[2] ap\n[3] arunachal\n[4] assam\n[5] bihar\n[6] chandigarh-district-court\n[7] chhattisgarh\n[8] dadra\n[9] damandiu\n[10] delhi\n[11] goa\n[12] gujarat\n[13] haryana\n[14] hp\n[15] jk\n[16] jharkhand\n[17] karnataka\n[18] kerala\n[19] lakshadweep\n[20] mp\n[21] maharashtra\n[22] manipur\n[23] meghalaya\n[24] mizoram\n[25] nagaland\n[26] odisha\n[27] puducherry\n[28] punjab\n[29] rajasthan\n[30] sikkim\n[31] tn\n[32] telangana\n[33] tripura\n[34] up\n[35] uttarakhand\n[36] wb\n</pre>\n\n<p>The function <code>get_states</code> returns a list of string, combo values only. If you are interested in the State names as well, then you could return a a list of dictionary pairs.</p>\n\n<p>Now that you have fetched the list you can select one item at a time, for example to choose Goa in the list you do this:</p>\n\n<pre><code>combo_identifier = '#sateist'\nstate_option = Select(driver.find_element_by_css_selector(combo_identifier))\nstate_option.select_by_value('goa')\n</code></pre>\n\n<hr>\n\n<p>Regarding structure/style I would recommend to add some more <strong>line spacing</strong>, and more <strong>comments</strong> to better follow the logic. I bet that the reason why you have so little line spacing is that your code is already so long and takes time to scroll. That's why you need small functions (say, 10-30 lines each) instead of big blocks.</p>\n\n<hr>\n\n<p>Something else that may be useful for you: <strong>logging</strong>. Python has an elaborate <a href=\"https://docs.python.org/3.8/library/logging.html\" rel=\"nofollow noreferrer\">logging module</a>, that you can use instead of writing to text files.</p>\n\n<p>I use it extensively in my applications to write text to the console AND to file. Note that you can write to multiple destinations but with different formats.</p>\n\n<p>You repeat paths and log file names too often eg:</p>\n\n<pre><code>os.path.join(log_Directory, nameCourtComp + '.txt'), 'a')\n</code></pre>\n\n<p>The logging module should help you simplify this. When you harness the power of this module you will get rid of those prints.\nThis is more <em>flexible</em> because you can change the level of detail you want instead of commenting a lot of print statements.</p>\n\n<p>Here is some sample code for demonstration purposes:</p>\n\n<pre><code>import logging\nimport sys\n\nlog_file = '/home/anonymous/test.log'\n\n# logging - source: https://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout\n# Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.\nlogging.getLogger().setLevel(logging.NOTSET)\n\n# Add stdout handler, with level INFO\nconsole = logging.StreamHandler(sys.stdout)\nconsole.setLevel(logging.INFO)\nformater = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', \"%Y-%m-%d %H:%M:%S\")\nconsole.setFormatter(formater)\nlogging.getLogger().addHandler(console)\n\n# Add file handler, with level DEBUG\nhandler = logging.FileHandler(log_file)\nhandler.setLevel(logging.DEBUG)\nformater = logging.Formatter('%(asctime)s\\t%(filename)s\\t%(lineno)s\\t%(name)s\\t%(funcName)s\\t%(levelname)s\\t%(message)s', \"%Y-%m-%d %H:%M:%S\")\nhandler.setFormatter(formater)\nlogging.getLogger().addHandler(handler)\n\nlogger = logging.getLogger(__name__)\n\n# this line will appear on console and in the log file\nlogger.info(\"Application started\")\n\n# this line will only appear in the log file because level = debug\nlogger.debug(\"Log some gory details here\")\n</code></pre>\n\n<hr>\n\n<p>Once again, well done. But if think your code is too long. Maintenance and debugging is not going to be easy. You really need to break it up in a number of steps and call them in a logical order that is easy to follow.</p>\n\n<p>The site will change at some point and you will have to review your code sooner or later. If you split the code in functions and add a lot of traces it will be easier to figure out (function name, line number) where the problem occurs.</p>\n\n<p>Something that you could/should do is put all the functions in a <strong>separate module</strong> file, then import it as a module from your main code. This will <strong>declutter</strong> your application <em>a lot</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:59:00.110",
"Id": "241980",
"ParentId": "241940",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T11:42:27.273",
"Id": "241940",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"selenium"
],
"Title": "Crawl a website and download records"
}
|
241940
|
<p>I am implementing a few Celery background tasks (e.g sending an email, subscribing someone to an Audience via Mailchimp API, etc.) and my project relies on a Flask application factory.
Now, I am trying to understand if the way I've used application contexts makes sense at all or if it can be improved (I've quite a few resources lying around presenting very different approaches).<br>
Here's my <code>__init__.py</code> </p>
<pre class="lang-py prettyprint-override"><code>from flask import Flask
from .config import Config
form celery import Celery
# [...] A bunch of external components
celery = Celery(__name__)
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
celery.conf.update(app.config)
# Instantiate external components
# Blueprint registration
return app
</code></pre>
<p>Now, the tasks that get executed in my blueprints are declared in the way presented below (in a <code>~/app/tasks.py</code> file). As you can see, an application context gets created each time a task gets executed. This is the point where I am struggling: does it make sense to instantiate a Flask app each time a task needs to be executed or should I find a way to create a new 'global' app context?</p>
<pre class="lang-py prettyprint-override"><code>from flask import current_app
from . import create_app, celery, mailchimp
@celery.task()
def newsletter_subscribe(user):
"""
Subscribe a new user to a newsletter via Mailchimp API
"""
app = create_app() # Create a new Flask app instance
with app.app_context():
mailchimp.lists.members.create(
list_id=current_app.config['MAILCHIMP_LISTS'][user["frequency"]],
data={
'email_address': user['email'],
'status': 'subscribed'
}
)
# ... some more tasks following the same structure
</code></pre>
<p>Celery gets its worker thanks to the following command in my <code>docker-compose</code> file:</p>
<pre class="lang-yaml prettyprint-override"><code> celery:
build:
context: .
dockerfile: 'Dockerfile.dev'
command: celery worker -B -A app.tasks -l info
env_file:
- '.env'
volumes:
- '.:/app'
</code></pre>
<p>Everything seems to work just fine but I am wondering if there's any pitfall in the way I am using app contexts or any margin for improvement.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T13:37:51.257",
"Id": "241944",
"Score": "1",
"Tags": [
"python",
"flask"
],
"Title": "Celery tasks and Flask application factory"
}
|
241944
|
<p>I've created something that I called System, where you can login, create the files and delete the files.</p>
<p>It's not any kind of big project, but it's the biggest project I made in PHP OOP so far. It uses MySQL PDO database connection. Passwords are not hashed since there's no registration page. The thing I'm not sure about is that I know what is and how to use abstract classes, final classes etc. but I don't see opportunity or need to use it in the current script. I can barely imagine a situation where something like abstract class would be useful, so if you can, tell me where could I use some of this more advanced object-oriented stuff so it'll be useful.</p>
<p>All the files: <a href="https://github.com/quono/oopsystem" rel="nofollow noreferrer">https://github.com/quono/oopsystem</a></p>
<p>There's also an .sql file with ready-to-import database with a few examples.</p>
<p>It asks me to add some code here, so I put here all 3 main pages, includes are available on github.</p>
<p><strong>index.php</strong></p>
<pre><code><?php
session_start();
require 'includes/InputValidator.class.php';
require 'includes/Client.class.php';
require 'includes/User.class.php';
require 'includes/db.php';
$client = new Client();
if ($client->isLogged()) $client->redirect('system.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$nick = htmlspecialchars($_POST['nick']);
$pass = $_POST['pass'];
$inputValidator = new InputValidator($nick);
if ($inputValidator->length(3, 20)) {
$inputValidator = new InputValidator($pass);
if ($inputValidator->length(8)) {
$user = new User($pdo);
if ($user->login($nick, $pass)) {
$client->setAsLogged($user->getId($nick), $nick);
$client->redirect('system.php');
}
}
}
if (!isset($err)) $err = 'Nickname or password incorrect';
}
?>
<?php require 'layout/header.html' ?>
<h1>Sign in</h1>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<p>Login: <input type="text" name="nick"></p>
<p>Password: <input type="password" name="pass"></p>
<input type="submit" value="Submit">
</form>
<?php if (isset($err)) echo '<p>' . $err . '</p>';
require 'layout/footer.html';
?>
</code></pre>
<p><strong>system.php</strong></p>
<pre><code><?php
session_start();
require 'includes/Client.class.php';
require 'includes/User.class.php';
require 'includes/Files.class.php';
$client = new Client();
if (!$client->isLogged()) if ($client->isLogged()) $client->redirect('index.php');
if (isset($_GET['logout'])) {
$client->logout();
$client->redirect('index.php');
}
require 'includes/db.php';
$files = new Files($pdo, $_SESSION['userid']);
if (!isset($_SESSION['filesData'])) $_SESSION['filesData'] = $files->fetch();
$htmlFileContent = '';
if (isset($_GET['open'])) {
if (in_array($_GET['open'], array_column($_SESSION['filesData'], 'id'))) {
$file = $_SESSION['filesData'][array_search($_GET['open'], array_column($_SESSION['filesData'], 'id'))];
$htmlFileContent .= '<hr>';
$htmlFileContent .= '<p><b>' . $file['name'] . '.txt</b></p>';
$htmlFileContent .= nl2br($file['text']);
} else {
$htmlFileContent = 'File doesn\'t exist on your system';
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delId'])) {
if (in_array($_POST['delId'], array_column($_SESSION['filesData'], 'id'))) {
$files->remove($_POST['delId']);
$_SESSION['filesData'] = null;
$_SESSION['message'] = 'File has been removed successfully';
$client->redirect($_SERVER['PHP_SELF']);
}
}
$htmlFiles = '';
foreach($_SESSION['filesData'] as $file) {
$htmlFiles .= '<form action method="post">';
$htmlFiles .= '<p><span style="margin-right:15px;"><input type="submit" name="delete" value="Remove"></span>';
$htmlFiles .= '<a href="?' . 'open=' . $file['id'] . '">' . $file['name'] . '.txt</a></p>';
$htmlFiles .= '<input type="hidden" name="delId" value="' . $file['id'] . '">';
$htmlFiles .= '</form>';
}
if (empty($htmlFiles)) $htmlFiles = '<i>You don\'t have any files yet</i>';
?>
<?php require 'layout/header.html' ?>
<h1>System - manage your files</h1>
<?php
echo 'Logged as: ' . $_SESSION['nick'];
if (isset($_SESSION['message'])) {
echo '<p>' . $_SESSION['message'] . '</p>';
$_SESSION['message'] = null;
}
?>
<p>
<a href="add.php">Add new file</a>
</p>
My files:
<br>
<?=$htmlFiles?>
<p>
<a href="?logout">Log out</a>
</p>
<?=$htmlFileContent?>
<?php require 'layout/footer.html'; ?>
</code></pre>
<p><strong>add.php</strong></p>
<pre><code><?php
session_start();
require 'includes/InputValidator.class.php';
require 'includes/Files.class.php';
require 'includes/Client.class.php';
require 'includes/User.class.php';
$client = new Client();
if (!$client->isLogged()) $client->redirect('index.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = htmlspecialchars($_POST['name']);
$content = htmlspecialchars($_POST['content']);
$inputValidator = new InputValidator($name);
if ($inputValidator->length(1, 50)) {
$inputValidator = new InputValidator($content);
if ($inputValidator->length(0, 10000)) {
require 'includes/db.php';
$files = new Files($pdo, $_SESSION['userid']);
$files->add($name, $content);
if (!isset($err)) {
$_SESSION['message'] = 'File has been added successfully';
$_SESSION['filesData'] = null;
$client->redirect('system.php');
}
} else {
$err = 'Your file size is too big';
}
} else {
$err = 'File name length is not correct';
}
}
?>
<?php require 'layout/header.html'; ?>
<h1>Add new file</h1>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<p>Name:<br><input type="text" name="name" maxlength="50"></p>
<p>Content:<br><textarea cols="60" rows="15" name="content"></textarea></p>
<p><input type="submit" value="Save"></p>
<a href="system.php">Cancel</a>
</form>
<?php if (isset($err)) echo '<p>' . $err . '</p>'; ?>
<?php require 'layout/footer.html'; ?>
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Well, let me tell you the truth: this is not OOP at all. This is a very common approach called \"ole good procedural disguised as OOP\". Your code is essentially procedural. Class methods here are used as functions. You can rewrite them as functions and your code will be the same. </p>\n\n<p>And even such a makeshift OOP is inconsistent. </p>\n\n<ul>\n<li>for example, <code>new Files($pdo, $_SESSION['userid']);</code> - why instead of using <code>$client</code> a direct access to the session variable?</li>\n<li><p>or, I would make the whole authentication into a method of the Client class, and call this method, like</p>\n\n<pre><code>if ($_SERVER['REQUEST_METHOD'] === 'POST') {\n $client = new Client();\n $client->authenticate($pdo, $_POST['nick'], $_POST['pass']);\n $err = 'Nickname or password incorrect';\n}\n</code></pre></li>\n<li><p>the same goes for the logout code</p></li>\n</ul>\n\n<p>To be honest, in your place I would rather try to learn how to make a more organized procedural code. For example instead of such \"accordion\" as in your add.php why not to make it more level</p>\n\n<pre><code>$err = [];\n$inputValidator = new InputValidator($name);\nif (!$inputValidator->length(1, 50)) {\n $err[] = 'File name length is not correct';\n}\n$inputValidator = new InputValidator($content);\nif (!$inputValidator->length(0, 10000)) {\n $err[] = 'Your file size is too big';\n}\nif (!$err) {\n require 'includes/db.php';\n $files = new Files($pdo, $_SESSION['userid']);\n $files->add($name, $content);\n $_SESSION['message'] = 'File has been added successfully';\n $_SESSION['filesData'] = null;\n $client->redirect('system.php');\n}\n</code></pre>\n\n<p>And you also need learn the basic PHP syntax. For example, why <code>$stmt->fetchAll()[0]['id'];</code> when there is <code>fetch()</code>, or even <code>fetchColumn()</code> intended exactly for this purpose? Both <code>fetchAll()</code> and <code>fetch()</code> would raise an error when there is no such user found, where <code>fetchColumn()</code> will just return FALSE.</p>\n\n<p>Oh - and you really, really should learn basic SQL as well. </p>\n\n<pre><code> $stmt->bindValue(':id', rand(10000001,99999999) . rand(10000001,99999999));\n</code></pre>\n\n<p>is <strong>abaslutely not</strong> how it works. You've got to make the id field <code>auto_increment PRIMARY KEY</code> in the table, and it will be assigned automatically and without the risk of collisions.</p>\n\n<p>Your idea on using exceptions is also wrong. As well as on the variable scope. To catch every exception on the spot is not how exceptions are intended to work. Least there is any point in assigning the error message to a variable that will be discarded the next instant. In PHP, a variable inside a function is only alive a long as the function is executed and when the function is finished your $err variable gets in to the void. And therefore it makes no sense to check <code>if (!isset($err))</code> - it is never set. In general, you should leave error and exceptions alone, and handle them in a single place with a dedicated code, instead of littering your application code with thousands of catch blocks. Here is an article I wrote on <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting</a>. </p>\n\n<p>Don't be discouraged though. OOP is a hard tack by itself, but tenfold when compared to obscene simplicity of traditional PHP. OOP is not a syntax. It's a mindset. No wonder you don't know what an abstract class is for, simply because you don't know yet <em>what a regular class is for</em> either. It takes time to realize.</p>\n\n<blockquote>\n <p>To me, OOP is an approach that improves the <em>manageability</em> of the code at the cost of adding extra <em>complexity</em>. Which means that as long as your procedural code is manageable, you won't see any benefit from OOP, yet your code will become unnecessarily more complex.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T09:44:35.503",
"Id": "474914",
"Score": "0",
"body": "Thanks for your answer. I would gladly modify my code, but I don't think it'd make any sense if that is not OOP at all. I don't know how I could make it more OOP, I followed tutorials, other people codes and that's what I Iearnt. I'm going to read your article about error handling. But the thing I need is to see a perfect code of a small project, similar to mine, where OOP was used well... You say that I use class methods as functions, it's true, how are they supposed to be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T09:53:01.467",
"Id": "474915",
"Score": "0",
"body": "For example, there are private methods that perform a lot of inner workings hidden from the outside world. Or there is an inheritance that cannot be used in such a small project. But really, like I said, OOP is not as primitive and intuitive as traditional PHP. You cannot expect learning OOP by reading a few comments, can you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T10:11:23.933",
"Id": "474916",
"Score": "0",
"body": "I can't build a good code without studying other codes either :) I know what private methods do, but I haven't used them because my methods are small enough (they do stuff like only add, remove etc.). I would use them if I had a bigger method, like authenticate() that you used. Is this how it should look like? One big method doing one big task using a few small private methods? And could you recommend me some place where I can study codes and sharpen my OOP skills in making a project? Some day, I will post on StackExchange a fully object-oriented code that'll be pleasant to read..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:46:20.150",
"Id": "474922",
"Score": "0",
"body": "I am sure you will! Instead of links, I would suggest some books. Martin Fowler's, Bob Martin's, Matt Zandstra's. But before that, you should really get more experience with PHP at whole, to face the problems these books are dealing with"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:57:02.503",
"Id": "474923",
"Score": "0",
"body": "Thanks, I will consider buying one of those in the future!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T08:23:07.060",
"Id": "241987",
"ParentId": "241947",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241987",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T15:30:39.223",
"Id": "241947",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "PHP OOP - Login & DB adding/removing script"
}
|
241947
|
<p>Here is the code for balance retrieval from EMPLOYEES record. Please simplify and improve it accordingly. It is working fine and I have no problem with it but I believe that's not the correct way to do it.</p>
<pre><code>Public Sub GET_BALANCE_VALUE(EMPLOYEE_ID As Integer, EMPLOYEE_NAME As String, ByRef BALANCE As Integer)
Dim con As New MySqlConnection("server=localhost; user=root; password=Masoom1; database=airtech_db; convert zero datetime=true;")
Dim dt As New DataTable
Dim da As New MySqlDataAdapter
Dim sql As String
Dim DR As MySqlDataReader
Dim DB_BAL_RETRIVAL As Integer
Dim cmd As New MySqlCommand
'TO GET PREVIOUS BALANCE
SQL_CMD_TXT = "SELECT * FROM `employees`" & " WHERE `NAME`= '" &
UCase(EMPLOYEE_NAME) & "' AND `EMPLOYEE_ID`= '" &
EMPLOYEE_ID & "';"
Try
con.Open()
sql = SQL_CMD_TXT
cmd = New MySqlCommand(sql, con)
DR = cmd.ExecuteReader
Do While DR.Read = True
DB_REC_VALUE = DR("NAME").ToString()
DB_ID_VALUE = DR("EMPLOYEE_ID")
DB_BAL_RETRIVAL = DR("BALANCE")
Loop
End If
con.Close()
Catch ex As MySqlException
Dim mbe = MessageBox.Show(ex.Message, "SALARY_HISTORY_MOD Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'RETURNING BALANCE VALUE
BALANCE = DB_BAL_RETRIVAL
End Sub<span class="math-container">`</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T15:45:10.447",
"Id": "474815",
"Score": "0",
"body": "I don't see much of complication in that code that could be simplified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:01:34.343",
"Id": "474817",
"Score": "2",
"body": "There is an \"end if\" statement but I don't see the if? And you are looping but expect only one record and you use only one of the values? Do I understand correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:04:12.820",
"Id": "474818",
"Score": "0",
"body": "Well, You don't really need to retrieve `DB_REC_VALUE` and `DB_ID_VALUE`. As what I understand from your code there should be exactly one record returned from the query, so you could just omit the loop and just check if there's exactly one row as result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:40:37.267",
"Id": "474823",
"Score": "0",
"body": "YES hafner you get it right thats whats i was thinking too so"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T05:47:24.513",
"Id": "474886",
"Score": "0",
"body": "`[that's what I] was thinking too` [Are you an author or maintainer of this code](https://codereview.stackexchange.com/help/on-topic), in a position to place it [under Creative Commons](https://codereview.stackexchange.com/help/licensing)?"
}
] |
[
{
"body": "<p>You could change to ExecuteScalar function if you only expect one record. The difference between your code and mine would be in case there are more than one records you take the last record and this code takes the first record.<br>\nI also removed the \"end if\" statement as I don't know what it was for.<br>\nMind that I also changed the select statement to only return the balance as you are not using the name and employee id: </p>\n\n<pre><code>Public Sub GET_BALANCE_VALUE(EMPLOYEE_ID As Integer, EMPLOYEE_NAME As String, ByRef BALANCE As Integer)\n Dim con As New MySqlConnection(\"server=localhost; user=rrrr; password=dddd; database=airtech_db; convert zero datetime=true;\")\n Dim dt As New DataTable\n Dim da As New MySqlDataAdapter\n Dim sql As String\n Dim DR As MySqlDataReader\n Dim DB_BAL_RETRIVAL As Integer\n Dim cmd As New MySqlCommand\n\n'TO GET PREVIOUS BALANCE - only selects column BALANCE.\nSQL_CMD_TXT = \"SELECT BALANCE FROM `employees`\" & \" WHERE `NAME`= '\" &\nUCase(EMPLOYEE_NAME) & \"' AND `EMPLOYEE_ID`= '\" &\nEMPLOYEE_ID & \"';\"\nTry\n con.Open()\n sql = SQL_CMD_TXT\n cmd = New MySqlCommand(sql, con)\n DB_BAL_RETRIVAL = (integer)cmd.ExecuteScalar() ' returns null if nothing found\n con.Close()\nCatch ex As MySqlException\n Dim mbe = MessageBox.Show(ex.Message, \"SALARY_HISTORY_MOD Error\", MessageBoxButtons.OK, MessageBoxIcon.Error)\nEnd Try\n\n'RETURNING BALANCE VALUE\nBALANCE = DB_BAL_RETRIVAL\nEnd Sub`\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:03:01.490",
"Id": "241951",
"ParentId": "241948",
"Score": "1"
}
},
{
"body": "<p>There are at least two things that can be done:</p>\n\n<ul>\n<li>prettify the code</li>\n<li>use <strong>parameterized queries</strong>: this is important from a security point of view but also for functional reasons (escaping values that contain single quotes and will break your SQL)</li>\n</ul>\n\n<p>I don't know how your DB is structured but in a properly designed DB the employee ID should be a unique (incremented ?) identifier and sufficient in itself. <code>Name</code> is a reserved keyword in many languages and it is generally discouraged. But that shouldn't cause problems here since it's enclosed within backticks.</p>\n\n<p>Here is some proposed code that returns the balance as integer value. I don't really think you are interested in the other variables since you already know them. But you could return a datarow if you want to fetch several values in one pass.</p>\n\n<hr>\n\n<pre><code>Public Class frmDemo\n\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\n Dim balance As Integer\n balance = GetBalanceValue(EmployeeID:=2, EmployeeName:=\"Jonas\")\n MessageBox.Show(\"Balance: \" & balance.ToString)\n\n End Sub\n\n Public Function GetBalanceValue(ByVal EmployeeID As Integer, ByVal EmployeeName As String) As Integer\n Dim balance As Integer\n Dim sql As String = \"SELECT BALANCE FROM `employees`\" & _\n \" WHERE `NAME`= @employee_name\" & _\n \" AND `EMPLOYEE_ID`= @employee_id\"\n\n Try\n Using con As New MySqlConnection(\"connection string goes here\")\n con.Open()\n If con.State = ConnectionState.Open Then ' connection successful, continue\n\n Using cmd As MySqlCommand = New MySqlCommand(sql, con)\n With cmd\n .Parameters.Add(\"@employee_id\", DbType.Int32).Value = EmployeeID\n .Parameters.Add(\"@employee_name\", DbType.String).Value = UCase(EmployeeName)\n\n ' retrieve the first value found\n balance = Convert.ToInt32(.ExecuteScalar())\n Return balance\n End With\n End Using\n\n Else\n MessageBox.Show(\"Connection failure\", \"Failed\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)\n Return Nothing\n End If\n\n End Using\n\n Catch ex As Exception\n MsgBox(ex.ToString)\n End Try\n\n End Function\n\nEnd Class\n</code></pre>\n\n<hr>\n\n<p>So the idea here is to use a function to retrieve the balance for a given employee. The error handling is a bit crap - this is for demonstration purposes.</p>\n\n<ul>\n<li>I tested the code with a SQLite DB but the proposed code should be ok or almost ok for you</li>\n<li>You will notice the use of the <strong>Using</strong> statement. If you are working with files, database connections or other kinds of unmanaged resources you will often use it. Intro: <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/using-statement\" rel=\"nofollow noreferrer\">Using Statement (Visual Basic).</a></li>\n<li>I am using <code>ExecuteScalar</code> to retrieve one single field from the first row found (normally there should be only one row per employee). Warning: this will cause an error if no row is found. If you anticipate this situation you have to adapt the logic a bit. An alternative approach is to load the results to a datatable and check that you have at least one datarow.</li>\n<li>Since you are using <strong>Mysql</strong>, perhaps you will have to remove the <code>@</code> in front of the parameter names, for some databases (Oracle) the norm is to use a colon instead. If the parameterized queries don't work immediately for you don't despair but investigate. The sooner you adopt best practices the better.</li>\n<li>consistency: your table name is lower case and field names are uppercase. Use lower case everywhere </li>\n<li>you can use the underscore character (<code>_</code>) to separate keywords in object names eg <code>employeee_id</code></li>\n<li>avoid generic/<strong>reserved keywords</strong>, they can cause problems that are not always obvious and sometimes hard to debug</li>\n<li>exception handling: normally you will handle Mysql exceptions only in this block, for all other exceptions you should have a module-level handler</li>\n</ul>\n\n<p>Suggestion: the next time you post public code, remove the password and other sensitive information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:57:48.870",
"Id": "474838",
"Score": "0",
"body": "Great answer. But wouldn't you have to change the query from returning * to returning the balance in the select?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T18:08:50.547",
"Id": "474841",
"Score": "0",
"body": "Yes you are correct. Will fix this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:25:51.117",
"Id": "241953",
"ParentId": "241948",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241953",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T15:31:56.583",
"Id": "241948",
"Score": "-4",
"Tags": [
"vb.net",
"windows"
],
"Title": "Returning employee balances"
}
|
241948
|
<p>I am having a small piece of code in my project. There are too many if condition. How can I rewrite it better to make it more readable, remove any redundancy etc and cleaner way? I am using Java 8.</p>
<pre><code>private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (user.getAccount() != null) {
PrimecastAccount account = primecastAccountRepository.findOneBySystem(user.getAccount())
.orElseThrow(PrimecastAccountNotFoundException::new);
if(account.getAccountType().equals(AccountType.INTERNAL)) {
if ( !account.getStatus().equals(AccountStatus.ACTIVE)) {
throw new DisabledException("User " + lowercaseLogin + " account not ACTIVE");
}
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
} else {
if ( !account.getStatus().equals(AccountStatus.DISABLED)) {
throw new DisabledException("User " + lowercaseLogin + " account not ACTIVE");
}
}
} else {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:36:23.297",
"Id": "474821",
"Score": "1",
"body": "Welcome to CodeReview! Please add a description of what your code does and also change the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:40:03.000",
"Id": "474822",
"Score": "0",
"body": "done i have changed . let me know it makes sense"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:45:11.433",
"Id": "474825",
"Score": "1",
"body": "Unfortunately, not really. The title should tell the people who read it, what your code does. What problem does it solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:18:23.420",
"Id": "474826",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>Welcome to Code Review and thanks for sharing your code.</p>\n\n<p>The usual approach is that you identify parts of your code that do (exactly) the same and transform the code so that the duplicated lines can be merged.</p>\n\n<p>In your case you have three lines duplicated:</p>\n\n<pre><code>if (!user.getActivated()) {\n throw new UserNotActivatedException(\"User \" + lowercaseLogin + \" was not activated\");\n }\n</code></pre>\n\n<p>The main problem is, that one of the occurrences is inside an <code>if</code> block. But if you take a closer look at this nested occurrence you can see, that it does not depend on the condition checked with the <code>if</code>. Therefore it is safe to move this three lines up before the <code>if</code> and delete the other occurrence. This also makes the <code>else</code> block completely obsolete.</p>\n\n<hr>\n\n<p>What I don't like in this code is that your method mixes concepts. The upper part is <em>procedural programming</em> while the lower part is <em>functional programming</em>.\nWithin a method you should stick to one concept only.\nThe usual approach to this is to put the different parts in separate methods called from the original method:</p>\n\n<pre><code>private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {\n checkUserData(lowercaseLogin,user);\n List<GrantedAuthority> grantedAuthorities =\n convertAuthoritiesOf(user);\n return new org.springframework.security.core.userdetails.User(user.getLogin(),\n user.getPassword(),\n grantedAuthorities);\n}\n\ncheckUserData(String lowercaseLogin, User user) {\n if (user.getAccount() != null) {\n // ...\n }\n}\n\nconvertAuthoritiesOf(User user){\n return user.getAuthorities().stream()\n .map(SimpleGrantedAuthority::new)\n .collect(Collectors.toList());\n}\n</code></pre>\n\n<p>another way would be to convert one part to the same concept as the other:</p>\n\n<pre><code>private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {\n\n Stream.of(user)\n .filter(User::getActivated)\n .findFirst()\n .orElseThrow(()->new UserNotActivatedException(\"User \" + lowercaseLogin + \" was not activated\"));\n\n PrimecastAccount account = Stream.of(user)\n .map(u->primecastAccountRepository.findOneBySystem(user.getAccount()))\n .findFirst()\n .orElseThrow(PrimecastAccountNotFoundException::new);\n\n Stream.of(account)\n .filter(AccountType.INTERNAL.equals(PrimecastAccount::getAccountType))\n .filter(PrimecastAccount::getActivated)\n .orElseThrow(()->new UserNotActivatedException(\"User \" + lowercaseLogin + \" was not activated\"));\n\n Stream.of(account)\n .filter(Predicate.not(AccountType.DISABLED.equals(PrimecastAccount::getAccountType)))\n .orElseThrow(()->new UserNotActivatedException(\"User \" + lowercaseLogin + \" was not activated\"));\n\n List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()\n .map(SimpleGrantedAuthority::new)\n .collect(Collectors.toList());\n return new org.springframework.security.core.userdetails.User(user.getLogin(),\n user.getPassword(),\n grantedAuthorities);\n}\n</code></pre>\n\n<p><strong>Attenion</strong>: your code has logical errors which I did not fix.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:40:19.057",
"Id": "241968",
"ParentId": "241949",
"Score": "2"
}
},
{
"body": "<p>The validation part that throws could be placed in its own method - maybe.</p>\n\n<p><code>AccountType</code> and <code>AccountStatus</code> seems enums, or might be due to implement as enums. Then <code>==</code> / <code>!=</code> can be used.</p>\n\n<p><em>Donnot-Repeat-Yourself</em> and introducing variables makes for a more compact notation.</p>\n\n<pre><code>PrimecastAccount account = null;\nif (user.getAccount() != null) {\n account = primecastAccountRepository.findOneBySystem(user.getAccount())\n .orElseThrow(PrimecastAccountNotFoundException::new);\n}\nif (!user.getActivated()) {\n throw new UserNotActivatedException(\"User \" + lowercaseLogin + \" was not activated\");\n}\nif (account != null) {\n AccountType type = account.getAccountType();\n AccountStatus status = account.getStatus();\n if (type == AccountType.INTERNAL && status != AccountStatus.ACTIVE)\n || (type != AccountType.INTERNAL && status != AccountStatus.DISABLED) {\n throw new DisabledException(\"User \" + lowercaseLogin + \" account not ACTIVE\");\n }\n}\n</code></pre>\n\n<p>This focuses on giving only different exceptions. For the same behavior unfortunately you would still do something to only call <code>findOneBySystem</code> once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T22:56:23.880",
"Id": "241974",
"ParentId": "241949",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241968",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:32:43.237",
"Id": "241949",
"Score": "-1",
"Tags": [
"java"
],
"Title": "How can i write my code snippet in a cleaner way so that it is easy to read and least possible lines?"
}
|
241949
|
<p>New to python.
I am converting multiple html files to csv. Developed a full code. It can easily convert 50+ files at a time but after 200+ files, the code takes too much time and with 1000s to convert, it seems that I should look for some other solution all together. Hope to receive some suggestion to speed up the process. (Attached source code of one of the html files for reference at the end.)</p>
<pre><code>import os
from bs4 import BeautifulSoup as bs
import pandas as pd
import glob
import datetime
root_dir = r'/home/some/path'
all_list = []
for newFile in glob.glob(os.path.join(root_dir, '**/*.html'), recursive=True):
dictionary = {}
# create soup.
openFile = open(newFile)
soup = bs(openFile, 'html.parser')
# section 1: Case Details
try:
caseType = soup.find('span', {'class': 'case_details_table'})
caseTypeChild = caseType.findChild()
# ref for .next - https://stackoverflow.com/questions/5999407/extract-content-within-a-tag-with-beautifulsoup
sessionsCase = caseTypeChild.next.next.next
filing = sessionsCase.next.next
filingNumberHeading = filing.find('label')
filingNumber = filingNumberHeading.next.next
filingDate = filingNumber.next.next.next.next
registration = filingDate.next.next
registrationNumberHeading = registration.find('label')
registrationNumber = registrationNumberHeading.next.next.next
cnrHeading = soup.find('b').find('label')
cnrNumber = cnrHeading.next.next
dictionary['Filing Number'] = filingNumber
dictionary['Filing Date'] = filingDate
dictionary['Registration Number'] = registrationNumber
dictionary['CNR Number'] = cnrNumber
except:
pass
# section 2: Case Status
try:
firstHearing = soup.find('strong')
firstHearingDate = firstHearing.next_sibling.text
dictionary['First Hearing'] = firstHearingDate
nextHearing = soup.find('strong', text='Next Hearing Date')
nextHearingDate = nextHearing.next_sibling.text
dictionary['Next Hearing'] = nextHearingDate
stageOfCase = soup.find('strong', text='Stage of Case')
stageOfCaseText = stageOfCase.next_sibling.text
dictionary['Stage of Case'] = stageOfCaseText
courtNumber = soup.find('strong', text='Court Number and Judge')
courtNumberText = courtNumber.next_sibling.next_sibling.text.strip()
dictionary['Court Number and Judge'] = courtNumberText
except:
pass
# section 6: FIR Details
try:
policeStationHeading = soup.find('span', attrs={'class': 'FIR_details_table'}).next.next
policeStation = policeStationHeading.next.next.next.next
firnumberHeading = policeStation.next.next.next
firNumber = policeStation.find_next('label').next
firYearHeading = firNumber.next.next.next
firYear = firNumber.find_next('span').find_next('label').next
# same as previous sections.
dictionary[policeStationHeading] = policeStation
dictionary[firnumberHeading] = firNumber
dictionary[firYearHeading] = firYear
except:
pass
# section 3: Petioner and Advocate
try:
petitioner = soup.find('span', attrs={'class': 'Petitioner_Advocate_table'})
petitionerName = petitioner.next
dictionary['Name of the Petitioner'] = petitionerName
petitionerAdvocate = petitionerName.next.next
dictionary['Name of the Advocate'] = petitionerAdvocate
# section 4: Respondent and Advocate
respondent = petitionerAdvocate.find_next('span')
respondentName = respondent.next
dictionary['Name of the Respondent'] = respondentName
except:
pass
# section 5: Acts
'''In this section 1. soup is prepared from act_table tab of web page
2. Keys for main dictionary are created defining headings of acts. with 'not applied' values.
3. short form variables are created for names of the act.
4. list of acts is compared with list of variables and sections are replaced as values in the dictionary. '''
acts = soup.select('#act_table td:nth-of-type(1)')
sections = soup.select('#act_table td:nth-of-type(2)')
dictionary['IPC'] = 'Not Applied'
dictionary['PoA'] = 'Not Applied'
dictionary['PCSO'] = 'Not Applied'
dictionary['PCR'] = 'Not Applied'
dictionary['Any Other Act'] = 'Not Applied'
ipc = 'indian penal code'
poa = 'prevention of atrocities'
pcso = 'protection of children from sexual'
pcr = 'protection of civil rights'
try:
act1 = tuple(acts[0].contents)
sections1 = tuple(sections[0].contents)
string = str(act1)
except:
pass
try:
act2 = tuple(acts[1].contents)
sections2 = tuple(sections[1].contents)
except:
pass
try:
act3 = tuple(acts[2].contents)
sections3 = tuple(sections[2].contents)
except:
pass
try:
act4 = tuple(acts[3].contents)
sections4 = tuple(sections[3].contents)
except:
pass
# using if and not for loop then actSession is not needed
# for first act in list
if len(acts) < 2:
if ipc in string.lower():
dictionary['IPC'] = sections1
elif poa in string.lower():
dictionary['PoA'] = sections1
elif pcso in string.lower():
dictionary['PCSO'] = sections1
elif pcr in string.lower():
dictionary['PCR'] = sections1
else:
pass
# for 2nd act in list
elif len(acts) == 2:
if ipc in string.lower():
dictionary['IPC'] = sections1
elif poa in string.lower():
dictionary['PoA'] = sections1
elif pcso in string.lower():
dictionary['PCSO'] = sections1
else:
pass
if ipc in str(act2).lower():
dictionary['IPC'] = sections2
elif poa in str(act2).lower():
dictionary['PoA'] = sections2
elif pcso in str(act2).lower():
dictionary['PCSO'] = sections2
else:
pass
# for 3rd act in list
elif len(acts) == 3:
if ipc in string.lower():
dictionary['IPC'] = sections1
elif poa in string.lower():
dictionary['PoA'] = sections1
elif pcso in string.lower():
dictionary['PCSO'] = sections1
elif pcr in string.lower():
dictionary['PCR'] = sections1
else:
pass
if ipc in str(act2).lower():
dictionary['IPC'] = sections2
elif poa in str(act2).lower():
dictionary['PoA'] = sections2
elif pcso in str(act2).lower():
dictionary['PCSO'] = sections2
elif pcr in str(act2).lower():
dictionary['PCR'] = sections2
else:
pass
else:
pass
all_list.append(dictionary)
df = pd.DataFrame(all_list)
df = df[['CNR Number', 'Filing Number', 'Filing Date', 'First Hearing', 'Next Hearing', 'Stage of Case', 'Registration Number', 'Year', 'FIR Number', 'Police Station', 'Court Number and Judge', 'PoA', 'IPC', 'PCR', 'PCSO', 'Any Other Act', 'Name of the Petitioner', 'Name of the Advocate', 'Name of the Respondent']]
outputFile = open(os.path.join('/home/some out put path' + 'all records' + str(
datetime.datetime.now().day) + '_' + str(datetime.datetime.now().month) + str(
datetime.datetime.now().year) + '.csv'), 'w')
df.to_csv(outputFile)
outputFile.close()
</code></pre>
<p>Find the sample html file here:
<a href="https://github.com/sangharshbyss/EcourtsData/blob/master/samplePage.html" rel="nofollow noreferrer">this source code of one of the files I am using to convert</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:30:18.520",
"Id": "474856",
"Score": "0",
"body": "I would help to know what the HTML looked like. Also, have you tried using `pandas.read_html()` to load convert the HTML tables to DataFrames?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:20:15.187",
"Id": "474920",
"Score": "0",
"body": "@RootTwo. Thanks. 1. html source code is attached. 2. pandas read () can'nt help as all the data is not stored in tables. Its very unstructured page."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T16:58:00.780",
"Id": "241950",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"html",
"csv",
"pandas"
],
"Title": "Converting multiple HTML files to csv lowers down the speed"
}
|
241950
|
<p>we have homework in Java to do some users, contracts, and some API. We should create a user with some information about him and one of that information should be address (one where he live and one where post should come) But I am not sure if I did it correctly.</p>
<p>I create a package called user inside which i created User.class</p>
<pre><code>package xxx;
import java.util.List;
public abstract class User {
private int ID;
private String firstName;
private String lastName;
private int idNumber;
private String email;
private String officialAddress;
private String postAddress;
private List contracts;
public User(String firstName, String lastName, int idNumber, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.idNumber = idNumber;
this.email = email;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
</code></pre>
<p>and OfficialAddress.class</p>
<pre><code>package xxx;
public class OfficialAddress extends User {
private int zipcode;
private String region;
private String streetName;
private int streetNumber;
public OfficialAddress(String firstName, String lastName, int idNumber, String email) {
super(firstName, lastName, idNumber, email);
}
}
</code></pre>
<p>I just want to ask if is good practice to do it like this or if it should be different. We just cant use nested classes and static methods. Thanks for review.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T22:41:50.990",
"Id": "474962",
"Score": "6",
"body": "Your title is weak. Rewrite to summarize your specific technical issue."
}
] |
[
{
"body": "<p>Welcome to Code Review and thanks for sharing your code.</p>\n\n<p>Your class <code>OfficialAddress</code> <em>extends</em> your class <code>User</code>. This does not look right.</p>\n\n<p>By <em>extending</em> a class you declare an <em>is a</em> relationship. But an <em>address</em> never <em>is a</em> user.</p>\n\n<p>instead a user <em>has a</em> Address. In OOP this is expressed by giving the owner (class <code>User</code>) a <em>property</em> of the other class (<code>OfficialAddress</code>):</p>\n\n<pre><code>public class OfficialAddress { // no extending here\n // ...\n}\n\npublic class User{\n private OfficialAddress officialAddress;\n // ...\n public User(String firstName, String lastName, int idNumber, String email, OfficialAddress, officialAddress) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.idNumber = idNumber;\n this.email = email;\n this.officialAddress = officialAddress;\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:19:15.603",
"Id": "474890",
"Score": "0",
"body": "Thank you very much it helps me a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T03:26:32.990",
"Id": "474971",
"Score": "0",
"body": "@JurajJakubov There is a name for this guideline: *Prefer composition over inheritance.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T08:01:15.240",
"Id": "474983",
"Score": "5",
"body": "@chrylis-onstrike- while this guideline exists it is not applicable here because inheritance is the completely wrong approach here, not even an option. *PCoI* is about providing *common behavior* while the classes in Questioners example do not have anything in common."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:52:20.733",
"Id": "241965",
"ParentId": "241956",
"Score": "18"
}
},
{
"body": "<p>A few remarks:</p>\n\n<ul>\n<li>you have an <code>ID</code> and <code>idNumber</code>;</li>\n<li>the constructor of <code>User</code> doesn't initialize a lot of fields, better make them <code>Optional<String></code> or <code>Optional<Address></code> if they are;</li>\n<li><code>contracts</code> is a <code>List</code> without <em>type parameter</em> (e.g. <code>List<Contact></code> or <code>List<User></code> would be logical type parameters;</li>\n<li>white space and indentation are a bit funky (sometimes no empty lines, sometimes up to three, what's up with that?).</li>\n</ul>\n\n<p>I'm not sure that <code>contacts</code> is something that is <em>inherent to</em> or <em>part of</em> a user. So I might want to create that <em>relationship</em> using e.g. a table rather than making it a field of a user.</p>\n\n<p>I agree with Timothy, an official address is clearly a \"has a\" relationship. However, is an official address of another type as a <code>PostAddress</code>? I'd at least make <code>Address</code> an interface or abstract class. Or it could a full blown class if there are no real differences between the two kind of addresses.</p>\n\n<p>When assigning an address within the constructor you may want to make the address <em>immutable</em> or otherwise make a copy. Otherwise you are not correctly implementing data encapsulation. The caller can change the given address and the user class will change with it. Same goes for any <code>getOfficialAddress</code> getter: either use an immutable <code>officalAddress</code> or perform a copy / clone.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:21:36.130",
"Id": "474891",
"Score": "0",
"body": "I never thought about details like whitespaces. Thank you for your effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T07:55:07.307",
"Id": "474902",
"Score": "0",
"body": "@JurajJakubov most IDEs provide an *auto formatter* feature (in eclipe you apply it with `<ctrl><shift><f>`), just use that as often as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T10:14:05.610",
"Id": "474917",
"Score": "4",
"body": "\"better make them Optional<String> or Optional<Address> if they are\" and then your IDE complains that you have `Optional` fields. No. Don't make them optional in the field, make their accessor (getter) return an optional and `return Optional.ofNullable(field)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T10:23:10.407",
"Id": "474919",
"Score": "0",
"body": "If you must. If I remember it is just a problem with serialization. As long as `null` is not returned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T14:51:14.940",
"Id": "474938",
"Score": "1",
"body": "@JurajJakubov the formating function can also be set to be applied automatically and once you work in a team with a version control software formating does get important as you want to avoid code changes just because of spacing changes that make it hard to track the actually important changes in your version control history."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T23:57:01.007",
"Id": "241975",
"ParentId": "241956",
"Score": "3"
}
},
{
"body": "<p>When designing a class never ignore what you're making the construction and using code look like.</p>\n\n<pre><code>User user = new User(\n 123,\n new FullName(\"Homer\", \"Jay\", \"Simpson\"),\n new Email(\"chunkylover53@aol.com\"),\n new Address(\"742\", \"Evergreen Terrace\", \"??\", \"?????\"),\n new Contacts(124, 125, 126, 127)\n);\n\nuser.sendBill(overdueNotice);\nuser.sendEmail(promotion42);\n</code></pre>\n\n<p>This uses composition, not inheritance, which, without a good reason otherwise, is generally preferred.</p>\n\n<p>Done this way the class can be fully immutable since no setters have been used. This means it can be shared across threads without fear of using it while it's partially updated. </p>\n\n<p>Breaking the class into smaller classes avoids long lists of unreadable constructor parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:21:55.033",
"Id": "241993",
"ParentId": "241956",
"Score": "5"
}
},
{
"body": "<p>In User, you define a user's name as:</p>\n\n<pre><code>private String firstName;\nprivate String lastName;\n</code></pre>\n\n<p>This is something that is very common, and very wrong. I am one of those oddballs that use a first initial, a middle name, and a last name. This is not uncommon in the US, and in my case is a family tradition -- we start using our middle name when we become adults, and so it feels like somebody is calling me a child when they insist on using our first name. And no, I will not put my middle name into a slot that asks for a first name.</p>\n\n<p>It can get even stranger even in the US. We had \"The Artist Formerly Known As Prince\" (look it up if you don't remember) -- he changed his name to an unpronounceable symbol.</p>\n\n<p>Then there was \"Moon Unit Zappa\" (Moon Unit was her first name).</p>\n\n<p>Then there are names from countries/cultures outside the US.</p>\n\n<p>And, just to make it even nastier, names are <em>not</em> unique! Even with a single \"name\" field, I doubt there are more than a handful of unique names in the US (Ms. Zappa may be one of those unique names, I certainly hope so.)</p>\n\n<p>Please check out this link: <a href=\"https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/\" rel=\"noreferrer\">Falsehoods Programmers Believe About Names</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T19:24:03.037",
"Id": "475004",
"Score": "1",
"body": "Considering this is a homework question, I think the onus is on the specification. Not on the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T19:30:24.443",
"Id": "475006",
"Score": "0",
"body": "He asked in Code Review, I told him what I thought would improve his code. And yes, this is probably due to a poor specification, and maybe this will get back to them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T17:22:51.857",
"Id": "242012",
"ParentId": "241956",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241965",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T17:53:59.393",
"Id": "241956",
"Score": "3",
"Tags": [
"java",
"object-oriented"
],
"Title": "Java OOP principes"
}
|
241956
|
<p>I'm working in swift and I've got a custom class <code>Array2D</code> to handle fixed-width, two-dimensional arrays of integers. What I'm trying to do is write a simple, ideally-elegant function <code>max() -> Int?</code> to behave the same way as for a 1-D array: return <code>nil</code> if the array is empty, or else the maximum value in the array. I make no promises about the array contents being positive.</p>
<p>For the sake of simplicity, I'm writing these functions as freestanding rather than parts of a class here.</p>
<p>Broadly speaking, I'm trying to do this:</p>
<pre><code>func max(array: [[Int]]) -> Int? {
set up a variable for maximum value maxSoFar
for row in array {
if row.max() > maxSoFar { maxSoFar = row.max() }
}
return maxSoFar
}
</code></pre>
<p>What I'm struggling with is avoiding lots of nested optional handling: I have to handle the <code>Int?</code> returned by <code>max</code> for each row of the array, and it looks like I'll need <code>maxSoFar</code> to be an <code>Int?</code> as well, since I don't want to initialize it to zero since all the entries in the array could be negative.</p>
<p>So, a few options:</p>
<pre><code>func max1(array: [[Int]]) -> Int? {
if array.count == 0 || array[0].count == 0 { return nil }
var maxval: Int = array[0][0]
for row in array {
if let rowmax = row.max() {
if rowmax > maxval { maxval = rowmax }
}
}
return maxval
}
</code></pre>
<pre><code>func max2(array: [[Int]]) -> Int? {
var maxval: Int?
for row in array {
guard let rowmax = row.max() else {
return nil
}
guard let temp = maxval else {
maxval = rowmax
continue
}
if rowmax > temp {
maxval = rowmax
}
}
return maxval
</code></pre>
<p>Thoughts? Alternatives? I'd be delighted to learn a better way to handle this.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:26:04.057",
"Id": "474852",
"Score": "0",
"body": "Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T22:44:50.190",
"Id": "474869",
"Score": "0",
"body": "Thanks! Pleasure to be here."
}
] |
[
{
"body": "<p>Your first method does not work correctly if the first row is empty:</p>\n\n<pre><code>print(max1(array: [[], [1, 2], [-3]])) // nil\n</code></pre>\n\n<p>This is difficult to salvage while avoiding an optional for the current <code>maxval</code>.</p>\n\n<p>Your second method returns <code>nil</code> if any row is empty:</p>\n\n<pre><code>print(max2(array: [[1, 2], [], [3, 4]])) // nil\n</code></pre>\n\n<p><code>guard</code> is a useful language feature to avoid the “optional pyramid of doom,” or to “early exit” in exceptional cases. But in your <code>max2()</code> function it makes the program flow difficult to understand (and introduced an error, as we saw above). With plain old <code>if-let-else</code> it would look like this:</p>\n\n<pre><code>func max2(array: [[Int]]) -> Int? {\n var maxval: Int?\n for row in array {\n if let rowmax = row.max() {\n if let temp = maxval {\n if rowmax > temp { maxval = rowmax }\n } else {\n maxval = rowmax\n }\n }\n }\n return maxval\n}\n</code></pre>\n\n<p>But actually the (explicit) handling of all the special cases of an empty array or empty rows can be avoided completely!</p>\n\n<p>The <a href=\"https://developer.apple.com/documentation/swift/sequence/2431985-joined\" rel=\"nofollow noreferrer\"><code>Sequence.joined()</code></a> can be applied to the nested array, it returns a (lazily evaluated) sequence of all concatenated rows.</p>\n\n<p>This simplifies the implementation to</p>\n\n<pre><code>func max2D(array: [[Int]]) -> Int? {\n return array.joined().max()\n}\n</code></pre>\n\n<p>Or more generic, for nested arrays of <em>comparable</em> elements:</p>\n\n<pre><code>func max2D<T>(array: [[T]]) -> T? where T: Comparable {\n return array.joined().max()\n}\n</code></pre>\n\n<p>You may also consider if it is worth defining a function for that purpose, if you also can call</p>\n\n<pre><code>let myMax = my2DArray.joined.max()\n</code></pre>\n\n<p>directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T22:44:31.633",
"Id": "474868",
"Score": "0",
"body": "Thank you so much! I guess I didn't make it clear that elsewhere in this class I enforce the fixed-width 2D array requirement, thus the \"single empty row\" errors. Your answers are substantially nicer than my original thoughts, so I really appreciate your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T18:57:39.960",
"Id": "241961",
"ParentId": "241960",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241961",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T18:41:55.250",
"Id": "241960",
"Score": "3",
"Tags": [
"array",
"swift",
"optional"
],
"Title": "Unwrapping optionals for max of a 2D array in swift"
}
|
241960
|
<p>I am trying to build a 12-column CSS grid system very similar to Bootstrap. 4 breakpoints are supported: <code>normal, sm, md, and lg</code>. Anyway, here is the code:</p>
<pre><code>.row {
position: relative;
width: 100%;
}
.row [class^="col-"] {
float: left;
}
.row::after {
content: "";
display: table;
clear: both;
}
[class^="col-"] {
width: 100%;
}
.col-1 {
width: 8.33333333%;
}
.col-2 {
width: 16.66666667%;
}
.col-3 {
width: 25%;
}
.col-4 {
width: 33.33333333%;
}
.col-5 {
width: 41.66666667%;
}
.col-6 {
width: 50%;
}
.col-7 {
width: 58.33333333%;
}
.col-8 {
width: 66.66666667%;
}
.col-9 {
width: 75%;
}
.col-10 {
width: 83.33333333%;
}
.col-11 {
width: 91.66666667%;
}
.col-12 {
width: 100%;
}
@media (min-width: 577px) {
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-12 {
width: 100%;
}
}
@media (min-width: 769px) {
.col-md-1 {
width: 8.33333333%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-3 {
width: 25%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-6 {
width: 50%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-9 {
width: 75%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-12 {
width: 100%;
}
}
@media (min-width: 993px) {
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-12 {
width: 100%;
}
}
</code></pre>
<p>Would really appreciate a review of this code. So far, I have no problems in my testing. It is also meant to support IE11.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:54:35.513",
"Id": "474877",
"Score": "0",
"body": "Is there a reason you are not using flexbox or css grid?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T09:43:18.933",
"Id": "474913",
"Score": "0",
"body": "@gview Yes, I wanted to support IE11, and flex-box has some weird bugs that randomly popup on that browser."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T07:10:36.197",
"Id": "474981",
"Score": "0",
"body": "Are you using plain CSS or generating this code dynamically using some preprocessor language like SCSS?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T01:28:50.613",
"Id": "475016",
"Score": "0",
"body": "@MohammadUsman Plain old CSS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T18:41:33.027",
"Id": "475215",
"Score": "0",
"body": "https://learncssgrid.com"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T19:08:30.003",
"Id": "485198",
"Score": "0",
"body": "Honestly, I've seen much worse. There may be some constructs available to make this even cleaner, but it's fairly straight-forward."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:35:53.850",
"Id": "241963",
"Score": "5",
"Tags": [
"html",
"css"
],
"Title": "12-column CSS grid system similar to Bootstrap"
}
|
241963
|
<p>I am creating a c++ library implementing Java Functional Programming alike interface. In short, the code will look like this:</p>
<pre><code>vector<string> buffer = ... ; // A buffer contains some strings
new IntStream(0, 100).map([](int a){
return (a * 0x2344DDEF) & 0xF;
}).map([=](int a) {
return buffer[a];
}).foreach([](string a) {
cout << a << '\n';
});
</code></pre>
<p>Now I want to support parallel evaluation. For the example above, I want to get 100 execution tasks and send them to a thread pool. To do this, I have created EvalOp classes. The stream returns a list of EvalOp objects. They will only perform the actual computation when you invoke <code>EvalOp::eval</code></p>
<pre><code>template <typename T>
class EvalOp {
public:
virtual T eval() = 0;
};
template <typename FROM, typename TO>
class TransformOp : public EvalOp<TO> {
public:
TO eval() override {
return mapper_(previous_->eval());
}
protected:
unique_ptr<EvalOp<FROM>> previous_;
function<TO(FROM&)> mapper_;
};
template <typename T>
class Stream {
public:
virtual bool isEmpty() = 0;
virtual EvalOp<T> next() = 0;
Stream<N> map(function<N(T)> mapper) {
return new MapStream<N,T>(this, mapper);
}
}
template <typename FROM, typename TO>
class MapStream : public Stream<TO> {
protected:
Stream<FROM>* previous_;
function<TO(FROM)> mapper_;
public:
EvalOp<TO> next() override {
return new TransformOp<FROM, TO>(previous_->next(), mapper_);
}
}
</code></pre>
<p>My stream will now return a bunch of EvalOp objects, which you can throw in a thread pool.</p>
<p>This code gets me the correct result. But as it creates many wrapper classes (the EvalOps), the execution is slower. I did a benchmark of the following two tasks:</p>
<pre><code>uint32_t __attribute__ ((noinline)) hash1(uint32_t input) {
return input * 0x12345768;
}
uint32_t __attribute__ ((noinline)) hash2(uint32_t input) {
return ((input * 0x2FDF1234) << 12) * 0x23429459;
}
uint32_t sum = 0;
void summer(uint32_t input) {
sum += input;
}
BENCHMARK(StreamBenchmark, Serial)(State& state) {
for(auto _:state) {
for(int i = 0 ; i < 10000; ++i)
sum += hash2(hash1(i));
}
}
}
BENCHMARK(StreamBenchmark, Wrapper)(State& state) {
for(auto _:state) {
IntStream stream(0, 10000);
stream.map(hash1).map(hash2).foreach(summer);
}
}
</code></pre>
<p>From the benchmark result, I see for each element, only 1ns is spent on actual computation and 40ns overhead is spent on the Stream and EvalOp. I am looking for some suggestions to make a more efficient design. Thank you very much! </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:41:30.297",
"Id": "474857",
"Score": "0",
"body": "I want to know how you do timings with 1ns resolution? I need that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:44:28.647",
"Id": "474859",
"Score": "0",
"body": "I use google benchmark to run the benchmark and it reports the Serial method consumes ~14000ns CPU time."
}
] |
[
{
"body": "<p>I think this question may be off-topic, as it does not consist of complete working code to be reviewed. I spent (too long) trying to get it to compile, and got as far as this: <a href=\"https://godbolt.org/z/qCE9S8\" rel=\"nofollow noreferrer\">https://godbolt.org/z/qCE9S8</a></p>\n\n<p>But you have a lot of problems with the current design. Most notably, you're using raw <code>new</code> all over the place, which creates pointers to the heap; but you aren't actually using the correct syntax to refer to those pointers. For example:</p>\n\n<pre><code>Stream<N> map(function<N(T)> mapper) {\n return new MapStream<N,T>(this, mapper);\n}\n</code></pre>\n\n<p>Here <code>new MapStream<...>()</code> yields a value of type <code>MapStream<N,T>*</code>, but you're trying to return it as if it were a <code>Stream<N></code> object. This flatly will not compile.</p>\n\n<p>You could consider changing this return type to <code>std::unique_ptr<Stream<N>></code> (and using <code>make_unique</code>), but that still won't really work for your use-case, because then you'll have to change this line:</p>\n\n<pre><code>stream.map(hash1).map(hash2).foreach(summer);\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>stream.map(hash1)->map(hash2)->foreach(summer);\n</code></pre>\n\n<p>because now <code>map</code> returns a pointer. And worse, there's no way for the <code>MapStream</code> object itself to transfer its own ownership into the <code>previous_</code> member of the next <code>MapStream</code> object in the chain. You end up with a bunch of temporary <code>unique_ptr</code>s, all linked together by raw pointers which will dangle as soon as the current full-expression finishes. That's okay for your benchmark, but it won't work at all in practice.</p>\n\n<p>You might consider looking at a <a href=\"https://www.youtube.com/watch?v=tbUCHifyT24\" rel=\"nofollow noreferrer\">type erasure</a> design, so that you could keep using <code>Stream<int></code> as a value type (not a polymorphic base class, no visible pointers) but give it behavior that appeared polymorphic at run time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T08:05:58.310",
"Id": "474903",
"Score": "0",
"body": "Thank you very much for your suggestion! You are right that this is not a complete working code but rather to show the concept. The problem you pointed out (not using unique pointers and returning pointers when requiring an object) are fixed in my working code. And I am looking at the type erasure design you mentioned, having a feeling this may be the way to solve my problem. I will accept your answer if it indeed is."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:24:43.627",
"Id": "241983",
"ParentId": "241964",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:41:15.693",
"Id": "241964",
"Score": "2",
"Tags": [
"c++",
"functional-programming",
"lazy"
],
"Title": "Efficient Implementation of functional and Lazy evaluation in C++"
}
|
241964
|
<p>I came across in a code base <code># TODO this seems very clumsy to duplicate the loop code like this?</code> so I figured I'd give it a shot as a learning exercise. I'd like some feedback on what I came up with, particularly:</p>
<ol>
<li>Is this proper idiomatic Julia, or close? Or am I just writing Python in Julia?</li>
<li>What explains the difference in allocations between the two approaches?<br>
(Arguments used: <code>[1,1], octaves=10</code>)
<ul>
<li><code>Old: 0.000013 seconds (63 allocations: 1.062 KiB)</code></li>
<li><code>New: 0.000008 seconds (41 allocations: 1.500 KiB)</code> </li>
</ul></li>
</ol>
<p>Thanks!</p>
<p>Original function:</p>
<pre><code># coords is [x] or [x, y] or [x, y, z] or [x, y, z, w]
function _octaves(coords::Array{T, 1} where T <: Real;
octaves::Int = 1,
persistence=1.0)
total = 0.0
frequency = 1.0
amplitude = 1.0
maxval = 0.0
# TODO this seems very clumsy to duplicate the loop code like this?
l = length(coords)
if l == 1
for i in 1:octaves
total += simplexnoise(coords[1] * frequency) * amplitude
maxval += amplitude
amplitude *= persistence
frequency *= 2
end
elseif l == 2
for i in 1:octaves
total += simplexnoise(coords[1] * frequency, coords[2] * frequency) * amplitude
maxval += amplitude
amplitude *= persistence
frequency *= 2
end
elseif l == 3
for i in 1:octaves
total += simplexnoise(coords[1] * frequency, coords[2] * frequency, coords[3] * frequency) * amplitude
maxval += amplitude
amplitude *= persistence
frequency *= 2
end
elseif l == 4
for i in 1:octaves
total += simplexnoise(coords[1] * frequency, coords[2] * frequency, coords[3] * frequency, coords[4] * frequency) * amplitude
maxval += amplitude
amplitude *= persistence
frequency *= 2
end
end
return total / maxval
end
</code></pre>
<p>And my refactor:</p>
<pre><code>function _octaves(coords::Array{T, 1} where T <: Real;
octaves::Int = 1,
persistence=1.0)
total = 0.0
frequency = 1.0
amplitude = 1.0
maxval = 0.0
for _ in 1:octaves
inputs = coords .* frequency
total += simplexnoise(inputs...) * amplitude
maxval += amplitude
amplitude *= persistence
frequency *= 2
end
return total / maxval
end
</code></pre>
|
[] |
[
{
"body": "<p>This is very idomatic, in principle. The loop refactoring is exactly what I would have done.</p>\n\n<p>Here's some other suggestions:</p>\n\n<pre><code>const Coords{T} = NTuple{N, T} where N\n\nfunction _octaves(coords::Coords{T}; octaves::Int=1, persistence::T=one(T)) where {T<:Real}\n if octaves < 1\n # prevent zero division\n throw(DomainError(octaves, \"`octaves` must be at least 1!\"))\n end\n\n total = zero(T)\n maxval = zero(T)\n\n for octave in 1:octaves\n p = octave - 1\n frequency = 2 ^ p\n amplitude = persistence ^ p\n\n maxval += amplitude\n\n scaled_coords = coords .* frequency\n total += simplexnoise(scaled_coords...) * amplitude\n end\n\n return total / maxval\nend\n</code></pre>\n\n<ol>\n<li>Using <code>one</code> and <code>zero</code> to ensure <strong>type stability</strong> (a very important concept, which you should read about if you don't know it!)</li>\n<li>Replacing some intermediate updates by explicit powers. The calculation of <code>frequency</code> is trivial to the compiler, since it is an integer power of 2. <code>amplitude</code> might do some unnecessary work; I think it is clearer that way, and not worth the microoptimisation, but you'd have to test that for your use case.</li>\n</ol>\n\n<p>The choice of type for <code>coords</code> is really determined by the rest of the code. If this is only ever going to be used for coordinates of bounded dimension, I'd very much prefer a tuple as I wrote above. If you use vectors all the way down (this looks a bit like signal processing?), then staying with <code>Coords{T} = Vector{T}</code> is easier.</p>\n\n<p>While not part of the question, it might be nicer to have <code>simplenoise</code> work on an iterable, not a varargs argument. Possibly even as <code>simplenoise(frequency, coords)</code>, then the allocation of <code>scaled_coords</code> is removed.</p>\n\n<p>If there's any chance that the summation will overflow, take a look at <a href=\"https://docs.julialang.org/en/v1/base/base/#Base.widen\" rel=\"nofollow noreferrer\"><code>Base.widen</code></a>. Also, you might want to ensure that <code>octaves < 8 * sizeof(Int)</code> or something like that, and add this to the check at the beginning.</p>\n\n<p>If this is really the hot part of some code to be optimized, with <code>octaves</code> being constant over many calls, there's the possibility to write a <code>@generated</code> function to unroll the loop completely, but unless it is critical, it's not worth it.</p>\n\n<hr>\n\n<p>As for the difference in benchmarking: first, you should do that with <a href=\"https://github.com/JuliaCI/BenchmarkTools.jl\" rel=\"nofollow noreferrer\">BenchmarkTools.jl</a>, not <code>@time</code>. Then, I haven't measured myself, but it's quite surely due to the intermediate <code>inputs</code> array you construct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T18:41:34.657",
"Id": "476947",
"Score": "0",
"body": "This is great, thank you! Looks like I have some reading lined up for tonight, I really appreciate you taking the time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T07:59:41.763",
"Id": "242993",
"ParentId": "241969",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242993",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T21:06:03.570",
"Id": "241969",
"Score": "2",
"Tags": [
"memory-optimization",
"julia"
],
"Title": "Restructuring loop logic and its effect on allocations"
}
|
241969
|
<p>In the past I have made programs that have generate a buddhabrot with mostly success however all of them were on the CPU and single threaded. As a result they were all slow so I wanted to remake the program but this time I wanted it to be fast and I decided to make it in CUDA. However I had never made a program in CUDA before so this is my first program made in CUDA and my main concern is performance.</p>
<pre><code>#include "png++/png.hpp"
#include <algorithm>
#include <chrono>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#include <fstream>
#include <thrust/complex.h>
typedef float float_; /*useful for testing float vs double*/
typedef unsigned int heatmap;
const int width = 500, height = 500;
const unsigned long long samples = 1000;
const unsigned long long sampleSamples = 10000;
/*map function*/
template <typename T>
__device__ constexpr T map(T x, T in_min, T in_max, T out_min, T out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
__device__ bool good(thrust::complex<float_> c) {
// test H1 and H2
float_ c2 = norm(c);
thrust::complex<float_> d = c + thrust::complex<float_>(1.0, 0.0);
float_ h1 = 256.0 * c2 * c2 - 96.0 * c2 + 32.0 * c.real() - 3.0;
float_ h2 = 16.0 * (norm(d)) - 1.0;
if (h1 > 0.0 && h2 > 0.0)
return false;
return true;
};
/*mandelbrot set function*/
__device__ void mSet(thrust::complex<float_> c, thrust::complex<float_>* Set,
int* iterations, int maxIterations) {
/*if point is the main cardioid it will not escape*/
if (good(c)) {
*iterations = 0;
return;
}
auto z = thrust::complex<float_>(0, 0);
*iterations = 0;
while (norm(z) <= 5 && *iterations < maxIterations) {
z = z * z + c;
/*keep track of the orbit of z*/
Set[*iterations] = z;
++(*iterations);
}
/*if iterations is 0(the point did not escape) discard the information*/
if (*iterations == maxIterations)
*iterations = 0;
}
__global__ void generateSamples(thrust::complex<float_>* Set, int* iterations,
int maxIterations, thrust::complex<float_> minr,
thrust::complex<float_> mini) {
/*create a random number generator for both the real values and imaginary
* values*/
curandStateMRG32k3a_t realRand, imagRand;
unsigned long long index = blockIdx.x * blockDim.x + threadIdx.x;
unsigned long long stride = blockDim.x * gridDim.x;
static unsigned long long seed = 0;
for (; index < samples; index += stride) {
// seed a random number generator
seed += index;
curand_init(seed, 0, 0, &realRand);
curand_init(curand(&realRand), 0, 0, &imagRand);
thrust::complex<float_> c(
map<float_t>(curand_uniform(&realRand), 0, 1, minr.real(), minr.imag()),
map<float_t>(curand_uniform(&imagRand), 0, 1, mini.real(),
mini.imag()));
/*generate points*/
mSet(c, Set + index * (unsigned long long)maxIterations, iterations + index,
maxIterations);
}
}
__global__ void addToHeatmap(heatmap* buffer, thrust::complex<float_>* Set,
int* iterations, int* maxIterations,
heatmap* maxValues, thrust::complex<float_> minr,
thrust::complex<float_> mini) {
unsigned long long index = blockIdx.x * blockDim.x + threadIdx.x;
unsigned long long stride = blockDim.x * gridDim.x;
for (; index < samples * maxIterations[3]; index += stride) {
int currentIteration = (index % maxIterations[3]);
if (currentIteration >= iterations[index / maxIterations[3]]) {
continue;
}
float_ real = Set[index].real(), imag = Set[index].imag();
if (real < minr.real() || real > minr.imag() || imag < mini.real() ||
imag > mini.imag())
continue; // if point is out of bounds continue
int row = map<float_>(real, minr.real(), minr.imag(), 0, (float_)width - 1);
int col =
map<float_>(imag, mini.real(), mini.imag(), 0, (float_)height - 1);
int pixelIndex = row * width + col;
/*red*/
if (currentIteration < maxIterations[0]) {
buffer[pixelIndex]++;
if (buffer[pixelIndex] > maxValues[0]) {
maxValues[0] = buffer[pixelIndex];
}
}
/*green*/
if (currentIteration < maxIterations[1]) {
buffer[pixelIndex + width * height]++;
if (buffer[pixelIndex + width * height] > maxValues[1]) {
maxValues[1] = buffer[pixelIndex + width * height];
}
}
/*blue*/
if (currentIteration < maxIterations[2]) {
buffer[pixelIndex + width * height * 2]++;
if (buffer[pixelIndex + width * height * 2] > maxValues[2]) {
maxValues[2] = buffer[pixelIndex + width * height * 2];
}
}
}
}
int getColor(heatmap value, heatmap maxValue) {
double scl = ((double)value) / ((double)maxValue);
scl = scl > 1 ? 1 : scl; // clamp scl
return round(scl * 255.0);
}
int main() {
/*mapping*/
thrust::complex<float_> minr = thrust::complex<float_>(-2.0, .828);
thrust::complex<float_> mini = thrust::complex<float_>(-1.414, 1.414);
auto t1 = std::chrono::high_resolution_clock::now();
int* iter;
cudaMallocManaged(&iter, sizeof(int) * 4);
/*red, green, and blue*/
iter[0] = 800, iter[1] = 500, iter[2] = 50;
/*find the highest max iteration*/
iter[3] = std::max({ iter[0], iter[1], iter[2] });
/*allocate memory for heatmap buffer*/
heatmap* buffer;
/*allocate memory for storing the highest values in the buffer*/
heatmap* maxValues;
cudaMallocManaged(&buffer, sizeof(heatmap) * width * height * 3);
cudaMallocManaged(&maxValues, sizeof(heatmap) * 3);
/*allocate memory for storing the orbits of points that escape*/
thrust::complex<float_>* Set;
/*allocate memory for stroring the number of iterations a point takes to
* escape*/
int* iterations;
cudaMallocManaged(&Set, sizeof(thrust::complex<float_>) * samples * iter[3]);
cudaMallocManaged(&iterations, sizeof(int) * samples);
/*sample multiple times*/
for (int i = 0; i < sampleSamples; ++i) {
generateSamples << <(samples+32-1)/32, 32 >> > (Set, iterations, iter[3], minr, mini);
cudaDeviceSynchronize();
addToHeatmap << <32, 1024 >> > (buffer, Set, iterations, iter, maxValues, minr,
mini);
cudaDeviceSynchronize();
}
/*output image*/
png::image<png::rgb_pixel> image(width, height);
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
int index = j * height + i; // rotate 90 degrees
image.set_pixel(
i, j,
png::rgb_pixel(
getColor(buffer[index], maxValues[0]),
getColor(buffer[index + width * height], maxValues[1]),
getColor(buffer[index + width * height * 2], maxValues[2])));
}
}
auto t2 = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
double timeTook = duration.count();
std::cout << "It took " << timeTook
<< ((timeTook == 1.0) ? " second" : "seconds") << "\n";
image.write("output.png");
/*free variables*/
cudaFree(iter);
cudaFree(buffer);
cudaFree(iterations);
cudaFree(Set);
cudaFree(maxValues);
}
</code></pre>
<p>Here is the image outputted:</p>
<p><a href="https://i.stack.imgur.com/WLpKm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WLpKm.png" alt=""></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T14:38:34.127",
"Id": "476003",
"Score": "0",
"body": "The result looks really cool!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T16:34:40.693",
"Id": "476308",
"Score": "0",
"body": "What is your performance ? It took 15.7738 seconds on my computer.\nHave you tried nvprof ?\nYou have a dependency with libpng++ and when CUDA is correctly installed, compilation command is :\nnvcc -o buddhabrot buddhabrot.cu -L/path/to/lib/png -lpng16"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T17:20:32.577",
"Id": "476313",
"Score": "0",
"body": "it took me about 12 seconds but after changing `generateSamples << <samples, 1024 >> >` to `generateSamples << <(samples+32-1)/32, 32 >> >` it took about 8 seconds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T19:00:01.610",
"Id": "476328",
"Score": "0",
"body": "So what is your question ?\nAre you asking for performance tuning ? Code improvement ?\nUsing your << grid, block >> configuration, I now have 2.2 seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T19:30:22.143",
"Id": "476331",
"Score": "0",
"body": "I am asking for code improvement and performance tuning"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T21:59:36.100",
"Id": "241972",
"Score": "6",
"Tags": [
"c++",
"image",
"cuda"
],
"Title": "Buddhabrot made in CUDA"
}
|
241972
|
<p>I've decided to make a socket library in C++.
To be honest i found it a bit tiring using winsock2 - I'd say it's a bit complex, comparing to for instance Python socket lib.
My code, header file:</p>
<pre><code>#pragma once
#pragma comment(lib,"WS2_32.lib")
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <windows.h>
#include <string>
#include <iostream>
enum flags{
TCPType = 0,
UDPType = 1
};
inline flags operator|(const flags& x, const flags& y){
return static_cast<flags>(static_cast<int>(x)|static_cast<int>(y));
}
class Socket
{
private:
std::string ip;
std::string port;
SOCKET* currentSocket = nullptr;
bool isTcp;
public:
Socket(flags f = TCPType);
~Socket();
bool Connect(const std::string& address, const std::string& port);
bool BindToPort(int p);
bool Listen();
bool isTcpType();
int ReceiveAll(void* buffer, int size);
int Receive(void* buffer, int size);
int Sendall(void* buffer, int size);
int Send(void* buffer, int size);
std::string getAddress() const;
std::string getPort() const;
Socket* AcceptConnection();
void close();
static bool InitWinsock();
};
</code></pre>
<p>And the source file:</p>
<pre><code>#include "pch.h"
#include "Socket.h"
Socket::Socket(flags f)
{
isTcp = !f;
auto connectionType = SOCK_DGRAM;
auto b = 0;
if (isTcp) {
connectionType = SOCK_STREAM;
b = IPPROTO_TCP;
}
SOCKET mainSocket = socket(AF_INET, connectionType, b);
if (mainSocket == INVALID_SOCKET)
{
std::cerr << "Error creating socket: " << WSAGetLastError() << '\n';
WSACleanup();
}
currentSocket = new SOCKET(mainSocket);
}
Socket::~Socket()
{
if(currentSocket != nullptr)
delete currentSocket;
}
bool Socket::Connect(const std::string& address, const std::string& port){
addrinfo hints, *result = nullptr;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int iResult = getaddrinfo(address.c_str(), port.c_str(), &hints, &result);
if (iResult != 0) {
std::cerr << "getaddrinfo failed with error: " << iResult << '\n';
WSACleanup();
return false;
}
addrinfo *ptr = result;
iResult = connect(*currentSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(*currentSocket);
*currentSocket = INVALID_SOCKET;
}
return 0;
}
bool Socket::BindToPort(int p){
if (currentSocket == nullptr)
return false;
sockaddr_in service;
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
InetPton(AF_INET, (PCWSTR)("127.0.0.1"), &service.sin_addr.s_addr);
service.sin_port = htons(p);
if(bind(*currentSocket, (SOCKADDR *)& service, sizeof(sockaddr)) == SOCKET_ERROR)
{
std::cerr << "Error during binding socket: " << WSAGetLastError() << '\n';
closesocket(*currentSocket);
return false;
}
this->port = p;
return true;
}
bool Socket::Listen() {
if (currentSocket == nullptr)
return false;
if(listen(*currentSocket, 1) == SOCKET_ERROR)
std::cerr << "Error during trying to listen on socket: " << WSAGetLastError() << '\n';
ip = "127.0.0.1";
return true;
}
bool Socket::isTcpType(){
return isTcp;
}
int Socket::ReceiveAll(void* buffer, int size) {
int bytesLeft = size, current = 0;
while (bytesLeft > 0) {
int bytesRecv = recv(*currentSocket, static_cast<char*>(buffer), size, 0);
if (bytesRecv < 0)
return -1;
bytesLeft -= bytesRecv;
}
return size;
}
int Socket::Receive(void* buffer, int size){
if (currentSocket == nullptr)
return -1;
int bytesRecv = SOCKET_ERROR;
while(bytesRecv == SOCKET_ERROR)
{
bytesRecv = recv(*currentSocket, static_cast<char*>(buffer), size, 0);
if(bytesRecv == WSAECONNRESET)
break;
if (bytesRecv < 0)
return -1;
}
return bytesRecv;
}
int Socket::Sendall(void* buffer, int size) {
if (currentSocket == nullptr)
return -1;
int bytesSent = 0, counter = 0;
while (counter < size) {
bytesSent = send(*currentSocket, static_cast<const char*>(buffer), size, 0);
counter += bytesSent;
}
return size;
}
int Socket::Send(void* buffer, int size){
if (currentSocket == nullptr)
return -1;
int bytesSent, bytesRecv = SOCKET_ERROR;
bytesSent = send(*currentSocket, static_cast<const char*>(buffer), size, 0);
return bytesSent;
}
std::string Socket::getAddress() const{
return ip;
}
std::string Socket::getPort() const{
return port;
}
Socket* Socket::AcceptConnection(){
if (currentSocket == nullptr)
return false;
SOCKET acceptSocket = SOCKET_ERROR;
while (acceptSocket == SOCKET_ERROR)
{
acceptSocket = accept(*currentSocket, NULL, NULL);
}
Socket* result = new Socket(*this);
result->currentSocket = new SOCKET(acceptSocket);
return result;
}
void Socket::close() {
closesocket(*currentSocket);
delete currentSocket;
WSACleanup();
}
bool Socket::InitWinsock() {
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != NO_ERROR) {
std::cerr << "Error during initializing WinSock: " << WSAGetLastError() << '\n';
return false;
}
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:27:36.273",
"Id": "474875",
"Score": "0",
"body": "Can you add some more context about how you want this code to be reviewed? Why did you choose to do things the way you did, what do you think can be improved?"
}
] |
[
{
"body": "<p>No need for this in modern C++:</p>\n\n<pre><code>Socket* AcceptConnection();\n</code></pre>\n\n<p>You should not be returning RAW pointers. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:05:38.830",
"Id": "241976",
"ParentId": "241973",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T22:09:02.250",
"Id": "241973",
"Score": "1",
"Tags": [
"c++",
"library"
],
"Title": "Socket library base on winsock"
}
|
241973
|
<p>Multiple forms make use of the autocomplete of material, which gives a resulting code that is repetitive and difficult to maintain.</p>
<p>The controller is left with pairs of repeated methods [for each controller].</p>
<pre><code>displayFn(option?: Interface): string | undefined {
return option ? option.Property : undefined;
}
filterAutocomplete(ev: string) {
if (ev !== '' && ev !== null) {
// ...
}
}
</code></pre>
<p>The view is based on using the mat-autocomplete with a different template variable for each of them, saving errors.</p>
<pre><code><mat-form-field>
<input
matInput
[matAutocomplete]="auto"
(ngModelChange)="filterAutocomplete($event)"
formControlName="name"
/>
<mat-autocomplete
#auto="matAutocomplete"
[displayWith]="displayAutocomplete"
>
<mat-option
*ngFor="let option of selectionsOption"
[value]="option"
>
{{ option.Property }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</code></pre>
<p>In summary it is an example that would serve me for any context of this type:</p>
<ol>
<li>List item</li>
<li>Project with multiple forms.</li>
<li>Frequent use of autocompletes in forms</li>
<li>Optional, use of external libraries.</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T00:12:58.953",
"Id": "241977",
"Score": "1",
"Tags": [
"angular-2+"
],
"Title": "Autofilling multiple selectors Angular"
}
|
241977
|
<h3>Application Summary</h3>
<p>I received a call from a client asking for a "simple app" that notified him via text message whenever a "Jeep Wrangler" is posted to Facebook Marketplace. It sounded simple enough, so I took the gig. I figured I would leverage FB's Graph API or possibly simply set up a filter in his account, or something along those lines.</p>
<p>It wasn't long until I faced reality. This was going to be harder than I thought.</p>
<p>I ended up deciding to write a screen scraper. I chose NodeJS, Express, and Puppeteer to do this.</p>
<h3>End User UI</h3>
<p><a href="https://i.stack.imgur.com/ophKK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ophKK.png" alt="App" /></a></p>
<h3>A JSON Failure</h3>
<p>When I was almost done with the app, I realized I could not use JSON as my data storage, as I intended. Heroku apparently uses Dyno's that sleep, and data does not persist. I don't fully understand it, but I had to take a different approach.</p>
<h3>Finally...</h3>
<p>Well, this is what I came up with so far. I am pretty much done, I just need to fix my HTML page to use <code><% %></code> tags to display the data.</p>
<pre><code>const puppeteer = require('puppeteer');
const jsonfile = require("jsonfile");
const _ = require("lodash");
var mysql = require('mysql');
var browser;
var page;
// Connect to database
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'marketplace'
});
global.pool = pool;
// Gets current items Search Results
const getItems = async searchTerm => {
browser = await puppeteer.launch({
headless: true,
timeout: 0,
args: ["--no-sandbox"]
});
page = await browser.newPage();
await page.goto(`https://facebook.com/marketplace/tampa/search/?query=${encodeURI(searchTerm)}&sort=created_date_descending&exact=true`);
await autoScroll(page);
const itemList = await page.waitForSelector('div > div > span > div > a[tabindex="0"]')
.then(() => page.evaluate(() => {
const itemArray = [];
const itemNodeList = document.querySelectorAll('div > div > span > div > a[tabindex="0"]');
itemNodeList.forEach(item => {
const itemTitle = item.innerText;
const itemURL = item.getAttribute('href');
const itemImg = item.querySelector('div > div > span > div > a > div > div > div > div > div > div > img').getAttribute('src');
var obj = ['price', 'title', 'location', 'miles',
...itemTitle.split(/\n/)
]
.reduce((a, c, i, t) => {
if (i < 4) a[c] = t[i + 4]
return a
}, {});
obj.imgUrl = itemImg;
obj.itemURL = itemURL;
itemArray.push(obj);
});
return itemArray;
}))
.catch(() => console.log("Selector error."));
return itemList;
}
const initScraper = async () => {
var finalArray = [];
var currentItems = [];
var previousItems = [];
// Scrape Page - Get New Items
currentItems = await getItems('Jeep Wrangler');
// Save Data: previousJeeps
const insertCurrentSuccess = await saveToDatabase('previousJeeps',currentItems);
allDone();
// Get Previous Items From Database
previousItems = await getPreviousItems();
// Get Differences
finalArray = _.difference(currentItems, previousItems);
//console.log(finalArray);
// Save Data: newJeeps
const insertNewSuccess = await saveToDatabase('newJeeps',finalArray);
// If New Items, Notify User
if (!_.isEqual(currentItems, previousItems)) {
changed = true;
const page2 = await browser.newPage();
await page2.goto(`http://john.mail.com/mail.php`);
console.log("changed");
}
// Let us know when done
console.log("done");
}
initScraper();
const allDone = async function(){
console.log("All done");
//process.exit();
}
//----------------------------------------------------
// This function loads the entire search results from
// last time - so it can be compared against the
// new search results.about_content
//----------------------------------------------------
const getPreviousItems = async function () {
pool.query("SELECT * FROM previousJeeps", function (err, result, fields) {
if (err){
console.log(err);
// Redirect to error page
} else {
return result;
}
});
}
// Save Data
const saveToDatabase = async function (tblName, results) {
/*
results.forEach(element => {
var sql = "";
var title = title.replace(/'/g, "\\'");;
var location= location.replace(/'/g, "\\'");;;
var miles= miles.replace(/'/g, "\\'");;;
var imgUrl= imgUrl.replace(/'/g, "\\'");;;
var itemURL= itemURL.replace(/'/g, "\\'");;;
sql = "INSERT INTO " + tblName +
"SET (title, price, location, miles, imgUrl, itemURL, status, is_deleted)" +
"VALUES (" +
"'${title}', '${element.price}', '${location}', '${miles}', '${imgUrl}', '${itemURL}', 1, 0" +
")";
pool.query(sql, function (err, rows, fields) {
if (err) throw err;
});
})
*/
return true;
}
// This takes care of the auto scrolling problem
async function autoScroll(page) {
await page.evaluate(async () => {
await new Promise(resolve => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if (totalHeight >= scrollHeight || scrollHeight > 9000) {
clearInterval(timer);
resolve();
}
}, 100);
});
});
}
//----------------------------------------------------
</code></pre>
<p>Any criticism , good or bad, welcome. I wonder if this could have been done better, more efficient, etc.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:06:51.327",
"Id": "474888",
"Score": "0",
"body": "I can see quite a few logic problems; the script will not work as it should on a number of crucial steps. You might want to try running the script and debugging to get it at least in mostly working order first, per CR rules"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:18:20.303",
"Id": "474889",
"Score": "0",
"body": "Thanks for looking. It actually works great. The code above is an early version of V2 which is where I went from JSON to MySQL. I should comment out the DB stuff, just to get some feedback on the architecture alone. But I am curious, what logic issues do you see?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:29:29.097",
"Id": "474892",
"Score": "0",
"body": "`saveToDatabase` doesn't return anything, nor does `getPreviousItems`, `previousItems` will always be `undefined` inside `initScraper`, so the `finalArray = _.difference(currentItems, previousItems);` and other stuff which depends on `finalArray` and `previousItems` won't work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T05:57:44.003",
"Id": "474977",
"Score": "0",
"body": "@certain, you are correct, and I am new to this forum. I now know to post finalized version of my code. What I was looking for was some advice on the approach as a whole. It just seems like there is a better way than: 1. Scrape, 2. Open last scrape file. 3. Compare. 4. Save differences back to file (in #2). 5. If any changes, email user. 6. Repeat. It just seems like a lot of work. Any suggestions? I foresee about one to two new items a day, in case that affects your suggestion. Thank you for looking. I will update the code when I get to office. Have a great night. Thanks again"
}
] |
[
{
"body": "<p>One thing that stands out to me is the database itself. It's somewhat ugly for something that sounds like it only really <em>needs</em> to keep track of one thing: a unique identifier for each truck viewed so far (such as its page URL), if the client wants to be alerted on <em>new</em> postings, and not on edits to <em>old</em> postings. If it were me, I'd set the script up on my <em>own</em> server, which does have a persistent file system, and then it'd be trivial to save and retrieve the URLs seen so far with <code>JSON.stringify</code>/<code>JSON.parse</code> with a tiny local file. If that's not possible, you can still make things simpler by saving <em>just</em> the URLs of each truck into the database, then checking whether the URL of a truck found on the page exists in the database yet or not.</p>\n\n<p>It's pretty much never a good idea to directly concatenate input to construct the SQL query string:</p>\n\n<pre><code>sql = \"INSERT INTO \" + tblName +\n \"SET (title, price, location, miles, imgUrl, itemURL, status, is_deleted)\" +\n \"VALUES (\" +\n \"'${title}', '${element.price}', '${location}', '${miles}', '${imgUrl}', '${itemURL}', 1, 0\" +\n \")\";\n</code></pre>\n\n<p>It's not only inelegant, when done wrong, it can lead to (inadvertent) SQL injection and other troubles. Consider using <a href=\"https://node-postgres.com/features/queries#Parameterized%20query\" rel=\"nofollow noreferrer\">parameterized queries</a> instead.</p>\n\n<p>You might also consider using <a href=\"https://www.sitepoint.com/using-redis-node-js/\" rel=\"nofollow noreferrer\">Redis</a> instead of a database, I think it might be a slightly better choice, especially if you just need to store an array of URLS. I believe you could do something like:</p>\n\n<pre><code>// Retrieve all elements in \"truckUrls\" list\n// lrange: retrieves all elements of list\n// Use a Set for less computational complexity\nconst existingUrls = new Set(await lrange('truckUrls', 0, -1));\n\nconst currentlyDisplayedItems = await getItems();\n\nconst newItems = currentlyDisplayedItems.filter(({ itemURL }) => !existingUrls.has(itemURL));\nif (newItems.length > 0) {\n // Save new URLs:\n // rpush: pushes elements to a list\n await rpush('truckUrls', ...newItems.map(({ itemURL }) => itemURL));\n // Then notify user with items from the newItems object here\n}\n// Done\n</code></pre>\n\n<p>where <code>lrange</code> and <code>push</code>, Redis methods have been promisified. (By default, they use callbacks, just like your existing <code>pool.query</code>.) To convert a callback API to a Promise, either use <a href=\"https://nodejs.org/dist/latest-v8.x/docs/api/util.html\" rel=\"nofollow noreferrer\">util.promisify</a> (recommended) or <a href=\"https://stackoverflow.com/q/22519784\">do it manually</a>. (Your current <code>getPreviousItems</code> and <code>saveToDatabase</code> are not promisified, so they resolve immediately, rather than when the action is complete, and don't resolve to anything.)</p>\n\n<p>In your <code>initScraper</code> function, there's no need to assign to a variable that isn't going to be read before it's reassigned:</p>\n\n<pre><code>var currentItems = [];\n// ...\n\n\n// Scrape Page - Get New Items\ncurrentItems = await getItems('Jeep Wrangler');\n</code></pre>\n\n<p>Better to declare the variable only after the value to assign to it is retrieved:</p>\n\n<pre><code>const currentItems = await getItems('Jeep Wrangler');\n</code></pre>\n\n<p>Note the use of <code>const</code>. You're sometimes declaring variables with <code>var</code>, and sometimes with <code>const</code>. If you're writing in ES2015+ syntax (which you are, and should be), you should always use <code>const</code> to declare variables: <code>var</code> has <a href=\"https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var\">too many gotchas</a> to be worth using, and is less readable than <code>const</code> (since with <code>const</code>, you know that a variable is never going to be reassigned). If a variable must be reassigned, declare it with <code>let</code>.</p>\n\n<p>Make sure to handle errors - unhandled Promise rejections are deprecated and in the future will cause the Node process to terminate. Best place to handle them would probably be at the entry point, the <code>initScraper</code> call:</p>\n\n<pre><code>initScraper()\n .catch((err) => {\n // handle errors\n // add to a logfile?\n });\n</code></pre>\n\n<p>I think the only thing left to look at is the <code>getItems</code> function.</p>\n\n<p>The reassignment of the global <code>browser</code> variable used both in <code>getItems</code> and <code>initScraper</code> is somewhat smelly:</p>\n\n<pre><code>browser = await puppeteer.launch({\n headless: true,\n timeout: 0,\n args: [\"--no-sandbox\"]\n});\n</code></pre>\n\n<p>Consider constructing the browser in <code>initScraper</code> instead, and then <em>pass</em> it to <code>getItems</code> - that'll let you declare it with <code>const</code>, and avoid an unnecessary global variable. <code>page</code> doesn't need to be global either - it's only used inside <code>getItems</code>, so feel free to declare it with <code>const</code> inside.</p>\n\n<p>Since you don't need to use the <code>page.waitForSelector</code> result directly, and since you're using <code>await</code> already (which is good!), you might use <code>await page.waitForSelector</code> and <em>separately</em> do <code>const itemList = await page.evaluate</code>. This also less you get rid of a layer of bracket nesting.</p>\n\n<p>You have a couple of <em>very specific</em> selectors. If they <em>work</em>, that's fine, but the slightest tweak to Facebook's HTML will cause your script to break. You might consider using the descendant selector instead when possible, and with something more specific than tag names. For example, it would be great if you could replace <code>div > div > span > div > a[tabindex=\"0\"]</code> with a selector similar to <code>.listContainer a[tabindex=\"0\"]</code> where <code>listContainer</code> is a class on an ancestor element - look through the DOM to see if something like that is possible. (Rather than repeating this selector twice, save it in a variable first, then reference that variable.) Same thing for <code>itemImg</code>'s selector - you might be able to replace</p>\n\n<pre><code>item.querySelector('div > div > span > div > a > div > div > div > div > div > div > img')\n</code></pre>\n\n<p>with</p>\n\n<pre><code>item.querySelector('img[src]')\n</code></pre>\n\n<p>It's best to <a href=\"http://perfectionkills.com/the-poor-misunderstood-innerText/\" rel=\"nofollow noreferrer\">avoid <code>.innerText</code></a> unless you're <em>deliberately</em> looking to invoke its strange text styling rules. See if you can use <code>textContent</code> instead, which is the standard method.</p>\n\n<p>If you're iterating over all elements of an array to construct a new one, it's more appropriate to use <code>Array.prototype.map</code> (from which you can return the item for the new array) than to use <code>forEach</code> and <code>push</code>. (See below for example.)</p>\n\n<p>The <code>reduce</code> there is really weird. If you have an array of values that you want to put into an object with particular key names, using a plain object literal by destructuring the <code>split</code> call would make more sense (see below for example).</p>\n\n<p>In full, <code>getItems</code> can be made to look something like the following:</p>\n\n<pre><code>const getItems = async (searchTerm, browser) => {\n const page = await browser.newPage();\n await page.goto(`https://facebook.com/marketplace/tampa/search/?query=${encodeURI(searchTerm)}&sort=created_date_descending&exact=true`);\n await autoScroll(page);\n const itemSelector = 'div > div > span > div > a[tabindex=\"0\"]';\n await page.waitForSelector(itemSelector);\n return page.evaluate(() => {\n return [...document.querySelectorAll(itemSelector)]\n .map((item) => {\n const itemTitle = item.textContent;\n const itemURL = item.href;\n const imgUrl = item.querySelector('img[src]').src;\n const [price, title, location, miles] = itemTitle.split(/\\n/);\n return { price, title, location, miles, imgUrl, itemURL };\n });\n });\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T02:04:51.700",
"Id": "475018",
"Score": "0",
"body": "Wow thank you so much! I can't wait to dig in and try every suggestion. Before I read this answer from you, I made some good progress ( on the same path, however ). The code is here: https://gist.github.com/johnsdeveloper/b856195b0d23efd219e18db2da5ff4fc , and if I could get the darn insert to work, I think I would be in good shape, Although I agree, your re-write is definitely in order. If the code in my latest gist worked, I would set up the cron for every 10 mins. It would simply write the new vehicles to a table the front end would grab. Looking at it now, though, needs ALOT of work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T17:16:33.343",
"Id": "242044",
"ParentId": "241981",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242044",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T04:09:27.943",
"Id": "241981",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"web-scraping"
],
"Title": "Text notifications for Facebook Marketplace posting"
}
|
241981
|
<p>This class represents a single entry in a log file of the <a href="https://en.wikipedia.org/wiki/Common_Log_Format" rel="nofollow noreferrer">Common Log Format</a>. Can this be improved? I think I might be able to use delegation to pluck values from the matcher. Ideally I would be able to set these values at declaration time. </p>
<p>Kotlin code </p>
<pre class="lang-kotlin prettyprint-override"><code> data class CommonLogEntry(private val entry: String) {
companion object {
private val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
private fun asDateTime(line: String) = LocalDateTime.parse(line, formatter)
val pattern: String = "^(\\S+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})] \"(\\S+) (\\S+)\\s*(\\S+)?\\s*\" (\\d{3}) (\\d+) \"(\\S+)\" \"(\\S+)\""
}
val clientIp: String
val rfc1413identity: String
val identity: String
val requestTime: LocalDateTime
val verb: String
val resource: String
val httpVersion: String
val statusCode: Int
val payloadSize: Long
val URI: URI
val userAgent: String
init {
val p = Pattern.compile(pattern)
val m = p.matcher(entry)
if (!m.matches() || m.groupCount() != 11)
throw IllegalArgumentException("Log Pattern doesn't match '$pattern'")
clientIp = m.group(1)
rfc1413identity = m.group(2)
identity = m.group(3)
requestTime = asDateTime(m.group(4))
verb = m.group(5)
resource = m.group(6)
httpVersion = m.group(7)
statusCode = m.group(8).toInt()
payloadSize = m.group(9).toLong()
URI = java.net.URI.create(m.group(10))
userAgent = m.group(11)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T08:11:01.357",
"Id": "474904",
"Score": "0",
"body": "Your title should be what your code does. Read https://codereview.stackexchange.com/help/how-to-ask ."
}
] |
[
{
"body": "<p>By moving a few things around you could easily get rid of the <code>init</code> block, shortening the amount of lines.</p>\n\n<p>Key parts is to move the <code>Pattern</code> to the companion object, and use <code>.also</code> on the matcher to make sure it is a correct match.</p>\n\n<pre><code>data class CommonLogEntry(private val entry: String) {\n companion object {\n private val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(\"dd/MMM/yyyy:HH:mm:ss Z\")\n private fun asDateTime(line: String) = LocalDateTime.parse(line, formatter)\n val pattern: Pattern = Pattern.compile(\"^(\\\\S+) (\\\\S+) (\\\\S+) \\\\[([\\\\w:/]+\\\\s[+\\\\-]\\\\d{4})] \\\"(\\\\S+) (\\\\S+)\\\\s*(\\\\S+)?\\\\s*\\\" (\\\\d{3}) (\\\\d+) \\\"(\\\\S+)\\\" \\\"(\\\\S+)\\\"\")\n }\n\n private val m = pattern.matcher(entry).also {\n if (!it.matches() || it.groupCount() != 11)\n throw IllegalArgumentException(\"Log Pattern doesn't match '$pattern'\")\n }\n val clientIp: String = m.group(1)\n val rfc1413identity: String = m.group(2)\n val identity: String = ...\n val requestTime: LocalDateTime = ...\n val verb: String = ...\n val resource: String = ...\n val httpVersion: String = ...\n val statusCode: Int = ...\n val payloadSize: Long = ...\n val URI: URI = ...\n val userAgent: String = ...\n</code></pre>\n\n<p>However, I have to question the reason for writing this code. I have a feeling there is already some library out there that can parse these log files, it is the \"Common Log Format\" after all. Also, if you want to parse log files in general I would strongly recommend the tool <a href=\"https://www.splunk.com\" rel=\"nofollow noreferrer\">Splunk</a> which does have a free license for up to 500 MB of logs per day.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:27:15.767",
"Id": "474925",
"Score": "0",
"body": "Normally I would agree with you - I looked around for libraries and most also brought in 20 other formats I didn't need. Plus, this is for demonstration, not production."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T09:07:12.287",
"Id": "241988",
"ParentId": "241984",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241988",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T06:35:22.223",
"Id": "241984",
"Score": "1",
"Tags": [
"regex",
"kotlin"
],
"Title": "Can delegation be used to set these values at declaration time (thus reducing lines)?"
}
|
241984
|
<p>I am currently backing up remote OS' while preserving the permissions using rsync:</p>
<pre><code>rsync -aAX --numeric-ids --delete ... root@X.X.X.X:/ /backup/server/
</code></pre>
<p>Now I want to backup the backup to a third party. I currently have:</p>
<pre><code>tar --xattrs -czpf - "/backup/server/" | openssl enc -aes-256-cbc -a -salt -pass pass:"$KEY" -out "/backup/server.encr"
</code></pre>
<p>Which will compress and encrypt while preserving permissions.</p>
<p>I would eventually like to write this in Go but it seems a bit complicated the preserving of permissions are there some alternative all in one libraries to do this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T10:08:27.943",
"Id": "241991",
"Score": "1",
"Tags": [
"bash",
"shell",
"compression",
"encryption"
],
"Title": "Compressing and encrypting file systems for backups"
}
|
241991
|
<p>This is a small script to update an external HDD, every night at 23:00, in the background.</p>
<p>Can you tell me how I can improve it? </p>
<p>What section in this code can be written as a class? Maybe the <code>log</code> function? </p>
<p>This line -> <code>from distutils import dir_util</code>. How can I write this to follow the same format as my other <code>import</code>s? </p>
<pre><code>###############################################################################
## Description: This script is meant to update the HDD given the location from
## the HDD needs to be synced and where it should copy the files.
## The script will check how much space is on the external HDD
## will create a folder with today's date and copy the files in
## that folder
##
## Example Call: python3 syncHDD.py --SYNCHDD_DAYS_KEEP [integer]
## --SYNCHDD_FROM [path]
## --SYNCHDD_TO [path]
## --SYNCHDD_LOG [path]
##
## python3 syncHDD.py --SYNCHDD_DAYS_KEEP 5 --SYNCHDD_FROM <fromdir> --SYNCHDD_TO <toDir> --SYNCHDD_LOG <logFolder>
##
###############################################################################
###############################################################################
## IMPORT UTILITIES
###############################################################################
import importlib, sys
for moduleName in ['os', 're', 'math', 'datetime', 'distutils', 'sys', 'getopt', 'crontab', 'getpass']:
print('Importing ' + moduleName + " ... ", end="")
try:
globals()[moduleName] = importlib.import_module(moduleName)
except ModuleNotFoundError:
print('FAILED')
sys.exit[1]
print('SUCCESS')
from distutils import dir_util
###############################################################################
## DEFINING FUNCTIONS
###############################################################################
def hdfooter(vr):
if(vr == 'header'):
print('')
print('========== STARTING FUNCTION ==========')
print('')
else:
print('')
print('========== **ENDING FUNCTION ==========')
print('')
def getTimestamp():
return datetime.datetime.now().strftime("%Y.%m.%dD%H.%M.%S.%f")
def getDate():
return datetime.datetime.now().strftime("%Y.%m.%d")
def sep():
if sys.platform.startswith('linux'):
return '/'
if sys.platform.startswith('win'):
return '\\'
def createLogMessage(lvl,message):
if (lvl == 0):
prefix = "[*INFO]|"
elif (lvl == 1):
prefix = "[ERROR]|"
else:
prefix = "[DEBUG]|"
return prefix + getTimestamp() + "| " + message
def openCloseLogFile(LFN, dV, action,file=None):
#function to open the logfile and print the header and footer
#create log file in specified location
logFilePath = dV['SYNCHDD_LOG']
logFilePath = logFilePath + "/" + LFN
if action == "open":
if os.path.exists(logFilePath):
#if file exists open to append new log messages
file = open(logFilePath,"a+")
file.write('========== STARTING FUNCTION ==========\n')
return file
else:
#if files does not exist, create it.
file = open(logFilePath,"w")
file.write('========== STARTING FUNCTION ==========\n')
return file
else:
file.write('========== **ENDING FUNCTION ==========\n\n')
file.close()
def log(lvl,message,file):
#create log message
message = createLogMessage(lvl,message)
#print to file
print(message)
file.write(message)
file.write('\n')
def convertBytesToMb(bytesValue):
return bytesValue/1000000
def return_date_like_folders(fld):
res = []
for fname in fld:
if (re.match(r"\d+\.\d+\.\d+", fname)):
res.append(fname)
return res
def removeDays(path,dV,file):
# check if SYNCHDD_DAYS_KEEP is defined and only keep the data copied for
# thos days
startTime = datetime.datetime.now()
log(0,"removeDays: Removing data older than " + dV['SYNCHDD_DAYS_KEEP'] + " days ...",file)
dt = return_date_like_folders(os.listdir(path))
thresholdDate = (datetime.datetime.today() - datetime.timedelta(days = int(dV['SYNCHDD_DAYS_KEEP']))).strftime('%Y.%m.%d')
for i in dt:
if (datetime.datetime.strptime(i,'%Y.%m.%d') < datetime.datetime.strptime(thresholdDate,"%Y.%m.%d")):
try:
log(0, "removeDays: Attempting to remove: " + path + i + "/", file)
dir_util.remove_tree(path + i + "/")
except OSError as e:
log(1,"removeDays: Failed to delete directory [" + (path + i + "/") + "] with error: " + e,file)
def getNecessarySpace(path,file):
log(0,"getNecessarySpace: Getting necessary space ...",file)
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return math.ceil(convertBytesToMb(total_size))
def getAvailableSpace(path,file):
log(2,"getAvailableSpace: Getting available space ...",file)
return math.ceil(convertBytesToMb(os.statvfs(path).f_frsize * os.statvfs(path).f_bavail))
def createTodayFolder(path,file):
folderName = datetime.datetime.now().strftime("%Y.%m.%d")
#list folder in directory and check if fodler for today already exists
if not folderName in os.listdir(path) :
log(0,"createTodayFolder: Creating folder: " + folderName + " in " + path,file)
try:
os.mkdir(path + folderName)
except OSError:
log(2,"createTodayFolder: Failed to create folder " + folderName + " in " + path,file)
else:
log(0,"createTodayFolder: Successfully created folder " + folderName + " in " + path,file)
else:
log(1,"createTodayFolder: Folder already exists ...",file)
sys.exit(2)
return folderName
def copyFilesAccross(source, destination, file):
#check if there is enough space
startTime = datetime.datetime.now()
log(0,"copyFilesAccross: Copying files ...",file)
try:
dir_util.copy_tree(source,destination)
log(0,"Operation has completed successfully in: " + str(datetime.datetime.now() - startTime), file)
except OSError as e:
log(1,"copyFileAccross: Failed to copy from " + source + " to " + destination + " with error: " + e,file)
def checkEnvVar(eV,file):
for v in eV:
if os.getenv(v) is None:
log(1,'checkEnvVar: Environment variable: ' + v + ' has not been set. Function will terminate ...',file)
sys.exit()
def getProgParams(arg, parName):
#function to check if env var are defined if not take from command line
#env variables have priority
if os.getenv(parName) is None:
print('getProgParams: Environment Variable Does Not Exist -> For variable '+ parName +' setting to ' + arg)
return arg
else:
print('getProgParams: Environment Variable Exists -> For variable '+ parName +' setting to ' + os.getenv(parName))
return os.getenv(parName)
def getCmdLineArguments():
#function to create a dictionary of arguments passed from the cmdline
dictVal = {} #Creating an empty dictionary
argv = sys.argv[1:]
dictVal['execLine'] = ' '.join([sys.executable] + [os.getcwd() + sep() + sys.argv[0]] + argv)
try:
opts, args = getopt.getopt(argv, "hd:f:t:l:" ,["SYNCHDD_DAYS_KEEP=", "SYNCHDD_FROM=", "SYNCHDD_TO=", "SYNCHDD_LOG="])
except getopt.GetoptError:
print('getCmdLineArguments: Failed to get command line arguments ...')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print("\nHelp Message:\nsyncHDD.py --SYNCHDD_DAYS_KEEP [integer] --SYNCHDD_FROM [path] --SYNCHDD_TO [path] --SYNCHDD_LOG [path]\n")
sys.exit()
elif opt in ("-d", "--SYNCHDD_DAYS_KEEP"):
dictVal['SYNCHDD_DAYS_KEEP'] = getProgParams(arg, 'SYNCHDD_DAYS_KEEP')
elif opt in ("-f", "--SYNCHDD_FROM"):
dictVal['SYNCHDD_FROM'] = getProgParams(arg, 'SYNCHDD_FROM')
elif opt in ("-t", "--SYNCHDD_TO"):
dictVal['SYNCHDD_TO'] = getProgParams(arg, 'SYNCHDD_TO')
elif opt in ("-l", "--SYNCHDD_LOG"):
dictVal['SYNCHDD_LOG'] = getProgParams(arg, 'SYNCHDD_LOG')
return dictVal
def addToCron(eL, dV, file):
#there are some errors in here that I need to sort out
#seems to add the jobs quite a few times
#also seems to change the scheduling for other jobs
#function to add this job to the cron job if on linux
log(0,'addToCron: Attempting to add a new job to cron',file)
myCron = crontab.CronTab(user = getpass.getuser())
scriptName = dV['execLine'].split(' ')[1].split('/')[-1]
jobExists = False
for job in myCron:
if job.comment == scriptName:
jobExists = not jobExists
if not jobExists:
log(0,'addToCron: Adding ' + dV['execLine'] + ' to crontab ...',file)
job = myCron.new(command = dV['execLine'], comment='syncHDD.py')
job.hour.on(23)
#job.minute.every(5)
try:
myCron.write()
log(0,'Job has been successfully added to crontab ',file)
except OSError as errorMessage:
log(1,'addToCron: Failed to write to crontab with OSError -> ' + str(errorMessage), file)
else:
log(1,'addToCron: Job ['+ scriptName +'] already exists',file)
def main():
dictVal = getCmdLineArguments()
print("RUNNING FUNCTION ...")
hdfooter('header')
logFileName = "logOutput_" + datetime.datetime.now().strftime("%Y%m%dD%H%M%S%f") + ".log"
file = openCloseLogFile(logFileName, dictVal, "open")
log(0,"Log messages will be printed in: "+ logFileName,file)
for elem in ['SYNCHDD_DAYS_KEEP','SYNCHDD_FROM','SYNCHDD_TO','SYNCHDD_LOG']:
if not elem in list(dictVal.keys()):
if os.getenv(elem) is None:
log(1,'main: Variable '+ elem + ' is missing. Exiting ...',file)
sys.exit(2)
else:
log(0,'main: Variable '+ elem + ' will be set to ' + os.getenv(elem),file)
dictVal[elem] = os.getenv(elem)
##checkEnvVar(["SYNCHDD_FROM","SYNCHDD_TO","SYNCHDD_LOG"],file)
src = dictVal['SYNCHDD_FROM']
destination = dictVal['SYNCHDD_TO']
addToCron(dictVal['execLine'], dictVal, file)
removeDays(destination,dictVal,file)
log(0,"main: Moving from " + src + " to " + destination,file)
#create folder with today's date
destination = destination + createTodayFolder(destination,file)
necessarySpace = getNecessarySpace(src,file)
availableSpace = getAvailableSpace(destination,file)
if( necessarySpace > availableSpace):
log(1,"main: Needed space is greater than available space. Necessary: "
+ str(necessarySpace)
+ " Available: "
+ str(availableSpace),file)
else:
log(0,"main: Available space: " + str(availableSpace) + " Necessary space: " + str(necessarySpace), file)
log(0,"main: There is enough space. Files can be copied",file)
copyFilesAccross(src,destination,file)
openCloseLogFile(logFileName, dictVal, "close", file)
hdfooter('footer')
###############################################################################
## MAIN
###############################################################################
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T14:53:23.517",
"Id": "474939",
"Score": "1",
"body": "In the future, please format your question as per [How to Ask](https://codereview.stackexchange.com/help/how-to-ask), in particular \"**Titling your question**\"."
}
] |
[
{
"body": "<p>DRTW: don't reinvent the wheel. Python provides extensive libraries for:</p>\n\n<ul>\n<li><a href=\"https://docs.python.org/3.8/library/logging.html\" rel=\"nofollow noreferrer\">logging</a></li>\n<li><a href=\"https://docs.python.org/3.8/library/argparse.html\" rel=\"nofollow noreferrer\">parsing command-line arguments</a></li>\n</ul>\n\n<p>If you take advantage of these built-in modules you can minimize the amount of code required. You can probably divide the code base by two without any loss of functionality.</p>\n\n<p>I repeat myself from other topics, but here is how you could do your logging:</p>\n\n<pre><code>import logging\nimport sys\n\nlog_file = '/home/anonymous/test.log'\n\n# logging - source: https://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout\n# Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.\nlogging.getLogger().setLevel(logging.NOTSET)\n\n# Add stdout handler, with level INFO\nconsole = logging.StreamHandler(sys.stdout)\nconsole.setLevel(logging.INFO)\nformater = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', \"%Y-%m-%d %H:%M:%S\")\nconsole.setFormatter(formater)\nlogging.getLogger().addHandler(console)\n\n# Add file handler, with level DEBUG\nhandler = logging.FileHandler(log_file)\nhandler.setLevel(logging.DEBUG)\nformater = logging.Formatter('%(asctime)s\\t%(filename)s\\t%(lineno)s\\t%(name)s\\t%(funcName)s\\t%(levelname)s\\t%(message)s', \"%Y-%m-%d %H:%M:%S\")\nhandler.setFormatter(formater)\nlogging.getLogger().addHandler(handler)\n\nlogger = logging.getLogger(__name__)\n\n# this line will appear on console and in the log file\nlogger.info(f\"Application started\")\n\n# this line will only appear in the log file because level = debug\nlogger.debug(f\"Log some gory details here\")\n</code></pre>\n\n<p>In this example I am logging to the console and to a log file at the same time so you can track progress and keep a permanent record of activity. But the log file contains more details, like procedure name, line number, etc. The console will not print messages that have a debug level (= fewer details).</p>\n\n<p>In your case you may want to add more <strong>destinations</strong>. If you want to have multiple log files no problem.</p>\n\n<p>And if the built-in logging module is not sufficient for your needs you can still derive your own class from it to add necessary enhancements.</p>\n\n<hr>\n\n<p>To parse and validate <strong>command-line arguments</strong> at the same time:</p>\n\n<pre><code>import argparse\n\n# check command line options\nparser = argparse.ArgumentParser()\n# Number of days to keep: short form = -dk\nparser.add_argument('--synchdd_days_keep', '-dk', dest=\"days_to_keep\", \ntype=int, choices=range(10), required=True, help=\"Number of days to keep: a value between 0 and 9\")\n\nargs = parser.parse_args()\n\n# show the values\nprint(f\"Number of days to keep: {args.days_to_keep}\")\n</code></pre>\n\n<p>This code expects an integer value for the argument <code>--synchdd_days_keep</code> but for demonstration purposes will also accept an alternative, short form: <code>-dk</code>. The integer must also be in the range 0->9.</p>\n\n<p>Usage:<br />\nRun with option <code>-h</code> to display the built-in help.<br />\nwill work: <code>-dk 1</code><br />\nwill not work: <code>-dk 10</code></p>\n\n<p>That's it. Parsing and validating parameters with a minimum of code. Let Python do the job for you. The functionality is already available. I think this code can still be improved/prettified a bit. It's up to you to decide which arguments should be mandatory and which ones are optional.</p>\n\n<p>My advice would to get a manual or tutorial about Python, and have a quick look at the standard features. Had you been aware, you would not have coded all those functions. There are better alternatives.</p>\n\n<hr>\n\n<p>One more tip: using F-strings to avoid string concatenations.\nInstead of:</p>\n\n<pre><code>log(0,\"main: Available space: \" + str(availableSpace) + \" Necessary space: \" + str(necessarySpace), file)\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>print(f\"Available space: {availableSpace} - Necessary space: {necessarySpace}\")\n</code></pre>\n\n<p>With logger:</p>\n\n<pre><code>logger.info(f\"Available space: {availableSpace} - Necessary space: {necessarySpace}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T14:48:35.177",
"Id": "242006",
"ParentId": "241994",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:24:04.950",
"Id": "241994",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Small script to update an external HDD every night at 23 in the background"
}
|
241994
|
<p><a href="https://codereview.meta.stackexchange.com/q/10480/42401">Code must be included in the question in code blocks</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:38:38.140",
"Id": "241995",
"Score": "0",
"Tags": null,
"Title": null
}
|
241995
|
Questions that are stored in a Jupyter notebook. Code must be provided in the question in code block(s).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:38:38.140",
"Id": "241996",
"Score": "0",
"Tags": null,
"Title": null
}
|
241996
|
<p>I created a simple bank program. The program asks for the user’s name and a starting balance. From there, the user can do 4 things, Check Balance, Add Funds, Transfer Funds and Exit the program. Check Balance simply returns the name of the user along with the remaining amount of funds in his account. Add Funds asks the user for an amount to put in his account. Transfer Funds asks the user for an amount to reduce from his account. This is a simple program that practices your understanding of objects and how to manipulate their fields. You can try Overriding a method to simplify one function of this program.</p>
<p>I posted this code in the hopes of getting people's opinion on if my program follows the standards of OOP and also for any improvements to how it is written. I am self-learning Java and would love any feedback so that I can learn from creating this program.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
boolean quit = false;
int choice;
String accountName;
double startBalance;
System.out.printf("%24s\n","BankApp v1.0");
System.out.println("=====================================");
System.out.println("Please enter your details below.");
System.out.println("Account Name: ");
accountName = scanner.nextLine();
System.out.println("Starting Balance: ");
startBalance = scanner.nextDouble();
Account account = new Account(accountName,startBalance);
while(!quit){
printMainMenu();
choice = scanner.nextInt();
switch(choice){
case 1:
System.out.printf("Account Name: %s\nAccount Balance: $%.2f\n",account.getAccountName(),
account.getAccountBal());
break;
case 2:
System.out.println("Enter amount to be added: ");
account.addFunds(scanner.nextDouble());
break;
case 3:
System.out.println("Enter amount to be transferred: ");
account.transferFunds(scanner.nextDouble());
break;
case 4:
quit = true;
break;
default:
System.out.println("Invalid choice.");
break;
}
}
scanner.close();
}
public static void printMainMenu(){
System.out.printf("%24s\n" +
"=====================================\n" +
"Please select an option:\n" +
"1 - Check Balance\n" +
"2 - Add Funds\n" +
"3 - Transfer Funds\n" +
"4 - Exit the program\n" +
"=====================================\n" +
"Choice: ","BankApp v1.0");
}
}
</code></pre>
<p>This is the Account class code.</p>
<pre class="lang-java prettyprint-override"><code>public class Account {
private String accountName;
private double accountBal;
public Account(String accountName, double accountBal) {
if(accountBal < 0) {
System.out.println("Starting balance cannot be less than zero.\nBalance set to $0.00");
}else {
this.accountName = accountName;
this.accountBal = accountBal;
System.out.println("Account initialized.\nBalance set to $" + this.accountBal);
}
}
public String getAccountName() {
return accountName;
}
public double getAccountBal() {
return accountBal;
}
public void transferFunds(double withdrawal){
if(withdrawal > this.accountBal){
System.out.printf("Unable to transfer $%.2f. Balance is insufficient.\n",withdrawal);
}else if(withdrawal < 0){
System.out.println("Transfer amount must be greater than zero. Transfer failed.");
}else{
this.accountBal -= withdrawal;
System.out.printf("Transfer of $%.2f successful. Your new balance is $%.2f.\n",withdrawal,this.accountBal);
}
}
public void addFunds(double deposit){
if(deposit < 0){
System.out.println("Amount deposited must be greater than zero.");
}else {
this.accountBal += deposit;
System.out.printf("Deposit of $%.2f successful. Your new balance is $%.2f.\n",deposit,this.accountBal);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One advice I can give is to throw exceptions or return true/false from methods in <code>Account</code> class to that the client (in your case main class) could take the necessary action. The problem I see here is the <code>Account</code> class prints some texts that are displayed to user. Obviously, this is not <code>Account</code> class' job.</p>\n\n<p>Secondly, there are too many lines of code in your main method which makes me think that you should create a class/methods and distribute the work accordingly at first glance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T13:55:37.767",
"Id": "242004",
"ParentId": "241997",
"Score": "4"
}
},
{
"body": "<h2>Naming</h2>\n\n<ul>\n<li>Even though this is only an example application you should use proper names\n<code>public class Main</code> could have a far better name, maybe think of <code>public class ExerciseObjectManipulation</code>. You can find such classes later much easier in your SCM</li>\n<li>Avoid redundancy in your variables, for example <code>Account.accountName</code> and <code>Account.accountBal</code>. That gives you the chance for proper naming of <code>Account.accountBal</code> into <code>Account.balance</code> (also: avoid abbreviations in namings)</li>\n<li>same applies for these method names <code>getAccountName</code>and <code>getAccountBal</code></li>\n</ul>\n\n<h2>Seperation of concerns</h2>\n\n<ul>\n<li>your main method is responisble for printing, inputhandling and program flow - maybe you could use separate methods (or even: separate objects) for these responsibilities? Did you realize that you already started doing that by creating a methode <code>printMainMenu()</code> i'm sure you could find some more responsibilities for a <code>class Printer</code>?!!</li>\n<li>provide a Constructor for <code>Account</code> without balance <code>public Account(String name, double balance) { this(name,0);}</code> to create Accounts without balance.</li>\n</ul>\n\n<h2>error handling</h2>\n\n<ul>\n<li>it's nice that you write your concerns into the <code>System.out</code> (even if it would be more approperiate to write to <code>System.error</code> - but the proper way to do it would be to throw an <code>Exception</code>! right now it is possible to create an <code>Account</code> with negative balance even if then not all attributes are set - this is terrible, you create an unfinished object!</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>public Account(String name, double balance) {\n if(accountBal < 0) {\n throw new IllegalArgumentException(\"Starting balance cannot be less than zero\");\n }\n this.name = name;\n this.balance = balance;\n}\n</code></pre>\n\n<ul>\n<li>use this approach for any invalid parameters you get, see <code>transferFunds()</code>, see <code>addFunds()</code></li>\n</ul>\n\n<h2>logic flaws</h2>\n\n<pre><code>if(deposit < 0){\n System.out.println(\"Amount deposited must be greater than zero.\");\n}\n</code></pre>\n\n<p>either <code>deposit <= 0</code> or <code>cannot be less than zero.</code></p>\n\n<p>same here: <code>if(withdrawal < 0)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T08:44:21.407",
"Id": "242323",
"ParentId": "241997",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242323",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T11:57:00.400",
"Id": "241997",
"Score": "3",
"Tags": [
"java",
"object-oriented"
],
"Title": "Simple Banking Program - OOP Principles in Java 11"
}
|
241997
|
<p>This Flask app, which makes use of SQLAlchemy, a MySQL server which is only reachable via SSH and Flask-Login, is the base on which I want to write an application which has login protected pages.</p>
<p>Registering users is a feature that I still have to write in a better way, but it works for now and testing purposes.</p>
<p>I'm posting this here because I want to be a 100% sure that my application is safe. I'm really curious to hear where I can improve, or if my application is reasonably safe. Cheers!</p>
<pre><code>from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_login import login_required, login_user, current_user, UserMixin, logout_user
from pathlib import Path
from sshtunnel import SSHTunnelForwarder
import re
import paramiko
import bcrypt
SSH_IP = "example.com"
SSH_PORT = 32452
SSH_USER = "ssh_user_here"
SSH_KEY = paramiko.RSAKey.from_private_key_file(Path(r'filepath\key.key'))
SSH_REMOTE_BIND_IP = "127.0.0.1"
SSH_REMOTE_BIND_PORT = 3306
DB_IP = "127.0.0.1"
DB_USER = "db_username"
DB_PASSWORD = "db_password"
app = Flask(__name__)
app.secret_key = 'randomly generated string'
wsgi_app = app.wsgi_app
login_manager = LoginManager()
login_manager.init_app(app)
#Defines to which page the user is redirected when it's trying to reach a protected page
login_manager.login_view = 'Login'
#Start SSH tunnel so app is able to connect to database
tunnel = SSHTunnelForwarder(
(SSH_IP, SSH_PORT),
ssh_username=SSH_USER,
ssh_pkey=SSH_KEY,
remote_bind_address=(SSH_REMOTE_BIND_IP, SSH_REMOTE_BIND_PORT))
tunnel.start()
#Connect to the actual database
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://' + DB_USER + ':' + DB_PASSWORD + '@' + DB_IP +':' + str(tunnel.local_bind_port)+'/' + "database name"
db = SQLAlchemy(app)
class User(UserMixin, db.Model):
__tablename__ = 'Login'
email = db.Column(db.String(200), unique=True, nullable=False, primary_key=True)
password = db.Column(db.String(500))
def get_id(self):
return str(self.email)
def check_password(self, password):
return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))
@login_manager.user_loader
def load_user(email):
return User.query.filter_by(email=email).first()
def create_user(email, password):
password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
password = password.decode('utf-8')
new_user = User(email=email, password=password)
db.session.add(new_user)
db.session.commit()
return
@app.route('/')
@login_required
def index():
return render_template('index.html', current_user=current_user.email)
@app.route('/login', methods=['GET', 'POST'])
def login():
#create_user("test@test.com", "testpassword123")
# If the user is already logged in, redirect to index
if current_user.is_authenticated:
return redirect(url_for('index'))
# Check if all the fields are filled in
if request.method == 'POST' and 'email' in request.form and 'password' in request.form:
email = request.form['email']
password = request.form['password']
# Check if email is valid.
if re.match(r'[^@]+@[^@]+\.[^@]+', email):
user = User.query.filter_by(email=email).first()
if user and user.check_password(password):
login_user(user)
return redirect(url_for('index'))
else:
return render_template('login.html', msg="Unknown email//password combination entered!")
else:
return render_template('login.html', msg='Please enter a valid e-mail address' )
else:
return render_template('login.html', msg='Please fill in the form!')
return render_template('login.html', msg="")
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T16:28:10.900",
"Id": "474944",
"Score": "0",
"body": "How do you plan to load the configuration for db/ssh on production? Will you pass environment variables or override the values on the file"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:17:57.327",
"Id": "241999",
"Score": "2",
"Tags": [
"python",
"mysql",
"security",
"flask",
"sqlalchemy"
],
"Title": "Basic flask template with sessions"
}
|
241999
|
<p>I have a stored procedure the every 5 min run in sqlserver
high cost iO/cpu
do you have any idea to tune this query </p>
<pre><code>ALTER PROCEDURE [dbo].[doc_Letters_SyncBulkUpdate]
@TrackerStatusSync BIT
AS
UPDATE doc_Letters SET
[CentralDeptNo] = tempLetters.[CentralDeptNo],
[IncomingNo] = tempLetters.[IncomingNo],
[IncomingDate] = tempLetters.[IncomingDate],
[SequenceNo] = tempLetters.[SequenceNo],
[Subject] = tempLetters.[Subject],
[Summary] = tempLetters.[Summary],
[Keywords] = tempLetters.[Keywords],
[DeliverFrom] = tempLetters.[DeliverFrom],
[DeliverTo] = tempLetters.[DeliverTo],
[DeliverDate] = tempLetters.[DeliverDate],
[DeliverComments] = tempLetters.[DeliverComments],
[SourceFlag] = tempLetters.[SourceFlag],
[Type] = tempLetters.[Type],
[LetterNo] = tempLetters.[LetterNo],
[Security] = tempLetters.[Security],
[LetterType] = tempLetters.[LetterType],
[Indicator] = tempLetters.[Indicator],
[AttachmentCount] = tempLetters.[AttachmentCount],
[BodyFileCount] = tempLetters.[BodyFileCount],
[WordDocCount] = tempLetters.[WordDocCount],
[SenderTitle] = tempLetters.[SenderTitle],
[ToReceiverList] = tempLetters.[ToReceiverList],
[Date] = tempLetters.[Date],
[PartitionFactor] = tempLetters.[PartitionFactor],
[Priority] = tempLetters.[Priority],
[RegisterarUserFullName] = tempLetters.[RegisterarUserFullName],
[RegisterationDate] = tempLetters.[RegisterationDate],
[Archived] = tempLetters.[Archived],
[ModificationServerGuid] = tempLetters.[ModificationServerGuid],
[ModificationDate] = tempLetters.[ModificationDate],
[Age] = tempLetters.[Age],
DelivererCellPhone=tempLetters.DelivererCellPhone,
TrackingStatusID=
CASE
WHEN @TrackerStatusSync = 1 THEN doc_Letters.TrackingStatusID
ELSE tempLetters.[TrackingStatusID]
END
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[SecurityID] = security.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_SecurityLevels security ON security.[Guid] = tempLetters.[SecurityGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[LetterTypeID] = letterType.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_Permanents letterType ON letterType.[Guid] = tempLetters.[LetterTypeGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[IndicatorID] = indicators.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
doc_Indicators indicators ON indicators.[Guid] = tempLetters.[IndicatorGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[SecretarialID] = secretarials.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_Departments secretarials ON secretarials.[Guid] = tempLetters.[SecretarialGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[PriorityID] = priority.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_Priorities priority ON priority.[Guid] = tempLetters.[PriorityGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[RegisterarUserID] = users.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_Users users ON users.[Guid] = tempLetters.[RegisterarUserGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
IF(@TrackerStatusSync=1)
BEGIN
UPDATE doc_Letters SET
[TrackingStatusID] = trackers.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_TrackerStatuses trackers ON trackers.[Guid] = tempLetters.[TrackingStatusGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
END
UPDATE doc_Letters SET
[FirstRootInstanceOwnerID] = staff.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_Staff staff ON staff.[Guid] = tempLetters.[FirstRootInstanceOwnerGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[FirstRootInstanceOwnerSecretarialID] = firstRootInstanceOwnerSecretarial.[ID]
FROM
doc_Letters INNER JOIN
doc_LettersSyncTemp tempLetters ON tempLetters.[Guid] = doc_Letters.[Guid] INNER JOIN
com_Departments firstRootInstanceOwnerSecretarial ON firstRootInstanceOwnerSecretarial.[Guid] = tempLetters.[FirstRootInstanceOwnerSecretarialGuid]
WHERE
tempLetters.[Age] >= doc_Letters.[Age]
UPDATE doc_Letters SET
[FirstRootInstanceID] = ISNULL(firstRootInstance.[ID], 0)
FROM
doc_Letters letters INNER JOIN
doc_LettersSyncTemp tempLetters ON letters.[Guid] = tempLetters.[Guid] LEFT JOIN
doc_LetterInstances firstRootInstance ON firstRootInstance.[Guid] = tempLetters.[FirstRootInstanceGuid]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T07:14:55.080",
"Id": "475390",
"Score": "0",
"body": "A good start would be Database Engine Tuning Advisor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T01:03:58.453",
"Id": "478225",
"Score": "0",
"body": "please post `doc_Letters` table schema. We need to know the columns."
}
] |
[
{
"body": "<p>It seems you need a view or a temporary table. But it would be best for you to use a view instead. \nso you might need to create a view first : </p>\n\n<pre><code>CREATE VIEW doc_Letters_view AS \n(\n SELECT \n [CentralDeptNo] = tempLetters.[CentralDeptNo]\n , [IncomingNo] = tempLetters.[IncomingNo]\n , [IncomingDate] = tempLetters.[IncomingDate]\n , [SequenceNo] = tempLetters.[SequenceNo]\n , [Subject] = tempLetters.[Subject]\n , [Summary] = tempLetters.[Summary]\n , [Keywords] = tempLetters.[Keywords]\n , [DeliverFrom] = tempLetters.[DeliverFrom]\n , [DeliverTo] = tempLetters.[DeliverTo]\n , [DeliverDate] = tempLetters.[DeliverDate]\n , [DeliverComments] = tempLetters.[DeliverComments]\n , [SourceFlag] = tempLetters.[SourceFlag]\n , [Type] = tempLetters.[Type]\n , [LetterNo] = tempLetters.[LetterNo]\n , [Security] = tempLetters.[Security]\n , [LetterType] = tempLetters.[LetterType]\n , [Indicator] = tempLetters.[Indicator]\n , [AttachmentCount] = tempLetters.[AttachmentCount]\n , [BodyFileCount] = tempLetters.[BodyFileCount]\n , [WordDocCount] = tempLetters.[WordDocCount]\n , [SenderTitle] = tempLetters.[SenderTitle]\n , [ToReceiverList] = tempLetters.[ToReceiverList]\n , [Date] = tempLetters.[Date]\n , [PartitionFactor] = tempLetters.[PartitionFactor]\n , [Priority] = tempLetters.[Priority]\n , [RegisterarUserFullName] = tempLetters.[RegisterarUserFullName]\n , [RegisterationDate] = tempLetters.[RegisterationDate]\n , [Archived] = tempLetters.[Archived]\n , [ModificationServerGuid] = tempLetters.[ModificationServerGuid]\n , [ModificationDate] = tempLetters.[ModificationDate]\n , [Age] = tempLetters.[Age]\n , DelivererCellPhone = tempLetters.DelivererCellPhone\n , TrackingStatusID = tempLetters.[TrackingStatusID]\n , [SecurityID] = security.[ID]\n , [LetterTypeID] = letterType.[ID]\n , [IndicatorID] = indicators.[ID]\n , [SecretarialID] = secretarials.[ID]\n , [PriorityID] = priority.[ID]\n , [RegisterarUserID] = users.[ID]\n , [FirstRootInstanceOwnerID] = staff.[ID]\n , [FirstRootInstanceOwnerSecretarialID] = firstRootInstanceOwnerSecretarial.[ID]\n , [FirstRootInstanceID] = ISNULL(firstRootInstance.[ID], 0\n , [Age] = tempLetters.[Age]\n , [Guid] = tempLetters.[Guid]\n FROM \n doc_LettersSyncTemp tempLetters\n LEFT JOIN com_SecurityLevels security ON security.[Guid] = tempLetters.[SecurityGuid]\n LEFT JOIN com_Permanents letterType ON letterType.[Guid] = tempLetters.[LetterTypeGuid]\n LEFT JOIN doc_Indicators indicators ON indicators.[Guid] = tempLetters.[IndicatorGuid]\n LEFT JOIN com_Departments secretarials ON secretarials.[Guid] = tempLetters.[SecretarialGuid]\n LEFT JOIN com_Priorities priority ON priority.[Guid] = tempLetters.[PriorityGuid]\n LEFT JOIN com_Users users ON users.[Guid] = tempLetters.[RegisterarUserGuid]\n LEFT JOIN com_TrackerStatuses trackers ON trackers.[Guid] = tempLetters.[TrackingStatusGuid]\n LEFT JOIN com_Staff staff ON staff.[Guid] = tempLetters.[FirstRootInstanceOwnerGuid]\n LEFT JOIN com_Departments firstRootInstanceOwnerSecretarial ON firstRootInstanceOwnerSecretarial.[Guid] = tempLetters.[FirstRootInstanceOwnerSecretarialGuid]\n LEFT JOIN doc_LetterInstances firstRootInstance ON firstRootInstance.[Guid] = tempLetters.[FirstRootInstanceGuid]\n)\n</code></pre>\n\n<p>Then use it in your store procedure, so your store procedure would be something like : </p>\n\n<pre><code>UPDATE doc_Letters\nSET \n [CentralDeptNo] = doc_Letters_view.[CentralDeptNo]\n, [IncomingNo] = doc_Letters_view.[IncomingNo]\n, [IncomingDate] = doc_Letters_view.[IncomingDate]\n, [SequenceNo] = doc_Letters_view.[SequenceNo]\n, [Subject] = doc_Letters_view.[Subject]\n, [Summary] = doc_Letters_view.[Summary]\n, [Keywords] = doc_Letters_view.[Keywords]\n, [DeliverFrom] = doc_Letters_view.[DeliverFrom]\n, [DeliverTo] = doc_Letters_view.[DeliverTo]\n, [DeliverDate] = doc_Letters_view.[DeliverDate]\n, [DeliverComments] = doc_Letters_view.[DeliverComments]\n, [SourceFlag] = doc_Letters_view.[SourceFlag]\n, [Type] = doc_Letters_view.[Type]\n, [LetterNo] = doc_Letters_view.[LetterNo]\n, [Security] = doc_Letters_view.[Security]\n, [LetterType] = doc_Letters_view.[LetterType]\n, [Indicator] = doc_Letters_view.[Indicator]\n, [AttachmentCount] = doc_Letters_view.[AttachmentCount]\n, [BodyFileCount] = doc_Letters_view.[BodyFileCount]\n, [WordDocCount] = doc_Letters_view.[WordDocCount]\n, [SenderTitle] = doc_Letters_view.[SenderTitle]\n, [ToReceiverList] = doc_Letters_view.[ToReceiverList]\n, [Date] = doc_Letters_view.[Date]\n, [PartitionFactor] = doc_Letters_view.[PartitionFactor]\n, [Priority] = doc_Letters_view.[Priority]\n, [RegisterarUserFullName] = doc_Letters_view.[RegisterarUserFullName]\n, [RegisterationDate] = doc_Letters_view.[RegisterationDate]\n, [Archived] = doc_Letters_view.[Archived]\n, [ModificationServerGuid] = doc_Letters_view.[ModificationServerGuid]\n, [ModificationDate] = doc_Letters_view.[ModificationDate]\n, [Age] = doc_Letters_view.[Age]\n, DelivererCellPhone = doc_Letters_view.DelivererCellPhone\n, TrackingStatusID = CASE WHEN @TrackerStatusSync = 1 THEN doc_Letters_view.[TrackingStatusID] ELSE doc_Letters.[TrackingStatusID] END\n, [SecurityID] = doc_Letters_view.[SecurityID]\n, [LetterTypeID] = doc_Letters_view.[LetterTypeID]\n, [IndicatorID] = doc_Letters_view.[IndicatorID]\n, [SecretarialID] = doc_Letters_view.[SecretarialID]\n, [PriorityID] = doc_Letters_view.[PriorityID]\n, [RegisterarUserID] = doc_Letters_view.[RegisterarUserID]\n, [FirstRootInstanceOwnerID] = doc_Letters_view.[FirstRootInstanceOwnerID]\n, [FirstRootInstanceOwnerSecretarialID] = doc_Letters_view.[FirstRootInstanceOwnerSecretarialID]\n, [FirstRootInstanceID] = doc_Letters_view.[FirstRootInstanceID]\nFROM \n doc_Letters\nJOIN doc_Letters_view ON doc_Letters_view.[Guid] = doc_Letters.[Guid]\nWHERE \n doc_Letters_view.[Age] >= doc_Letters.[Age]\n</code></pre>\n\n<p>A few other notes to optimize it, when using Views, you're taking advantage of the view's statistics to get the best possible execution plan. This is not enough though, you'll need to create indexes on <code>Age</code> and also another on <code>Guid</code> for <code>doc_Letters</code> and <code>doc_LettersSyncTemp</code> tables, and include all needed columns.</p>\n\n<p>Another thought, if you can avoid the <code>UPDATE</code> and depend on the view instead, do that, it would be faster. As you're clearly only need a view to show the the record status based on <code>Age</code> which either an integer or datetime. So, you're updating it every 5 minutes !, while if you used a view, it would give you the same results, but there is no <code>UPDATE</code> action on the main table. Which would be faster!. </p>\n\n<p>You can also use computed columns, which are some what partial views, these would be updated every time you query the table. The only disadvantage on that and on the view, is that the values are not stored since they will be updated on each time you querying it. It would be feasible to apply it on status columns, but it's not a good solution for data that meant to be stored, and logged when there is an update like user information or financial data. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T02:33:31.753",
"Id": "243643",
"ParentId": "242001",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T12:54:40.047",
"Id": "242001",
"Score": "2",
"Tags": [
"performance",
"sql-server",
"database",
"stored-procedure"
],
"Title": "Performance stored procedure update multi-coulmn sql"
}
|
242001
|
<p>I'm beginner in rust.
I would ask code review of my finite state machine.
Main feature :</p>
<ul>
<li>static (event, state and transition)</li>
<li>support pushdown </li>
</ul>
<p>It is the first step, second step is to use macro for generate section.</p>
<p>In my example i have 3 events (e1, e2, e3), 4 states (red, green, blue , rainbow). There are 4 type of transitions :</p>
<ul>
<li>Move to other state with or without save origin state</li>
<li>None to stay on same State</li>
<li>Pop to restore the last save state</li>
<li>Invalid to say invalid event on the state</li>
</ul>
<p>static code :</p>
<pre><code>use std::marker::PhantomData;
/**
* Static
*/
#[derive(Debug, Copy, Clone)]
enum Transition<S> {
None,
Invalid,
Move(S, bool),
Pop,
}
trait StateAction<E, S> {
fn push(&mut self, event: E) -> Transition<S>;
}
trait StateManager<E, S> {
fn get_state(&mut self, state: S) -> &mut dyn StateAction<E, S>;
}
struct StateMachine<M, E, S>
where
M: StateManager<E, S>,
S: Copy,
E: Copy,
{
manager: M,
current: S,
pop_state: Vec<S>,
phantom: PhantomData<E>,
}
impl<M, E, S> StateMachine<M, E, S>
where
M: StateManager<E, S>,
S: Copy,
E: Copy,
{
fn new(manager: M, state: S) -> Self {
Self {
manager: manager,
current: state,
pop_state: Vec::new(),
phantom: PhantomData,
}
}
fn push(&mut self, event: E) -> Transition<S> {
let current_state = self.manager.get_state(self.current);
let mut transition = current_state.push(event);
match transition {
Transition::Move(new_state, push) => {
if push {
self.pop_state.push(self.current);
}
self.current = new_state;
}
Transition::Pop => {
match self.pop_state.pop() {
Some(new_state) => {
self.current = new_state;
transition = Transition::Move(new_state, false);
},
None => panic!("invalid pop"),
}
}
_ => {}
}
transition
}
}
</code></pre>
<p>generated code :</p>
<pre><code>#[derive(Debug, Copy, Clone)]
enum Event {
E1,
E2,
E3,
}
#[derive(Debug, Copy, Clone)]
enum State {
Green,
Red,
Blue,
Rainbow,
}
struct GreenState;
impl GreenState {
fn new() -> Self {
Self {}
}
}
impl StateAction<Event, State> for GreenState {
fn push(&mut self, event: Event) -> Transition<State> {
match event {
Event::E1 => Transition::Move(State::Red, false),
Event::E2 => Transition::Move(State::Blue, false),
Event::E3 => Transition::Move(State::Rainbow, true),
}
}
}
struct RedState;
impl RedState {
fn new() -> Self {
Self {}
}
}
impl StateAction<Event, State> for RedState {
fn push(&mut self, event: Event) -> Transition<State> {
match event {
Event::E1 => Transition::Move(State::Rainbow, true),
Event::E2 => Transition::Move(State::Blue, false),
Event::E3 => Transition::Move(State::Green, false),
}
}
}
struct BlueState;
impl BlueState {
fn new() -> Self {
Self {}
}
}
impl StateAction<Event, State> for BlueState {
fn push(&mut self, event: Event) -> Transition<State> {
match event {
Event::E1 => Transition::Move(State::Red, false),
Event::E2 => Transition::Move(State::Rainbow, true),
Event::E3 => Transition::Move(State::Green, false),
}
}
}
struct RainbowState;
impl RainbowState {
fn new() -> Self {
Self {}
}
}
impl StateAction<Event, State> for RainbowState {
fn push(&mut self, event: Event) -> Transition<State> {
match event {
Event::E1 => Transition::Pop,
Event::E2 => Transition::None,
Event::E3 => Transition::Invalid,
}
}
}
struct StateManagerImpl {
states: (GreenState, RedState, BlueState, RainbowState),
}
impl StateManagerImpl {
fn new() -> Self {
Self {
states: (
GreenState::new(),
RedState::new(),
BlueState::new(),
RainbowState::new(),
),
}
}
}
impl StateManager<Event, State> for StateManagerImpl {
fn get_state(&mut self, state: State) -> &mut dyn StateAction<Event, State> {
match state {
State::Green => &mut self.states.0,
State::Red => &mut self.states.1,
State::Blue => &mut self.states.2,
State::Rainbow => &mut self.states.3,
}
}
}
</code></pre>
<p>Example :</p>
<pre><code>fn main() {
let manager = StateManagerImpl::new();
let mut sm = StateMachine::new(manager, State::Green);
{
// Green -> Red
let n = sm.push(Event::E1);
println!("after e1 {:?}", n);
}
{
// Red -> Blue
let n = sm.push(Event::E2);
println!("after e2 {:?}", n);
}
{
// Blue -> Rainbow
let n = sm.push(Event::E2);
println!("after e2 {:?}", n);
}
{
// Rainbow (stay)
let n = sm.push(Event::E2);
println!("after e2 {:?}", n);
}
{
// Rainbow (error)
let n = sm.push(Event::E3);
println!("after e3 {:?}", n);
}
{
// Rainbow/Pop -> Blue
let n = sm.push(Event::E1);
println!("after e3 {:?}", n);
}
}
</code></pre>
<p>the output:</p>
<pre><code>after e1 Move(Red, false)
after e2 Move(Blue, false)
after e2 Move(Rainbow, true)
after e2 None
after e3 Invalid
after e3 Move(Blue, false)
</code></pre>
<p>what do you think ?</p>
<p>Thanks
Etienne</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T16:33:24.117",
"Id": "474945",
"Score": "1",
"body": "Welcome to Code Review. Can you tell usorr about the purpose of your goal? I'm familiar with FSMs, but what prompted you to write this one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T16:57:08.850",
"Id": "474946",
"Score": "0",
"body": "My goal is the world domination but in the first time i want to learn rust and made a little game... but i'm not sure to understand your question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T20:24:58.433",
"Id": "474954",
"Score": "2",
"body": "What I'm trying to ask for, considering code rarely stands on itself, is what prompted you to write this. This helps in understanding why you made certain decisions and what kind of advice you're actually looking for. A beginner requires different answers than an expert, we try to facilitate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T08:26:22.890",
"Id": "474985",
"Score": "0",
"body": "I have lot of experience in programming (c++) but 1) i'm beginner in rust (so i need feedback about my code about perf/useless copy/ rust writing style 2) it is first time i write a FSM, so i would want feedback about my api ..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T14:58:03.347",
"Id": "242007",
"Score": "1",
"Tags": [
"beginner",
"rust",
"state-machine"
],
"Title": "Finite State Machine"
}
|
242007
|
<p>I recently had a need to convert a TrueType font to a Game Boy tileset, so I wrote a program to do it.</p>
<p>This correctly aligns the characters on an 8x8 plane and outputs in the form of RGBDS-style GBZ80 assembly.</p>
<p>Needs the FreeType library installed; use the Makefile (or copy the commands) to compile it.</p>
<p><code>drawtile.c</code>:</p>
<pre><code>/*
* Copyright © 2020 James Larrowe
*
* This file is part of ttf2gb.
*
* ttf2gb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ttf2gb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ttf2gb. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "ttf2gb.h"
#include <ft2build.h>
#include FT_FREETYPE_H /* FT_FaceRec, FT_GlyphSlotRec */
#include FT_IMAGE_H /* FT_BBox, FT_Bitmap, FT_UShort, FT_Int */
/* assumes horizontal font */
void draw_tile(const FT_FaceRec *face)
{
FT_Int i, j;
FT_BBox box = face->bbox;
const FT_GlyphSlotRec *glyph = face->glyph;
const FT_Bitmap *bitmap = &glyph->bitmap;
const FT_UShort hEM = face->units_per_EM / bitmap->width;
const FT_UShort vEM = face->units_per_EM / bitmap->rows;
box.xMin /= hEM;
box.xMax /= hEM;
box.yMin /= vEM;
box.yMax /= vEM;
#ifndef NDEBUG
fprintf(stderr, "rows:%u, width:%u\n", bitmap->rows, bitmap->width);
fprintf(stderr, "top:%u, left:%u\n", glyph->bitmap_top, glyph->bitmap_left);
fprintf(stderr, "horizontal units per EM:%hu, vertical:%hu\n", hEM, vEM);
fprintf(stderr, "xmin:%ld, xmax:%ld\n", box.xMin, box.xMax);
fprintf(stderr, "ymin:%ld, ymax:%ld\n", box.yMin, box.yMax);
#endif
for (i = 0; i < box.yMax - glyph->bitmap_top; i++) {
fputs("\tDW `", stdout);
for (j = box.xMin; j < box.xMax; j++)
putchar('0');
putchar('\n');
}
for (i = 0; i < (FT_Int)bitmap->rows; i++) {
fputs("\tDW `", stdout);
for (j = box.xMin; j < glyph->bitmap_left; j++)
putchar('0');
for (j = 0; j < (FT_Int)bitmap->width; j++)
putchar(bitmap->buffer[i * bitmap->width + j] ? '3' : '0');
for (j = box.xMin + glyph->bitmap_left + bitmap->width; j < box.xMax; j++)
putchar('0');
putchar('\n');
}
for (i = box.yMin; i < glyph->bitmap_top - (FT_Int)bitmap->rows; i++) {
fputs("\tDW `", stdout);
for (j = box.xMin; j < box.xMax; j++)
putchar('0');
putchar('\n');
}
putchar('\n');
}
</code></pre>
<p><code>Makefile</code>:</p>
<pre><code>#########################################################################
# Copyright © 2020 James Larrowe #
# #
# This file is part of ttf2gb. #
# #
# ttf2gb is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# ttf2gb is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with ttf2gb. If not, see <https://www.gnu.org/licenses/>. #
#########################################################################
.POSIX:
# variables to be set by the user
CC = gcc
CFLAGS =
LDFLAGS =
PKG_CONFIG = pkg-config
# variables to be set by the maintainer
BUILD = RELEASE
DEBUG_OPTFLAGS = -g3
RELEASE_OPTFLAGS = -O3 -DNDEBUG
WARNFLAGS = -Wall -Wextra -std=c89 -pedantic
FT_CFLAGS = `$(PKG_CONFIG) --cflags freetype2`
FT_LDFLAGS = `$(PKG_CONFIG) --libs freetype2`
REAL_CFLAGS = $($(BUILD)_OPTFLAGS) $(WARNFLAGS) $(FT_CFLAGS) $(CFLAGS)
REAL_LDFLAGS = $(REAL_CFLAGS) $(FT_LDFLAGS) $(LDFLAGS)
OBJ = main.o utils.o drawtile.o
ttf2gb: $(OBJ)
$(CC) $(REAL_LDFLAGS) -o $@ $(OBJ)
.c.o:
$(CC) $(REAL_CFLAGS) -c -o $@ $<
clean:
rm -f ttf2gb $(OBJ)
</code></pre>
<p><code>ttf2gb.h</code>:</p>
<pre><code>/*
* Copyright © 2020 James Larrowe
*
* This file is part of ttf2gb.
*
* ttf2gb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ttf2gb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ttf2gb. If not, see <https://www.gnu.org/licenses/>.
*
*/
#ifndef TTF2GB_H_
#define TTF2GB_H_ 1
#include <ft2build.h>
#include FT_TYPES_H /* FT_Error */
#include FT_FREETYPE_H /* FT_FaceRec */
/* utils.c */
/* a strerror that works on FT_Error instead of errno */
const char *ftstrerror(FT_Error error);
/* a perror for an FT_Error */
void ftperror(const char *message, FT_Error error);
/* drawtile.c */
/* draw a tile to STDOUT as RGBDS-formatted assembly */
void draw_tile(const FT_FaceRec *face);
#endif
</code></pre>
<p><code>utils.c</code>:</p>
<pre><code>/*
* Copyright © 2020 James Larrowe
*
* This file is part of ttf2gb.
*
* ttf2gb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ttf2gb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ttf2gb. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "ttf2gb.h"
#include <ft2build.h>
#include FT_TYPES_H
const char *ftstrerror(FT_Error error)
{
#undef FTERRORS_H_
#define FT_ERRORDEF(error_code, value, string) case error_code: return string;
#define FT_ERROR_START_LIST switch(error) {
#define FT_ERROR_END_LIST default: return "Unknown error"; }
#include FT_ERRORS_H
}
void ftperror(const char *message, FT_Error error)
{
if(message)
fprintf(stderr, "%s: %s\n", message, ftstrerror(error));
else
fprintf(stderr, "%s\n", ftstrerror(error));
}
</code></pre>
<p>(Yes, I'm aware that this is now licensed under the CC-by-SA 4.0. Feel free to use it under that license, too.)</p>
<p>What I'm looking for:</p>
<ul>
<li><p>Is there a more "central" location that I can grab the dimensions from? I feel like I'm missing something, because I have to get them from the bounding box, the bitmap, and the glyph...</p></li>
<li><p>Is this good usage of the FreeType library? Can anything be simplified with respect to library functions and structures?</p></li>
<li><p>Are there any obscure edge cases I might've missed? This seems to generate correct results for the font I was trying to use but I didn't try it with any other fonts.</p></li>
<li><p>Any other general recommendations or advice would be appreciated.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T05:25:36.947",
"Id": "475116",
"Score": "0",
"body": "Why does code use `FT_Int i ... for (i = 0; i < (FT_Int)bitmap->rows; i++) {` vs the type that matches `bitmap->rows`? Curious that `for (j = box.xMin; j < glyph->bitmap_left; j++)` employs no similar cast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T13:46:04.923",
"Id": "475159",
"Score": "0",
"body": "@chux The types of `rows` and `bitmap_left` are different. `rows` is unsigned and `bitmap_left` is signed. I figured giving myself a signed counter would make it the easiest for me if I ever needed vertical fonts."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T15:48:58.350",
"Id": "242008",
"Score": "1",
"Tags": [
"c",
"converting",
"freetype"
],
"Title": "Convert a TrueType font to a Game Boy tileset"
}
|
242008
|
<p>I'm newly exploring time series databases, and trying to wrap my head around what data I'll store and how I'll query it. Also, I'm relatively new to TypeScript. This prototype exercises my current understanding of how it will work.</p>
<p>What I most want feedback on is:</p>
<ul>
<li><p>TypeScript idioms: am I following them? Does anything I'm doing stick out like a sore thumb?</p></li>
<li><p>Am I properly representing this in a way analogous to a time-series database? (TimescaleDB is the one I'm eyeing, if it matters.)</p></li>
</ul>
<pre><code>namespace Position {
export enum State {
BuyingToOpen,
SellingToOpen,
Open,
BuyingToClose,
SellingToClose,
Closed,
};
export namespace State {
export type Transition = OrderPlacementTransition | OrderFillTransition;
export interface OrderPlacementTransition extends TransitionBase {
newState: Opening | Closing;
orderId: string;
}
export type Opening = State.BuyingToOpen | State.SellingToOpen;
export type Closing = State.BuyingToClose | State.SellingToClose;
export interface OrderFillTransition extends TransitionBase {
newState: State.Open | State.Closed;
}
interface TransitionBase {
timestamp: number;
positionId: string;
newState: State;
affectedAsset: string;
affectedAssetDelta: number;
}
}
}
const positionHistory: Position.State.Transition[] = [
{
// placed an order to spend $500 on 2,500 ZRX
timestamp: 0,
positionId: '0',
newState: Position.State.BuyingToOpen,
orderId: 'A',
affectedAsset: 'USD',
affectedAssetDelta: -500,
},
{
// order to spend $500 has been filled, we now hold 2,500 more ZRX
timestamp: 1,
positionId: '0',
newState: Position.State.Open,
affectedAsset: 'ZRX',
affectedAssetDelta: +2500,
},
{
// placed an order to sell that 2,500 ZRX
timestamp: 2,
positionId: '0',
newState: Position.State.SellingToClose,
orderId: 'B',
affectedAsset: 'ZRX',
affectedAssetDelta: -2500,
},
{
// order to sell 2,500 ZRX for $505 has been filled
timestamp: 3,
positionId: '0',
newState: Position.State.Closed,
affectedAsset: 'USD',
affectedAssetDelta: +505,
},
];
type ProfitOrLoss = { [asset: string]: number };
console.log(
positionHistory.reduce<ProfitOrLoss>(
(profitOrLoss, historyElement) => {
profitOrLoss[historyElement.affectedAsset] = (
(profitOrLoss[historyElement.affectedAsset] || 0)
+ historyElement.affectedAssetDelta
);
return profitOrLoss;
},
{},
),
);
</code></pre>
<p>Result:</p>
<pre><code>{
"USD": 5,
"ZRX": 0
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T16:07:08.983",
"Id": "242009",
"Score": "4",
"Tags": [
"typescript",
"finance"
],
"Title": "Model profit/loss of a time series of financial position state changes"
}
|
242009
|
<p>I am calculating the log-likelihood of data that have some observations censored. For uncensored "a" clusters, the likelihood calculates P(Y=y). For censored "b" clusters, it calculates that Y is <em>at least</em> size Y, P(Y≥y). So the likelihood is L=mult[P(Y=y)P(Y≥y)]. </p>
<p>The below code is my working, actual-in-use code that calculates this log likelihood based on censorship status. However, when in place with several other functions, it is extremely slow since it has to iterate through each row in the dataset (datasets are usually several thousand rows long, and maximization runs through several thousands of iterations of R and k values).</p>
<p>My hope is that someone will know of an alternative way to approach this that will increase performance. I am (obviously) not an expert coder. </p>
<pre><code>new_likelihood <- function(Y,R,k) {
p_function <- function(y,n){ #Create a dummy function to use in for loop
exp(log(n)-log(y)+lgamma(k*y+y-n)-(lgamma(k*y)+lgamma(y-n+1))+(y-n)*log(R/k)-(k*y+y-n)*log(1+R/k))
}
liks_a <- numeric(nrow(Y)) # initialize vector of logliks for `a` clusters
liks_b <- numeric(nrow(Y)) # initialize vector of logliks for `b` clusters
#Loop through each row of the data
for(i in 1:nrow(Y)){
y <- Y[i,1]
n <- Y[i,2]
c <- Y[i,3]
if (c==0){ #For uncensored, apply regular PDF
liks_a[i] <- log(p_function(y,n))
} #outputs a value of 0 in liks_a[i] if c=1, so doesnt affect sum(log(liks))
if(c==1){ #for censored, sum to do 1-(sum(Y-1))
liks_b[i] <- log(1-sum(p_function(1:(y-1),n)))
} #outputs a value of 0 if in liks_b[i] if c=0, so doesnt affect sum(log(liks))
}
sumliks <- sum(liks_a,liks_b)
return(sumliks)
}
# Example data
Y_censor0 <- cbind(c(3,2,2,10,1,1),c(1,1,1,1,1,1),c(0,0,0,0,0,0)) # 3-column data w/ no one censored
Y_censor1 <- cbind(c(3,2,2,10,1,1),c(1,1,1,1,1,1),c(0,0,1,1,0,0)) # 3-column data with some censored
# Test
new_likelihood(Y_censor0,0.9,0.25)
new_likelihood(Y_censor1,0.9,0.25)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Your function <code>p_function</code> is vectorized and that is nice. There's a little difficulty for the sum though.</p>\n<p>Below is the improved code that takes advantage of the vectorization. I also replaced <code>log(1+x)</code> with <code>log1p(x)</code>, which is better for a small <code>|x|</code>. And I replaced the stuff with the <code>lgamma</code> functions with some stuff with the <code>lbeta</code> function.</p>\n<pre><code>new_likelihood2 <- function(Y, R, k) {\n\n p_function <- function(y, n){ \n exp(log(n) - log(y) - lbeta(k*y, y-n+1) - log(k*y+y-n) + (y-n)*log(R/k) - (k*y+y-n)*log1p(R/k))\n }\n \n p_function_sum <- function(y, n){\n vapply(\n seq_along(y), function(i) sum(p_function(1:(y[i]-1), n[i])), numeric(1)\n )\n }\n \n uncensored <- Y[, 3] == 0\n Yuncensored <- Y[uncensored, 1:2]\n Ycensored <- Y[!uncensored, 1:2]\n liks_a <- log(p_function(Yuncensored[, 1], Yuncensored[, 2]))\n liks_b <- log1p(-p_function_sum(Ycensored[, 1], Ycensored[, 2]))\n \n sum(liks_a, liks_b)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:43:06.273",
"Id": "252649",
"ParentId": "242011",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T17:17:11.967",
"Id": "242011",
"Score": "1",
"Tags": [
"performance",
"r"
],
"Title": "Log Likelihood Calculations for Censored Data in R"
}
|
242011
|
<p>My code passes 11 out of 12 test cases. I was wondering where I can improve my code. NOTE: This code needs performance improvement, as it is working for most of the cases. To mu knowledge it would work for all the test cases where the size of arrays is smaller than 200.</p>
<p>Here is the question:</p>
<blockquote>
<p>Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses Dense Ranking, so its leaderboard works like this:</p>
<p>The player with the highest score is ranked number 1 on the leaderboard.
Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.<br />
For example, the four players on the leaderboard have high scores of 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively. If Alice's scores are 70, 80 and 105, her rankings after each game are 4, 3 and 1.</p>
</blockquote>
<p>And here is my code:</p>
<pre><code>#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def binSearchMod(list1, value, start, end): #implemented for descending order
mid = (start+end)//2
#print('Looking for value: ', value, ' in ', start, end, mid , 'list :', list1)
#conditions for element at start or end or mid
if value==list1[start]:
mid = start
if value == list1[end]:
mid = end
if value == list1[mid]:
return [True, mid]
if end-start == 1: # if some element lies in between 2 numbers of array
#print('Found between ', start, end)
return [False, start]
if value < list1[mid]:
return binSearchMod(list1, value, mid, end)
else:
return binSearchMod(list1, value, start, mid)
def climbingLeaderboard(scores, alice): # O(log n), not really we have to go through all scores to determine their rank
res=[]
rank =1
rankScores=[scores[0]]
#ssign ranks to scores
for score in range(1,len(scores)):
if scores[score]!=scores[score-1]:
rank+=1
rankScores.append(scores[score])
for ascore in alice:
if ascore<scores[len(scores)-1]: # alice scores are smaller than all
res.append(len(set(scores))+1)
elif ascore > scores[0]: #alice score is greatest
res.append(1)
else: #alice score lies somewhere in between
bsResult = binSearchMod(rankScores, ascore, 0 , len(rankScores)-1)
#print(ascore, bsResult)
if bsResult[0]:
res.append(bsResult[1]+1)
else:
res.append(bsResult[1]+2)
return res
</code></pre>
<p>I am guessing I'm trying to improve on test cases with length of arrays containing all scores and alice scores are > 200.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T03:45:10.283",
"Id": "474973",
"Score": "1",
"body": "Welcome (again) to CodeReview@SE. You should probably move your assessment of correctness and execution time to the top of your post - if the result is incorrect, it is [not ready for review here](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T05:18:04.847",
"Id": "474975",
"Score": "0",
"body": "@greybeard, again, I do not understand how this question is off-topic. It seems on-topic for the same reasons as [here](https://codereview.stackexchange.com/questions/241925/runtime-error-in-minion-game-problem-hackerrank/241934#comment474762_241925)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T05:22:23.327",
"Id": "474976",
"Score": "1",
"body": "(@AlexPovel I suggested moving an assessment to an eye-catching place - to support assessments of suitability of this question for CodeReview@SE, too. FWIW, it hasn't been me voting to close.)"
}
] |
[
{
"body": "<p>You are on the right track. However, implementing your own bisection algorithm is not a good idea. Python has the built-in (\"batteries included\") <code>bisect</code> module, containing all the bisection algorithms we need.\n<a href=\"https://github.com/python/cpython/blob/master/Lib/bisect.py\" rel=\"nofollow noreferrer\">They are implemented in Python</a>, but overridden by fast C implementations if those are available, which would then be as fast as we can hope for.</p>\n\n<p>The <code>from bisect import bisect</code> (with the <code>bisect</code> function as an alias for <code>bisect_right</code>) replaces your <code>binSearchMod</code> function.\nIn the code at the bottom, there is a \"manual\" bisect implementation without recursion, which is also a step forward.\nIt is probably best to avoid recursion if (much) simpler means are available.</p>\n\n<p>In your base <code>climbingLeaderboard</code> function, you have</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if ascore<scores[len(scores)-1]: # alice scores are smaller than all\n res.append(len(set(scores))+1)\n elif ascore > scores[0]: #alice score is greatest\n res.append(1)\n</code></pre>\n\n<p>which handles special cases.\nThese cases are not special enough to warrant this, and are code smell.\nYour basic search algorithm should return correct results to append to <code>res</code> on its own, as we will see shortly.\nSee also <code>import this</code>: <em>Special cases aren't special enough to break the rules.</em>.</p>\n\n<p>As an aside, slicing (using <code>slice</code> objects) makes indexing sequences much easier: <code>scores[len(scores)-1]</code> is just <code>scores[-1]</code>.\nFurther, you return a list using</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return [False, start]\n</code></pre>\n\n<p>This is a bad idea.\nYou later use it to index into it, but that job can better be done by a <code>tuple</code>.\nSimply calling</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return False, start\n</code></pre>\n\n<p>will return a tuple.\nThis can be unpacked into two variables in one assignment, or indexed into just like lists.\nTuple unpacking is convenient and easy to read.</p>\n\n<p>The distinction between lists and tuples is important: lists are (should be) homogeneous, aka contain a sequence of elements of the same type (think filenames).\nTuples are <em>heterogeneous</em>, aka the position of elements has meaning and they are of different types.\nIn your example here, this would be <code>bool</code> and <code>int</code>, which have different semantics.</p>\n\n<hr>\n\n<p>A key aspect to realize is that duplicate scores in the leaderboard can just be tossed, since they do not count towards anything.\nThis calls for a <code>set</code> implementation.\nThis also automatically gets rids of your</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> #ssign ranks to scores\n for score in range(1,len(scores)):\n if scores[score]!=scores[score-1]:\n rank+=1\n rankScores.append(scores[score])\n</code></pre>\n\n<p>code block, saving a whole <span class=\"math-container\">\\$ \\mathcal{O} (n) \\$</span> iteration.</p>\n\n<p>Since <code>bisect</code> relies on <em>ascending</em> order, while the input is sorted in descending order, a call to <code>sorted</code> is required, which automatically returns a <code>list</code>.</p>\n\n<p><code>bisect(sequence, item)</code> will return the index where to insert <code>item</code> in <code>sequence</code> while retaining order.\nIf items compare equal, <code>item</code> is inserted to the right of existing items.\nIf a list of scores in ascending order is <code>[20, 30, 50]</code>, then Alice is really in second place if she scored <code>30</code>. <code>bisect_left</code> would sort her into third place.</p>\n\n<p>Since ranks are 1-indexed, increment by <code>1</code>.\nLastly, the below result would be inverted, since the sorting inverted the list.\nTherefore, use <code>len</code> to rectify.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom bisect import bisect\n\n# Complete the climbingLeaderboard function below.\ndef climbingLeaderboard(scores, alice):\n length = len(scores)\n return [length - bisect(scores, alice_score) + 1 for alice_score in alice]\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n scores_count = int(input())\n\n scores = sorted(set(map(int, input().rstrip().split())))\n\n alice_count = int(input())\n\n alice = list(map(int, input().rstrip().split()))\n\n result = climbingLeaderboard(scores, alice)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n</code></pre>\n\n<p>This passes all tests. The required <code>sorted</code> step is <span class=\"math-container\">\\$ \\mathcal{O}(n\\, \\log n)\\$</span>, see <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<hr>\n\n<p>Without sorting the input, a <code>bisect</code> implementation that works on reversed sorted lists is required.\nThe change compared to the original implementation (link above) is minimal, as seen below.\n<code>if a[mid] < x: lo = mid+1</code> is simply inverted to <code>if a[mid] > x: lo = mid+1</code> (I also formatted the code more).</p>\n\n<p>Simply calling <code>list((set(sequence))</code> on the scores will not work.\nDuplicates will be purged, but the order will be lost.\nTherefore, we simply construct a new list, using a <code>set</code> to block appending already seen elements, see <a href=\"https://stackoverflow.com/a/480227/11477374\">here</a>.</p>\n\n<p>The below approach works, but similarly to yours, fails for long inputs in its naive version.\nThis is why I added <code>previous_higher_bound</code>.\nThis counter keeps track of what rank Alice was on in the past.\nIt could also be named <code>previously_lowest_rank</code> or similar.\nThis is passed to <code>bisect</code> to drastically tighten the searched range, allowing the tests to pass.\nUnfortunately, it also makes the approach more verbose.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Complete the climbingLeaderboard function below.\ndef climbingLeaderboard(scores, alice):\n def reverse_bisect_left(sequence, x, lower_bound=0, higher_bound=None):\n \"\"\"Return the index where to insert item x in list a, assuming a is sorted in reverse.\n \"\"\"\n if lower_bound < 0:\n raise ValueError(\"lo must be non-negative\")\n if higher_bound is None:\n higher_bound = len(sequence)\n while lower_bound < higher_bound:\n middle = (lower_bound + higher_bound) // 2\n if sequence[middle] > x:\n lower_bound = middle + 1\n else:\n higher_bound = middle\n return lower_bound, higher_bound\n\n\n def uniquelify_list(sequence):\n seen = set()\n return [int(x) for x in sequence if not (x in seen or seen.add(x))]\n\n\n def leaderboard_rank(scores, score, higher_bound=None):\n result, previous_higher_bound = reverse_bisect_left(scores, int(score), higher_bound=higher_bound)\n return result + 1, previous_higher_bound\n\n\n def get_ranks(scores, alice_scores):\n scores = uniquelify_list(scores)\n previous_higher_bound = len(scores)\n ranks = []\n for alice_score in alice_scores:\n result, previous_higher_bound = leaderboard_rank(scores, alice_score, previous_higher_bound)\n ranks.append(result)\n return ranks\n return get_ranks(scores, alice)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T07:41:51.393",
"Id": "242028",
"ParentId": "242017",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242028",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T20:30:35.543",
"Id": "242017",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"time-limit-exceeded",
"binary-search"
],
"Title": "Binary Search implementation: HackerRank - Climbing the Leaderboard"
}
|
242017
|
<p>Let me preface this with saying that it's probably not necessary to understand all the math behind this to review my code. Unless you have a lot of spare time or a very strong interest I also wouldn't try too hard to understand the background if you don't already know some of the basics, like what a symmetric polynomial is. In my edit below I provide a description of what the function is actually doing, which is a lot less lofty than it sounds.</p>
<p>This is math code, which as I'm sure you all know has a reputation for being ugly. The language is Python 3. I am implementing a special case of the formula in <a href="https://arxiv.org/abs/alg-geom/9505001" rel="nofollow noreferrer">this paper</a>. Specifically, it is to get a formula (in terms of indexing permutations) for multiplying a Schubert polynomial (which is a polynomial S_p indexed by a permutation p, there is one for each permutation, and any polynomial in any number of variables with integer coefficients can be expressed uniquely as a linear combination of Schubert polynomials with integer coefficients) by a polynomial of the form x_1*x_2*...*x_k. The input is a dictionary with key a tuple of integers (the indexing permutation) and value an int (the coefficient of the corresponding Schubert polynomial) and the result is a dictionary of the same kind. </p>
<p><code>single_variable</code> calculates the coefficients of Schubert polynomials when multiplied by the monomial x_k. <code>elem_sym_mul</code> takes a similar permutation->coefficient dictionary and a list of values of k and for each k multiplies by x_1, x_2, ..., up to x_k, using <code>single_variable</code>.</p>
<p>Permutations are lists or tuples, which are unfortunately necessarily zero indexed, but the permutation is a permutation of all positive integers where all but finitely many elements are fixed, but if, for example, after index n everything is fixed, we omit everything after index n. For example (2,3,1,4) (when it needs to be hashed) or [2,3,1,4]. <code>permtrim</code> is just a utility function for trimming the permutation if the final elements are redundant. [2,3,1,4,5,6] is considered the same as [2,3,1,4] and <code>permtrim</code> implements this.</p>
<p>I'm looking for notable style issues or, if you see any, optimizations.</p>
<hr>
<p><strong>Edit:</strong> I realized it would probably be helpful to explain exactly what <code>single_variable</code> does. Let us assume the input is</p>
<pre><code>{perm: coeff}
</code></pre>
<p>This represents the Schubert polynomial S_perm. The result when multiplying by x_k gives you some Schubert polynomials with a coefficient of <code>coeff</code>, and some Schubert polynomials with a coefficient of <code>-coeff</code>. The ones with a coefficient of <code>coeff</code> are obtained as follows: all permutations <code>perm2</code> such that <code>perm2</code> differs from <code>perm</code> by exchanging the element at index <code>k-1</code> with an element at index <code>j</code> for some <code>j>k-1</code> such that <code>perm[k-1]<perm[j]</code> and there does not exist any <code>k-1<i<j</code> such that <code>perm[k-1]<perm[i]<perm[j]</code>. In this case, the index <code>j</code> is allowed to go beyond the length of the list/tuple into fixed elements, but it will only ever go one element past the length of the list due to the considerations above, so before the processing one element is added to complete the search space.</p>
<p>The ones with coefficient <code>-coeff</code> are obtained similarly, but instead we are looking for indexes <code>i<k-1</code> such that <code>perm[i]<perm[k-1]</code> and there does not exist <code>i<j<k-1</code> such that <code>perm[i]<perm[j]<perm[k-1]</code>.</p>
<p>Doing this for the whole dictionary of permutations to coefficients just iterates this for each entry and sums the result.</p>
<pre><code>from typing import Dict, Tuple, List
def permtrim(perm:List[int]):
if len(perm)==1:
return perm
elif perm[len(perm)-1]==len(perm):
return permtrim(perm[:len(perm)-1])
else:
return perm
def single_variable(perm_dict:Dict[Tuple[int],int],k:int):
res_dict = {}
for perm,val in perm_dict.items():
perm2 = (*perm,len(perm)+1)
for i in range(k,len(perm2)):
if perm2[k-1]<perm2[i]:
good = True
for p in range(k,i):
if perm2[k-1]<perm2[p] and perm2[p]<perm2[i]:
good = False
break
if good:
permp = list(perm2)
permo = tuple(permtrim(permp[:k-1]+[permp[i]]+permp[k:i]+[permp[k-1]]+permp[i+1:]))
res_dict[permo] = res_dict.get(permo,0)+val
if res_dict.get(permo,0) == 0:
del res_dict[permo]
for i in range(0,k-1):
if perm2[i]<perm2[k-1]:
good = True
for p in range(i+1,k-1):
if perm2[i]<perm2[p] and perm2[p]<perm2[k-1]:
good = False
break
if good:
permp = list(perm2)
permo = tuple(permtrim(permp[:i]+[permp[k-1]]+permp[i+1:k-1]+[permp[i]]+permp[k:]))
res_dict[permo] = res_dict.get(permo,0)-val
if res_dict.get(permo,0) == 0:
del res_dict[permo]
return res_dict
def elem_sym_mul(perm_dict:Dict[Tuple[int],int],ks:List[int]):
dicto = perm_dict
for i in range(1,max(ks)+1):
for k in ks:
if i<=k:
dicto = single_variable(dicto,i)
return dicto
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><strong>Avoid recursion</strong>. It is expensive. <code>permtrim</code> can be (mechanically) converted into a clean iterative form:</p>\n\n<pre><code>def permtrim(perm):\n while len(perm) > 1 and perm[-1] == len(perm):\n perm.pop()\n return perm\n</code></pre></li>\n<li><p><strong>Avoid naked loops</strong>. Every loop implements an algorithm, and deserves a name. For example, he loops <code>for p in range(k, i)</code> and <code>for p in range(i+1, k-1)</code> test that the every element in the range are between than some bounding values. Consider factoring it into a function, like <code>range_is_between</code>,</p>\n\n<pre><code> if perm2[k-1] < perm2[i]:\n if range_is_between (perm2[k:i], perm2[k-1], perm2[i]):\n permp = ....\n ....\n</code></pre>\n\n<p>Now it should be obvious that the first <code>if</code> essentially is a part of the same logic, and better be delegated to the same function.</p>\n\n<pre><code> if range_is_between (perm2[k:i], perm2[k-1], perm2[i]):\n ....\n</code></pre>\n\n<p>Flat is better than nested.</p>\n\n<p>Also, notice how the <code>good</code> boolean flag disappears. Elimination of a boolean flags is a strong indication that you are going in a right direction.</p></li>\n<li><p><strong>DRY</strong>. The bodies of two loops are suspiciously similar:</p>\n\n<pre><code>for i in range(0,k-1):\n if range_is_between(perm2[i+1:k-1], perm2[i], perm2[k-1]):\n permp = list(perm2)\n permo = tuple(permtrim(permp[:i] + [permp[k-1]] + permp[i + 1:k-1] + [permp[i]] + permp[k:]))\n res_dict[permo] = res_dict.get(permo,0)-val\n if res_dict.get(permo,0) == 0:\n del res_dict[permo]\n\nfor i in range(k,len(perm2)):\n if range_is_between(perm2[k:i], perm2[k-1], perm2[i]):\n permp = list(perm2)\n permo = tuple(permtrim(permp[:k-1] + [permp[i]] + permp[k:i] + [permp[k-1]] + permp[i+1:]))\n res_dict[permo] = res_dict.get(permo,0)+val\n if res_dict.get(permo,0) == 0:\n del res_dict[permo]\n</code></pre>\n\n<p>This is also an indication that they really want to be functions too:</p>\n\n<pre><code>def single_variable(perm_dict:Dict[Tuple[int],int],k:int):\n res_dict = {}\n for perm,val in perm_dict.items():\n perm2 = (*perm,len(perm)+1)\n res_dict = do_important_stuff(0, k, perm2)\n res_dict = do_important_stuff(k, len(perm2), perm2)\n</code></pre>\n\n<p>I have no idea what is the right name for <code>do_important_stuff</code>. I have no domain knowledge. You do.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T23:47:54.880",
"Id": "475015",
"Score": "0",
"body": "I was skeptical about the recursion performance hit being enough to matter since it's generally only one or two layers deep, but I tried your version on a large example that previously took 29 seconds and it took 27 seconds, so definitely an improvement. I'll have to look at the rest later, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T02:31:02.647",
"Id": "475020",
"Score": "0",
"body": "@MattSamuel Don't get me wrong, the recursion point was not so much about performance (I am glad it helped the performance), but about clarity. Just like the other points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T10:41:26.343",
"Id": "475045",
"Score": "0",
"body": "Unfortunately that speed gain is lost when I implement your second suggestion, it goes to 30.5 seconds. Apparently function calls in general are expensive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T11:26:19.930",
"Id": "475052",
"Score": "0",
"body": "I ended up naming range_is_between as bruhat_ascent and leaving the two loops separate to save time, but making them look cleaner by naming the indices first_index and last_index. It also saved time to just do a straight swap of the two indices rather than all of that slicing, also clearer. Anyway, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T21:10:29.177",
"Id": "475101",
"Score": "0",
"body": "In the large example I speak of, it spends over 6 seconds in `bruhat_ascent`, because it is called 33363163 times. Most of the time the examples aren't that large, but if I want to test n=9 I'm probably going to want to use a different language."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T21:40:42.883",
"Id": "242051",
"ParentId": "242018",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242051",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T20:33:47.967",
"Id": "242018",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"mathematics"
],
"Title": "Multiplying by certain elementary symmetric polynomials"
}
|
242018
|
<p>I had just put together my first public project: simple(sane) new-handler for c++.</p>
<p>It allocates some reserved memory on start up, then releases it piece by piece. It may also raise a signal when each piece is released. It allows to monitor approaching of low memory conditions and gracefully handle them at the system level while there are still some memory available and avoid raising meaningless std::bac_alloc exceptions.</p>
<p>Please, review.</p>
<p><a href="https://github.com/alex4747-pub/simple_new_handler" rel="nofollow noreferrer">https://github.com/alex4747-pub/simple_new_handler</a></p>
<pre><code>#ifndef _INCLUDE_SIMPLE_NEW_HANDLER_H_
#define _INCLUDE_SIMPLE_NEW_HANDLER_H_
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <new>
#include <utility>
namespace simple {
class NewHandler {
public:
// Initialize the driver and allocate reserved memory blocks
//
// If not enough memory allocate as many blocks as possible
//
static void Init(size_t finalBlockSize = 0, size_t reservedBlockCount = 0,
size_t reservedBlockSize = 0, int signo = 0) {
GetWorker().Init(finalBlockSize, reservedBlockCount, reservedBlockSize,
signo);
}
struct State {
size_t allocated_block_count;
size_t available_block_count;
};
static State GetState() { return GetWorker().GetState(); }
// Full state
struct FullState {
bool init_done;
int signo;
size_t final_block_size;
bool final_block_allocated;
size_t reserved_block_size;
size_t reserved_block_count;
size_t allocated_block_count;
size_t available_block_count;
};
static FullState GetFullState() { return GetWorker().GetFullState(); }
private:
class Worker;
static void Process() { GetWorker().Process(); }
static Worker& GetWorker() {
static Worker worker_;
return worker_;
}
class Worker {
public:
Worker()
: init_done_(),
signo_(),
final_block_size_(),
reserved_block_size_(),
reserved_block_count_(),
allocated_block_count_(),
available_block_count_(),
final_block_(),
blk_arr_list_() {}
// Note on concurrency:
//
// It is a responsibility of the user to call init()
// before entering multithreaded environment
//
// The environment guarantees that
// the handler call itself is thread safe.
//
// Volatile is good enough for reporting purposes
// because we do not care about race condition
// between actual and reported usage
//
void Init(size_t finalBlockSize = 0, size_t reservedBlockCount = 0,
size_t reservedBlockSize = 0, int signo = 0) {
if (init_done_) {
// We expect to be done once and it is done
// more than once we do not care much
return;
}
final_block_size_ = finalBlockSize;
size_t finalSize =
(final_block_size_ + sizeof(Blk) - 1) / sizeof(Blk) * sizeof(Blk);
if (finalSize) {
final_block_ = new (std::nothrow) Blk[finalSize / sizeof(Blk)];
if (final_block_) {
// Assign a value to map allocated block
final_block_->m_next = 0;
}
}
reserved_block_count_ = reservedBlockCount;
unsigned int blockLimit = std::numeric_limits<unsigned int>::max();
if (reserved_block_count_ < blockLimit)
blockLimit = static_cast<unsigned int>(reserved_block_count_);
reserved_block_size_ = reservedBlockSize;
if (reserved_block_count_ && reserved_block_size_) {
size_t reservedSize = (reserved_block_size_ + sizeof(Blk) - 1) /
sizeof(Blk) * sizeof(Blk);
for (unsigned int ii = 0; ii < blockLimit; ii++) {
Blk* blkArr = new (std::nothrow) Blk[reservedSize / sizeof(Blk)];
if (!blkArr) {
allocated_block_count_ = ii;
break;
}
blkArr[0].m_next = blk_arr_list_;
blk_arr_list_ = blkArr;
}
if (blk_arr_list_ && !allocated_block_count_) {
// All reserved blocks were allocated
allocated_block_count_ = blockLimit;
}
available_block_count_ = allocated_block_count_;
}
signo_ = signo;
std::set_new_handler(NewHandler::Process);
init_done_ = true;
}
State GetState() const volatile {
State s;
memset(&s, 0, sizeof(s));
if (!init_done_) {
return s;
}
s.allocated_block_count = allocated_block_count_;
s.available_block_count = available_block_count_;
return s;
}
FullState GetFullState() const volatile {
FullState s;
memset(&s, 0, sizeof(s));
if (!init_done_) {
return s;
}
s.init_done = true;
s.signo = signo_;
s.final_block_size = final_block_size_;
if (final_block_) s.final_block_allocated = true;
s.reserved_block_size = reserved_block_size_;
s.reserved_block_count = reserved_block_count_;
s.allocated_block_count = allocated_block_count_;
s.available_block_count = available_block_count_;
return s;
}
void Process() {
Blk* curBlkArr = blk_arr_list_;
if (curBlkArr) {
// Release the first avalable block to the process
// and raise signal if configured
blk_arr_list_ = curBlkArr[0].m_next;
delete[] curBlkArr;
if (available_block_count_ > 0) available_block_count_--;
if (signo_ != 0) std::raise(signo_);
return;
}
// Release final block and terminate
delete[] final_block_;
final_block_ = 0;
std::terminate();
}
private:
struct Blk {
Blk* m_next;
};
bool init_done_;
int signo_;
size_t final_block_size_;
size_t reserved_block_size_;
size_t reserved_block_count_;
unsigned int allocated_block_count_;
volatile unsigned int available_block_count_;
Blk* final_block_;
Blk* blk_arr_list_;
};
};
} // namespace simple
#endif // _INCLUDE_SIMPLE_NEW_HANDLER_H_
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T21:10:03.907",
"Id": "474959",
"Score": "0",
"body": "Thank you, included the code."
}
] |
[
{
"body": "<p>My biggest bug bear:</p>\n\n<pre><code>#ifndef _INCLUDE_SIMPLE_NEW_HANDLER_H_\n#define _INCLUDE_SIMPLE_NEW_HANDLER_H_\n</code></pre>\n\n<p>These macros are reserved for the implementation (i.e. you can't use them). An identifier with an initial underscore followed by a capitol letter is reserved for the implementation in any scope.</p>\n\n<p>See: <a href=\"https://stackoverflow.com/q/228783/14065\">What are the rules about using an underscore in a C++ identifier?</a></p>\n\n<hr>\n\n<p>What is the purpose of this?</p>\n\n<pre><code> State s;\n\n memset(&s, 0, sizeof(s));\n</code></pre>\n\n<p>If you want to make sure that everything is zeroed in <code>State</code> object then create an appropriate constructor!</p>\n\n<hr>\n\n<p>Not sure what this is for!</p>\n\n<pre><code> if (!init_done_) {\n return s;\n }\n</code></pre>\n\n<p>You should design your code so it can't get to this location without it being already initialized correctly. Not sure how you can call a method on an object before it is constructed.</p>\n\n<p>Since you are using a function static variable for all <code>Worker</code> objects creation of this object is already thread safe.</p>\n\n<hr>\n\n<p>Not sure why you would do this:</p>\n\n<pre><code> s.allocated_block_count = allocated_block_count_;\n s.available_block_count = available_block_count_;\n\n return s;\n</code></pre>\n\n<p>Why is this state not already part of the worker object as a <code>State</code> object. Then you can simply return the workers <code>State</code> object!</p>\n\n<hr>\n\n<p>I would have defined the structures like this:</p>\n\n<pre><code> struct State\n {\n size_t allocated_block_count;\n size_t available_block_count;\n };\n\n struct FullState {\n bool init_done;\n int signo;\n size_t final_block_size;\n bool final_block_allocated;\n size_t reserved_block_size;\n size_t reserved_block_count;\n State currentState;\n };\n\n class Worker\n {\n FullState fullState;\n Blk* final_block_;\n Blk* blk_arr_list_;\n\n State GetState() const volatile {return fullState.state;}\n FullState GetFullState() const volatile {return fullState;}\n };\n</code></pre>\n\n<p>This simplifies a lot of the work you have done.</p>\n\n<hr>\n\n<p>The call to <code>std::set_new_handler(NewHandler::Process);</code> actually returns the current new_handler. You may want to retain this value and use it.</p>\n\n<p>If you fail to allocate any extra memory then you call (if it is not null) the originally available handler (or put it back in place potentially).</p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T15:39:21.390",
"Id": "475183",
"Score": "0",
"body": "Thanks for review. I will implement most of your notes. I do not see any point in keeping original handler - once the thing is out of memory nothing could be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T18:57:52.113",
"Id": "475219",
"Score": "0",
"body": "The original handler (which may not be the C++ original handler but one installed by another library) may have saved space just like your handler has done. By not calling it you have wasted that space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T19:35:08.377",
"Id": "475224",
"Score": "0",
"body": "If there is other handlers there is simply no point of using this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T21:26:57.077",
"Id": "475230",
"Score": "0",
"body": "That's not true in the slightest. Libraries are know to install their own handlers for their use cases. When you have run out of memory to release you should give the other libraries a chance to do there stuff (they may be able to copy stuff to disk and release memory etc). There may be a whole chain of low memory handlers that were installed before you. If you don't call the previously installed handler you are not allowing that chain of handler to do their library specific clean up to try and reduce the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T21:27:47.950",
"Id": "475231",
"Score": "0",
"body": "The only real question to ask is should you call their handler first or only call their handler if your handler has nothing else to give."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T21:29:32.697",
"Id": "475232",
"Score": "0",
"body": "Note: Most handlers are not installed by the developer calling an `Init()` function like you have. Most are installed by the constructor of some static storage duration object that is part of the library (there is no need for a manually installing these libraries)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T00:39:50.870",
"Id": "475241",
"Score": "0",
"body": "Sorry, this is not intended to be used in libraries, this should be called early from main during process initialization, so if there is a chain of handlers this should be the first one in the chain and the last one used. BTW in 30 years of software development I never saw (and never heard of) anything reasonable done on out of memory conditions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T01:16:30.527",
"Id": "475242",
"Score": "0",
"body": "That's the point. Other libraries could have installed their handlers before you without you knowing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T12:11:43.423",
"Id": "475310",
"Score": "0",
"body": "There is no point of having multiple kludges in memory management. So if this handler is going to be used it should override other ones, otherwise there is no point to add yet another kludge. BTW, libraries by definitions should not participate in memory management because libraries have no information on how they are being used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T15:36:10.320",
"Id": "475342",
"Score": "0",
"body": "If somebody else has already installed a handler. That has probably done some work. You are now basically giving up on their attempt to handle the low memory issue. Do you think your low memory handler is better than standard ones that have had years of development?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T15:41:38.550",
"Id": "475343",
"Score": "0",
"body": "`multiple kludges in memory management`: Just because you create a kludges does not mean other people have. In short: If somebody has installed a low memory handler you should be using it. This is **WHY** installing a new one returns the original to give you that opportunity to chain them together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T15:45:45.867",
"Id": "475344",
"Score": "0",
"body": "I once worked on a graphical system library (many many moons ago). We tried to keep all the objects in memory for speed but they were big. When we got into low memory situations we would page out the objects to disc in a very controlled way leaving only enough to reconstitute the object when it was actually needed (object oriented code at its finest). We combined a technique of least recently used but also took into account potential operations that were about to happen on objects, bringing objects back into memory using predictions before they we were needed on a separate thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T15:51:14.550",
"Id": "475346",
"Score": "0",
"body": "Sure its slower than all memory, but it did not crash and worked just fine (SSD are fast). If you added your memory handler on top of that one (and that one was automatically installed at startup if you linked against the library) you would simply crash when your `kludges` ran out of memory. Not.a real inspiring result?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T19:11:41.043",
"Id": "475471",
"Score": "0",
"body": "I wrote a handler that will do simple/reasonable/generic thing. There is simply no point of putting it before something that is better or more specialized - it may still make sense to put it after that is something better but it is for app developer to decide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T23:12:42.747",
"Id": "475499",
"Score": "0",
"body": "@zzz777 The point is you don't know if something better has been installed or not. Its not as if you are given the choice to install the better handler it will be installed automatically simply by the fact that you linked against a third party library. Your code should still work (and behave) when other people change different parts of the system not just after you built in the first time. What happens when somebody adds a new feature and links against a library that does add an extra low memory handler that installs itself. Are you not going to use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T23:15:23.470",
"Id": "475500",
"Score": "0",
"body": "@zzz777 You seem to be not considering the lifetime of software projects. The most important feature of code is that it should be easy to use correctly. Without using an existing handler you are breaking this very important part of software engineering. That is not the kind of thing I would associate with somebody with 30 years of development experience. We have all had to deal with systems where people did made things hard to use. That is why we have code review to make sure best practices are followed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T02:46:36.287",
"Id": "475519",
"Score": "0",
"body": "I spent 30 years developing applications (some of them were long lived 10+ years and 20+ and still going, widely used and the latter one was also big) so my view of the world is slightly different from the common one that is library-centric. I will add optional chaining just for completeness sake. I have a question: one of variable is volatile because it could be changed in one context while being read from another one. Does your review suggest what it will work without marking it volatile?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T16:55:47.023",
"Id": "475593",
"Score": "0",
"body": "@zzz777 My compiler for SISAL I wrote for my PhD in 92 is still being used (I get e-mails from current students improving it) if we are comparing numbers. If you are writing code without using libraries then that's exceedingly surprising. Writing everything from scratch is just re-inventing the wheel (I hope you at least use the standard library)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T17:00:24.783",
"Id": "475594",
"Score": "0",
"body": "@zzz777 `volatile` is one of those keywords that is only vaguely defined by the standard as to the requirements basically giving a hint to the compiler about it being updated out of line. I believe that the MS compiler does provide the guarantee that if it is being used in multiple threads it will be correctly update (but I am not sure). I have not read about such guarantees from other compilers. I don't comment on the volatile in the above code because there is not enough context to make a judgement. i.e. I don't know enough on the subject."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T04:33:26.093",
"Id": "242116",
"ParentId": "242019",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242116",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T20:44:56.033",
"Id": "242019",
"Score": "2",
"Tags": [
"c++",
"memory-management",
"exception"
],
"Title": "c++ new-handler"
}
|
242019
|
<p>the following tutorial uses an interceptor to show/hide a loading bar:</p>
<p><a href="https://www.freakyjolly.com/http-global-loader-progress-bar-using-angular-interceptors/" rel="nofollow noreferrer">https://www.freakyjolly.com/http-global-loader-progress-bar-using-angular-interceptors/</a></p>
<pre><code>export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }
removeRequest(req: HttpRequest<any>) {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
this.loaderService.isLoading.next(this.requests.length > 0);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests.push(req);
this.loaderService.isLoading.next(true);
return Observable.create(observer => {
const subscription = next.handle(req)
.subscribe(
event => {
if (event instanceof HttpResponse) {
this.removeRequest(req);
observer.next(event);
}
},
err => {
alert('error' + err);
this.removeRequest(req);
observer.error(err);
},
() => {
this.removeRequest(req);
observer.complete();
});
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
});
}
}
</code></pre>
<p>The idea is to call the method <code>removeRequest</code> for every type of http response, including errors etc., to make sure the loading spinner would disappear again no matter what may happens.</p>
<p>I have simplified this interceptor, to favor .pipe and .tap over .subscription, and would return an observable in my <code>removeRequest</code> function:</p>
<pre><code>export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }
removeRequest(req: HttpRequest<any>): Observable<any> {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
this.loaderService.isLoading.next(this.requests.length > 0);
return of([]);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests.push(req);
this.loaderService.isLoading.next(true);
return next.handle(req).pipe(tap(
event => {
return this.removeRequest(req);
},
err => {
return this.removeRequest(req);
},
() => {
return this.removeRequest(req);
}));
}
}
</code></pre>
<p>Is there any reason at all to not favor the simplified version?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T21:03:33.933",
"Id": "242020",
"Score": "1",
"Tags": [
"angular-2+",
"rxjs"
],
"Title": "Angular8 & RxJs: handling Observable in interceptor"
}
|
242020
|
<p>So I'm on level 5 of Google Foobar, and the Question is Expanding Nebula.
It goes as follows : </p>
<h1>Expanding Nebula</h1>
<p>You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! - one of the escape pods has flown into a nearby nebula, causing you to lose track of it. You start monitoring the nebula, but unfortunately, just a moment too late to find where the pod went. However, you do find that the gas of the steadily expanding nebula follows a simple pattern, meaning that you should be able to determine the previous state of the gas and narrow down where you might find the pod. <br/>
From the scans of the nebula, you have found that it is very flat and distributed in distinct patches, so you can model it as a 2D grid. You find that the current existence of gas in a cell of the grid is determined exactly by its 4 nearby cells, specifically, (1) that cell, (2) the cell below it, (3) the cell to the right of it, and (4) the cell below and to the right of it. If, in the current state, exactly 1 of those 4 cells in the 2x2 block has gas, then it will also have gas in the next state. Otherwise, the cell will be empty in the next state.<br/>
For example, let's say the previous state of the grid (p) was:<br/>
.O..<br/>
..O.<br/>
...O<br/>
O...<br/>
To see how this grid will change to become the current grid (c) over the next time step, consider the 2x2 blocks of cells around each cell. Of the 2x2 block of [p[0][0], p[0][1], p[1][0], p[1][1]], only p[0][1] has gas in it, which means this 2x2 block would become cell c[0][0] with gas in the next time step:<br/>
.O -> O<br/>
..<br/>
Likewise, in the next 2x2 block to the right consisting of [p[0][1], p[0][2], p[1][1], p[1][2]], two of the containing cells have gas, so in the next state of the grid, c[0][1] will NOT have gas:<br/>
O. -> .<br/>
.O<br/>
Following this pattern to its conclusion, from the previous state p, the current state of the grid c will be:<br/>
O.O<br/>
.O.<br/>
O.O<br/>
Note that the resulting output will have 1 fewer row and column, since the bottom and rightmost cells do not have a cell below and to the right of them, respectively.<br/>
Write a function solution(g) where g is an array of array of bools saying whether there is gas in each cell (the current scan of the nebula), and return an int with the number of possible previous states that could have resulted in that grid after 1 time step. For instance, if the function were given the current state c above, it would deduce that the possible previous states were p (given above) as well as its horizontal and vertical reflections, and would return 4. The width of the grid will be between 3 and 50 inclusive, and the height of the grid will be between 3 and 9 inclusive. The answer will always be less than one billion (10^9). <br/></p>
<h1>Languages</h1>
<p>To provide a Java solution, edit Solution.java
To provide a Python solution, edit solution.py</p>
<h1>Test cases</h1>
<p>Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
<br/>
-- Python cases --
Input:
solution.solution([[True, True, False, True, False, True, False, True, True, False], [True, True, False, False, False, False, True, True, True, False], [True, True, False, False, False, False, False, False, False, True], [False, True, False, False, False, False, True, True, False, False]]) <br/>
Output:
11567<br/>
Input:
solution.solution([[True, False, True], [False, True, False], [True, False, True]])<br/>
Output:
4<br/>
Input:
solution.solution([[True, False, True, False, False, True, True, True], [True, False, True, False, False, False, True, False], [True, True, True, False, False, False, True, False], [True, False, True, False, False, False, True, False], [True, False, True, False, False, True, True, True]])<br/>
Output:
254<br/></p>
<p>Basically, given an input matrix, you have to find the number of preimages to that matrix, according to the rule that is specified. Now I've got a program, and it does compute the preimages, and if tweeked more, it can even print the preimages. But it takes a while. It doesn't pass the final 2 hidden testcases. Is there any way to make this code work faster?<br/>
My code:</p>
<pre><code> import itertools
allPreimagesCol=[]
matches=[]
count=0
totalpaths=[]
found_matches={}
match_side=dict({0:[0,1,4,5],
1:[2,3,6,7],
2:[0,1,4,5],
3:[2,3,6,7],
4:[8,9,12,13],
5:[10,11,14,15],
6:[8,9,12,13],
7:[10,11,14,15],
8:[0,1,4,5],
9:[2,3,6,7],
10:[0,1,4,5],
11:[2,3,6,7],
12:[8,9,12,13],
13:[10,11,14,15],
14:[8,9,12,13],
15:[10,11,14,15]})
match_down=dict({0:[0,1,2,3],
1:[4,5,6,7],
2:[8,9,10,11],
3:[12,13,14,15],
4:[0,1,2,3],
5:[4,5,6,7],
6:[8,9,10,11],
7:[12,13,14,15],
8:[0,1,2,3],
9:[4,5,6,7],
10:[8,9,10,11],
11:[12,13,14,15],
12:[0,1,2,3],
13:[4,5,6,7],
14:[8,9,10,11],
15:[12,13,14,15]
})
paths={}
sides={}
rules=dict({0:[0,3,5,6,7,9,10,11,12,13,14,15],
1:[1,2,4,8]})
#for every i,j the rulebase follows the order [(i,j),(i,j+1),(i+1,j),(i+1,j+1),nextstate]
rulebase=[[0,0,0,0,False],
[0,0,0,1,True],
[0,0,1,0,True],
[0,0,1,1,False],
[0,1,0,0,True],
[0,1,0,1,False],
[0,1,1,0,False],
[0,1,1,1,False],
[1,0,0,0,True],
[1,0,0,1,False],
[1,0,1,0,False],
[1,0,1,1,False],
[1,1,0,0,False],
[1,1,0,1,False],
[1,1,1,0,False],
[1,1,1,1,False]]
def getAllPathsCol(col, u, depth, path):
global matches
depth+=1
path.append(u)
if depth==length:
matches.append(path[:])
else:
for i in match_down[u]:
if(rulebase[i][4]==col[depth]):
getAllPathsCol(col,i, depth, path)
path.pop()
def match(row,depth):
global count
global length
global newg
prods=[]
nextl=[]
depth+=1
if(depth<length):
vaar=tuple((tuple(row)+tuple(tuple(i) for i in allPreimagesCol[depth] )))
if(depth==length):
count+=1
elif( vaar in found_matches):
for p in found_matches[vaar]:
match(list(p),depth)
else:
if(tuple(row) in sides):
prods=sides[tuple(row)]
else:
prods=[l for l in itertools.product(*[match_side[k] for k in row])]
m=[]
for i in allPreimagesCol[depth]:
m.append((tuple(i)))
nextl=[q for q in set(m)]
s=set(prods) & set(nextl)
if(len(s)>0):
found_matches[vaar]=s
for j in (list(s)):
match(list(j),depth)
def findMatch(row):
for i in row:
if(tuple((tuple(i)+tuple([tuple(j) for j in allPreimagesCol[0] ]))) in found_matches):
for p in found_matches[tuple((tuple(i)+tuple([tuple(j) for j in allPreimagesCol[0] ])))]:
match(list(p),0)
else:
match(i,0)
def solution(g):
# Okay I had to search "expanding nebula foobar", but I found the concept to be "Cellular Automaton" -
# Nature of Code by Daniel Shiffman is a great resource.
# The question wants it in reverse.
col=[]
global length
newg=list(zip(*g))
global allPreimagesCol
global matches
for i in range(len(newg)):
col=newg[i]
length=len(col)
if(tuple(col) in paths):
allPreimagesCol.append(paths[tuple(col)])
else:
for item in rules[col[0]]:
path=[]
getAllPathsCol(col,item,0,path)
allPreimagesCol.append(matches)
paths[tuple(col)]=matches
matches=[]
row=allPreimagesCol[0]
length=len(allPreimagesCol)
findMatch(row)
return(count)
</code></pre>
<p>The code actually creates all the possible preimages for each column of the matrix, then matches tries to merge the columns.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T22:23:47.570",
"Id": "242021",
"Score": "2",
"Tags": [
"python",
"performance",
"cellular-automata"
],
"Title": "Google Foobar -Expanding Nebula - Code takes too long"
}
|
242021
|
<p>So I was investigating overflow safe division for a class that uses an int64 member with a given RESOLUTION ( 10000 ) for the fractional part. To preserve precision in the fractional part during an easy division you would multiply by the resolution first, which if the number is large enough results in an overflow. I came up with an algorithm to divide without overflow but I think it could probably be optimized better, I just can't see at first glance how:</p>
<pre><code>int64 divideOverflowSafe( const int64 Lhs, const int64 Rhs ) const
{
// The idea here is simple, split Lhs * RESOLUTION / Rhs into two separate divisions to avoid the multiplication by RESOLUTION and thus avoid the overflow
const int64 FracPart = Lhs % RESOLUTION;
const int64 DecPart = Lhs - FracPart;
// Just dividing the integral part means there's already an inherent resolution buffer for precision. We then need to also calculate the remainder, which is small enough that it can be multiplied by RESOLUTION ( and needs to be, to maintain precision )
const int64 Res1 = DecPart / Rhs;
const int64 Res1Remainder = ( DecPart % Rhs ) * RESOLUTION / Rhs;
// The fractional part is small enough to be multiplied by RESOLUTION, again for precision reasons
const int64 Res2 = FracPart * RESOLUTION / Rhs;
// At the end we add everything back together to obtain the result
const int64 Res = Res1 * RESOLUTION + Res1Remainder + Res2;
return Res;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T06:06:40.057",
"Id": "474979",
"Score": "0",
"body": "Is m_nVal and b.m_nVal supposed to be Lhs and Rhs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T07:57:08.950",
"Id": "474982",
"Score": "0",
"body": "@AbhayAravinda sorry, fixed. Yes"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T23:10:57.060",
"Id": "242023",
"Score": "2",
"Tags": [
"c++",
"c",
"mathematics"
],
"Title": "Division safe from overflow for fixedpoint"
}
|
242023
|
<p>I'm learning python (started about 30 hours ago) and my son asked if I could make a hangman game. Well, okay, I'll give that a try. I'm sure this code is crap, but I'll never learn if I don't ask how I could have done this better. Anything that's poor practice or doesn't scale? (I won't ask what's sloppy - it's all sloppy.)</p>
<pre><code>#
# HANGMAN
#
# Import some things I think I'll need
import random # For selecting from the word list randomly
import os # Only use is to be able to clear the screen on Windows
# Create tiny word list to get started
word_list = ['sandwich', 'hamburger', 'pizza', 'nuggets',
'fries', 'yogurt', 'popsicle']
# print(f"Selected words: {word_list}") # Used to check my syntax for formatting from a list
# Build the parts of the hangman fellow
# Originally had just 4 parts, comments below are from expanding to 7 parts
hung_man1 = " O\n"
hung_man2 = " /"
hung_man3 = "|" #added this line and removed | from prior
hung_man4 = "\\ \n" #added this line and removed \\ \n from prior
hung_man5 = " |\n"
hung_man6 = " / "
hung_man7 = "\\ \n" # added this line and removed \\ \n from prior
# Used this to compare syntax of strings and lists
# print(f"Built hangman sequence: \n{hung_man1}{hung_man2}{hung_man3}{hung_man4}")
# Stuff the entire hangman construction into a list
hung_man = hung_man1,hung_man2,hung_man3,hung_man4, hung_man5, hung_man6, hung_man7
# Here it is, the whole reason for calling the OS - used one other time below
os.system('cls')
# An introduction screen. Didn't try to make this nice.
print("")
print("")
print(" AND NOW IT'S TIME TO PLAY.... ")
print(" !!!HANGMAN!!!")
print("")
print("")
# Purpose is to check what it says it does - do I even need to comment this line?
# print(f"Created hangmand sequence list (should be the same): \n{hung_man}")
# Computer pics from a tiny list of words
computer_pick = random.choice(word_list)
# I store the length of the word
word_size = len(computer_pick)
# Initialize list used to display letter guessing status to player
display_word = []
# Used to check prior steps, could be killed now
# print(f"Computer selected {computer_pick} with length of {word_size}.")
# Quick function to chop the word into letters - currently unused.
def split(word):
return [char for char in word]
# Hint should be unnecesary for the player since the letter placeholders are displayed
print("The word you are guessing has", word_size, "letters:")
print("")
print("")
# Initializing more variables game_round is not used, wrong_guess is counter, winner is status
game_round = 0
wrong_guess = 0
winner = False
# For each letter in the selected word, create list with placeholder string spaces
for character in range(word_size):
display_word.append("___ ")
# Obviously used for debugging. Probably not needed anymore
# print("Displayed word with placeholders for guesses has been built.")
# Exit conditions are winning or guessing wrong 7 times
while (wrong_guess < 7 and not winner):
game_round += 1 # game_round is not used.
# First thing, display the word being guessed (will include correct guesses)
for character in range(word_size):
print(display_word[character], end="")
print("")
# After displaying the word with guesses so far (initially zero), fetch another guess
my_guess = input("What letter do you think is in the word? ")
# Execute the following only if the letter matches
if my_guess.lower() in computer_pick:
# Create a list to index where the letters match (in case letter used more than once)
matching_letters = [i for i, x in enumerate(computer_pick) if x == my_guess]
# Update the string list in display_word to reflect the correct guesses as capital letters
for position in matching_letters:
display_word[position] = f" {my_guess.upper()} "
# If all of the blank spaces have been filled - show completed word and set win status
if "___ " not in display_word:
for character in range(word_size):
print(display_word[character], end="")
print("")
winner = True
# If the guessed letter does not match, increment guesses and display hangman status
# This block also has the second use of the import OS to clear the screen
else:
wrong_guess += 1
os.system('cls')
print("")
print(" Be Careful! You're headed to the gallows!", end="")
print("")
# As stated, this line prints the count (so I could check my logic)
# print(wrong_guess) # Keeps count of wrong guesses for debugging
# Prints as much of the hangman as suits the number of wrong guesses
for hangman in range(wrong_guess):
print(hung_man[hangman], end="")
print("\n\n")
# What to do when the maximum number of wrong guesses have been reached
if wrong_guess > 6:
print(" OH NO\n !! YOU'VE BEEN HUNG !!")
# What to do when the game has been won
else:
print("")
print(" !!YOU WON!!")
</code></pre>
|
[] |
[
{
"body": "<p>Without rewriting the entire thing, there are a bunch of pointers I can give you:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>hung_man1 = \" O\\n\"\nhung_man2 = \" /\"\nhung_man3 = \"|\" #added this line and removed | from prior\nhung_man4 = \"\\\\ \\n\" #added this line and removed \\\\ \\n from prior\nhung_man5 = \" |\\n\"\nhung_man6 = \" / \"\nhung_man7 = \"\\\\ \\n\" # added this line and removed \\\\ \\n from prior\n</code></pre>\n\n<p>Is not something you would ever want to do.\nWhen you find yourself naming variables <code>name</code> + <code>number</code>, think of lists:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>hung_man = [\n \" O\\n\",\n \" /\",\n \"|\", # added this line and removed | from prior\n \"\\\\ \\n\", # added this line and removed \\\\ \\n from prior\n \" |\\n\",\n \" / \",\n \"\\\\ \\n\", # added this line and removed \\\\ \\n from prior\n]\n</code></pre>\n\n<p>This gets rid of </p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Stuff the entire hangman construction into a list\nhung_man = hung_man1,hung_man2,hung_man3,hung_man4, hung_man5, hung_man6, hung_man7\n</code></pre>\n\n<p>which is incidentally not a list, but a <code>tuple</code>.\nYou may have never noticed because these behave the same in your code.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>os.system(\"cls\")\n</code></pre>\n\n<p>does not work on Unix-based systems.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"\")\nprint(\"\")\nprint(\" AND NOW IT'S TIME TO PLAY.... \")\nprint(\" !!!HANGMAN!!!\")\nprint(\"\")\nprint(\"\")\n</code></pre>\n\n<p>can just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"\\n\\n AND NOW IT'S TIME TO PLAY.... \")\nprint(\" !!!HANGMAN!!!\\n\\n\")\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code># I store the length of the word\nword_size = len(computer_pick)\n</code></pre>\n\n<p>If that comment helps you learn or remember in any way, keep it, but under normal circumstances, it should definitely be removed.\nIt just replicates what the code says almost verbatim.\nIf the code ever changes, the comment can become outdated and confusing (comments lie, code never does).</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code># Quick function to chop the word into letters - currently unused.\ndef split(word):\n return [char for char in word]\n</code></pre>\n\n<p>already exists in the form of <code>list(word)</code>.\nOther than that, there is <code>str.split</code> to split a string according to some delimiter, which is not what your function does but might be handy for the future.\nNote that you can just iterate over a string naturally, no need to convert it to a list or similar.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"The word you are guessing has\", word_size, \"letters:\")\nprint(\"\")\nprint(\"\")\n</code></pre>\n\n<p>This could be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"The word you are guessing has {word_size} letters:\", end=\"\\n\\n\")\n</code></pre>\n\n<p>f-strings are powerful, convenient and fast.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code># Initializing more variables game_round is not used, wrong_guess is counter, winner is status\ngame_round = 0\nwrong_guess = 0\nwinner = False\n</code></pre>\n\n<p>But <code>game_round</code> occurs later on, where it also has a similar comment.\nIt therefore seems used at first sight.\nAccording to the comment, it is not.\nTherefore, just use fewer comments in general and do not leave unused lines in the code, if at all possible.\nLook into version control systems like <code>git</code> if you want to handle this properly.</p>\n\n<p><code>winner</code> sounds like it should be a string containing the winner's name or similar.\n<code>won</code> is more suitable to signal a <code>bool</code>.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>for character in range(word_size):\n display_word.append(\"___ \")\n</code></pre>\n\n<p>works, but <code>display_word</code> is initialized to an empty list way earlier.\nKeep the <code>display_word = []</code> line close to where it is used.</p>\n\n<p>Also, <code>\"___ \"</code> works, but \"explicit is better than implicit\" (<code>import this</code>).\nSomeone might come along and think the spaces are accidents.</p>\n\n<p>Lastly, list comprehension will make all of this faster and more readable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>display_word = [\"_\" * 3 + \" \" * 2 for _ in range(word_size)]\n</code></pre>\n\n<p>Notice the <code>_</code> for \"this variable is unused\".\nYour <code>character</code> variable from before was wrong or at least very misleading, since <code>range</code> yields integers.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code> for character in range(word_size):\n print(display_word[character], end=\"\")\n</code></pre>\n\n<p>can just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> for word in display_word:\n print(word, end=\"\")\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>if my_guess.lower() in computer_pick:\n</code></pre>\n\n<p>is very confusing.\nI entered capital letters into the game and they are silently dropped without error or hangman-penalty.</p>\n\n<p>This is because the following line lacks a <code>.lower()</code> call to <code>my_guess</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> matching_letters = [i for i, x in enumerate(computer_pick) if x == my_guess]\n</code></pre>\n\n<p>Just put it into the <code>input</code> line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> my_guess = input(\"What letter do you think is in the word? \").lower()\n</code></pre>\n\n<p>Note that the list comprehension has poor variable naming as well, namely <code>x</code>.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code> if \"___ \" not in display_word:\n for character in range(word_size):\n print(display_word[character], end=\"\")\n print(\"\")\n winner = True\n</code></pre>\n\n<p>Here, <code>winner = True</code> can be replaced by a simple <code>break</code>.\nThis allows you to get rid of the <code>winner</code> variable altogether.</p>\n\n<p>There is also the possibility to add an <code>else</code> block to your <code>while</code> block.\nThis executes if no <code>break</code> occurred but the <code>while</code> condition evaluated to <code>False</code>.\nAka, your <code>while</code> loop finished, no <code>break</code> was found (here, this is the winning flag).\nThus, you can put handling the losing situation there.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>if wrong_guess > 6:\n</code></pre>\n\n<p>Alongside <code>while wrong_guess < 7</code> above, you hard-coded the numbers here as well.\nThese two can go out of sync, breaking your program.\nUsing the <code>while</code>/<code>else</code> construct, you can avoid this problem altogether.</p>\n\n<p>In general, extract any repetition into variables.\nThis also applies to for example <code>\"___ \"</code>, which you use multiple times.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T19:35:39.647",
"Id": "475008",
"Score": "1",
"body": "Very helpful, and thanks for all the examples! You spent a good amount of time on that explanaiton and it is really appreciated. I think I suspected that some of the things could \"be done better\", but actually making that happen wasn't happening. \nSo again, kudos on examples. I'll definitely try to take advantage of this going forward."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T10:39:15.497",
"Id": "242032",
"ParentId": "242026",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T01:37:01.613",
"Id": "242026",
"Score": "4",
"Tags": [
"python"
],
"Title": "Simple python for playing Hangman"
}
|
242026
|
<p>This is a mix of data structure and multi threading concept based question. (This is only for understanding and learning purpose) The language for the solution : Java</p>
<p>A Queue with FIFO behavior needs to be implemented by having underlying data structure as Stack.
Enqueue and Dequeue need to be parallel and need not block each other, i.e. enqueue thread must not wait for dequeue thread.</p>
<p>During my search (java based solutions) I could only find the blocking version of this problem where enqueue and dequeue are blocking for each other.</p>
<p>Below is my attempt for this, please correct me if I am wrong or in case I missed something.</p>
<ol>
<li>Two Stacks : addStack and removeStack with individual Lock Objects addLock and removeLock</li>
<li>Enqueue operation : enqueue inside synchronized block on addLock, once item added, invoke notifyAll on addLock</li>
<li>Dequeue operation : If removeStack is empty then addStack is checked if it is empty , if not then all the elements from addStack are popped and pushed to removeStack</li>
<li>pop the element from removeStack and return </li>
</ol>
<p>Below is the java code : </p>
<pre><code>import java.util.Stack;
/**
* Queue Implementation with Stack as underlying data-structure and with
* parallel (almost) enqueue and dequeue
*
* @author krishna_k
*
*/
public class Queue {
private Stack<Integer> addStack = new Stack<>();
private Stack<Integer> removeStack = new Stack<>();
private final Object addLock = new Object();
private final Object removeLock = new Object();
public void enqueue(int item) {
synchronized (addLock) {
addStack.push(item);
addLock.notifyAll();
}
}
public int dequeue(){
int value = 0;
synchronized (removeLock) {
if (removeStack.isEmpty()) {
try {
synchronized (addLock) {
while (addStack.isEmpty()) {
addLock.wait();
}
while (!addStack.isEmpty()) {
removeStack.push(addStack.pop());
}
}
}catch(InterruptedException e) {
//code to log the exception e
}
}
value = removeStack.pop();
}
return value;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T00:27:51.460",
"Id": "475374",
"Score": "0",
"body": "Using Stack as the base for your implementation is problematic because Stack uses synchronized methods and thus will block you enqueue and dequeue methods. Must it be Stack?"
}
] |
[
{
"body": "<p>Let's start by talking about the requirements. </p>\n\n<p><strong>Implement a thread-safe queue with an underlying stack</strong>. This is pretty basic, and has many ways to implement. However, the catch here is <strong>Enqueue and Dequeue need to be parallel</strong>. This is actually problematic, because as long as a lock is used, blocking will occur. So one can either not use locks, or try to limit their affects.</p>\n\n<h2>Your Implementation</h2>\n\n<p>Let's talk about your implementation. The first clear thing is that you are using locks, which means blocking is likely.</p>\n\n<p>You have 2 locks, a good thought to try and separate the methods. You also have 2 stacks, each corresponding to a lock. Again, good thought, a single lock must be responsible for all the usage of a specific data source.</p>\n\n<p>The usage of the <code>Stack</code> class however, is a problem. Not only is <code>Stack</code> a outdated collection class, you must also be aware that it extends <code>Vector</code> and each method in it is <code>synchronized</code>. Luckily, as we will see, most of this doesn't have much functionality impact, but rather more of a performance issue. I would recommend using a <code>Dequeue</code> instead. </p>\n\n<p>Another clear part is that it is an <code>int</code> only implementation. In reality, implementing it generically isn't that different or complicated, since an underlying data structure that supports generics is used.</p>\n\n<h3>Enqueue</h3>\n\n<p>Your enqueue is quite basic. Take the addition lock, add an element, notify about this addition, and release the lock.</p>\n\n<p>The notifying part, tells us that there is waiting somewhere. I'm assuming this is a blocking queue then. This is both not defined in the requirements, and will cause blocking between the threads. Although, the use of <code>notifyAll</code> may cause a problem.</p>\n\n<p>Otherwise, this is quite straightforward. However, it is already obvious that for the <code>dequeue</code> to work, <code>addStack</code> must be accessed, and thus <code>addLock</code> must be touched. This already tells us that blocking will occur.</p>\n\n<h3>Dequeue</h3>\n\n<p>Now comes the complicated part. </p>\n\n<p>You start by entering a <code>synchronized</code> block of <code>removeLock</code>, this is quite expected, given how the stacks require usage of the locks. </p>\n\n<p>You then check if the <code>removeStack</code> is empty or not. If it isn't you simply <code>pop</code> and return that value. This might seem like a basic example of a <code>dequeue</code> implementation, but that is not true. Because values are not added directly into <code>removeStack</code>, so it being empty means nothing about the actual queue.</p>\n\n<p>Now, if <code>removeStack</code> is empty... then comes the problematic part. The moment <code>addLock</code> is used, we know blocking between the two method will occur. </p>\n\n<p>If <code>addStack</code> is empty, you wait on <code>addLock</code> until it is notified. This is a blocking queue operation. Which again, is not specified as needed. A non-blocking queue operation would be simply to throw some exception indicating that no value is available. Let's return to the use of <code>notifyAll</code>. If multiple <code>dequeue</code> calls are done, all of them will reach the <code>wait</code>, since the locks are not actually taken while waiting. When <code>enqueue</code> is called and <code>notifyAll</code> is done, only one element was added, however all the waiting threads will wake up, and compete on getting the lone element. Perhaps it is best to just use <code>notify</code>.</p>\n\n<p>if <code>addStack</code> is not empty, you copy the values from it to <code>removeStack</code>, and then pop from it and return a value. This still causes blocking between <code>enqueue</code> and <code>dequeue</code>. Luckily, if <code>enqueue</code> runs longer, the blocking will be decreased, since the values will already be in <code>removeStack</code>.</p>\n\n<p>Catching of <code>InterruptedException</code> here is not really a good idea. When you have a blocking method (method that waits), throwing an <code>InterruptedException</code> is important, since this exception is thrown when the thread is interrupted and the user likely wants to stop the operations running.</p>\n\n<h3>Summary</h3>\n\n<p>Although it has some good logic behind it, in reality this implementation both doesn't accomplish the full requirements, and adds some complications. However, because stack is LIFO, the complexity in <code>dequeue</code> cannot be avoided. Luckily, this blocking is actually pretty short. So it might be even negligible enough to not care about it.</p>\n\n<p>If <code>enqueue</code> is used more than <code>dequeue</code>, the blocking in <code>dequeue</code> will be longer for the first call, but because <code>removeStack</code> stores stuff, subsequent runs may be faster. If <code>dequeue</code> is used more than <code>enqueue</code>, <code>dequeue</code> will simply be blocked most of the time, because it is waiting.</p>\n\n<p>Unfortunately using stack is not a good option for implementing a queue, because the 2 are completely reversed. There are more ways to implement, however they will all be blocking. So this really depends on how each method is used in relation to the other (frequency of calls, amount of read/write threads). </p>\n\n<h3>Snapshot on <code>addStack</code></h3>\n\n<p>An example for another implementation is to use a single stack, and limit the holding of the lock by taking a snapshot of it:</p>\n\n<pre><code>private Stack<Integer> stack = new Stack<>();\n\npublic int dequeue() {\n Stack<Integer> reverse = new Stack<>();\n Stack<Integer> copy;\n synchronized(lock) {\n copy = new Stack<>(stack);\n }\n\n while (!copy.isEmpty()) {\n reverse.push(copy.pop());\n }\n\n if (reverse.isEmpty()) {\n throw new NoSuchElementException(); \n }\n\n return reverse.pop();\n}\n</code></pre>\n\n<p>Of course, if <code>stack</code> has a lot of elements, the synchronized block may take some time. However it is just a complexity of <code>o(n)</code>.</p>\n\n<h2>Not using a stack</h2>\n\n<p>Of course not using a stack is always an option. There are many other data structures which can be used to implement a queue. However, the real problem is <strong>Enqueue and Dequeue need to be parallel</strong>.</p>\n\n<p>There are 2 ways to safely deal with data in a concurrent environment:</p>\n\n<ul>\n<li>Locks</li>\n<li>Atomic operations</li>\n</ul>\n\n<p>Locks, inherently can cause blocking. However, atomic operations, do not. So a true non-blocking implementation lays in using atomic operation.</p>\n\n<h3>Lock-free queue</h3>\n\n<p>The concept of a lock-free queue is to implement a queue, which is safe for use in concurrent environments, without using locks, which only leaves us with atomic operations for use. </p>\n\n<p>This is actually well known, but difficult to implement. Depending on the amount of read/write threads, the difficulty can increase.</p>\n\n<p>When working with a single writer thread, and a single reader thread it is actually quite simple.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T09:58:47.277",
"Id": "242328",
"ParentId": "242029",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T08:12:44.350",
"Id": "242029",
"Score": "1",
"Tags": [
"java",
"multithreading",
"concurrency",
"stack",
"queue"
],
"Title": "Concurrent Queue with enqueue and dequeue using Stack as underlying data structure"
}
|
242029
|
<p>I have made a linear interpolation functions as a side project of mine. It assumes everything is sorted before hand - x and f(x) are the same length.</p>
<p>I would like to ask for:</p>
<ul>
<li>general recommendations</li>
<li>if I can improve the design (generalize it to all iterables like <em>std::array</em> etc...)</li>
<li>and for further performance optimizations.</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <cmath>
#include <type_traits>
#include <vector>
#if (__cplusplus < 202002L)
template <typename T,
typename = std::enable_if_t<std::is_floating_point<T>::value>>
T lerp(T a, T b, T t) noexcept {
return a + t * (b - a);
}
#else
using std::lerp;
#endif
template <typename T,
typename = std::enable_if_t<std::is_floating_point<T>::value>>
class ListLerp {
public:
explicit ListLerp(const std::vector<T>& xp, const std::vector<T>& yp)
: xp(xp), yp(yp) {
b = this->xp.begin() + 1;
}
[[nodiscard]] T interp(const T x) noexcept {
// No extrapolation
if (x <= xp.front()) return yp.front();
if (x >= xp.back()) return yp.back();
// b = xp.begin() + 1;
// find b position
while (x > *b) b++;
// Calculate a, a_y, b_y from b
const auto a = b - 1;
const auto a_y = yp.begin() + (a - xp.begin());
const auto b_y = yp.begin() + (b - xp.begin());
const auto t = (x - *a) / (*b - *a);
return lerp(*a_y, *b_y, t);
};
private:
typename std::vector<T>::const_iterator b;
const std::vector<T>& xp;
const std::vector<T>& yp;
};
template <typename T,
typename = std::enable_if_t<std::is_floating_point<T>::value>>
std::vector<T> interp(const std::vector<T>& xp, const std::vector<T>& yp,
const std::vector<T>& x) {
std::vector<T> out(x.size());
auto lLerp = ListLerp(xp, yp);
std::transform(x.begin(), x.end(), out.begin(),
[&lLerp](const auto& xi) { return lLerp.interp(xi); });
return out;
}
///////////////
int main() {
std::vector<double> xp = {1, 2, 3};
std::vector<double> fp = {3, 2, 0};
for (auto &i : interp(xp, fp, {1, 1.5, 2.72})){
std::cout << " " << i;
}
std::cout << "\n";
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>template <typename T,\n typename = std::enable_if_t<std::is_floating_point<T>::value>>\nT lerp(T a, T b, T t) noexcept;\n</code></pre>\n\n<p>Looks fine. I'd prefer to see <code>static_assert</code> than <code>enable_if</code> since there's no other overloads (and if there are I'd rather fine out with a compilation error).</p>\n\n<pre><code>T lerp(T a, T b, T t) noexcept {\n return a + t * (b - a);\n}\n</code></pre>\n\n<p>How about <code>std::fma</code>?</p>\n\n<p>Note that GCC and Clang both do this differently... They do <code>b * t + a * (1-t)</code> and have special cases for <code>t</code> at 0 and near 1. Maybe it's better to just copy their code exactly so the compiler version doesn't change the output?</p>\n\n<hr>\n\n<pre><code>template <typename T,\n typename = std::enable_if_t<std::is_floating_point<T>::value>>\nstd::vector<T> interp(const std::vector<T>& xp, const std::vector<T>& yp,\n const std::vector<T>& x);\n</code></pre>\n\n<p>There's nothing in this function that directly needs T to be a floating point type. I think it's better to remove the <code>enable_if</code> and let the compiler show a traceback with the \"real\" reason T needs to be an FP.</p>\n\n<p>This function takes vectors and returns a new vector. That is a fine and very common pattern, but it's not optimally efficient. If this is a hot function, you could return an iterator/some sort of range that computes the next result when it is incremented. Boost example of this kind of thing: <a href=\"https://www.boost.org/doc/libs/1_66_0/libs/iterator/doc/html/iterator/specialized/transform.html\" rel=\"nofollow noreferrer\">https://www.boost.org/doc/libs/1_66_0/libs/iterator/doc/html/iterator/specialized/transform.html</a>.</p>\n\n<p>If you want to generalize this to other iterables, then don't take <code>std::vector</code>... instead take a templated <code>T const&</code> and same for <code>ListLerp</code>.</p>\n\n<hr>\n\n<pre><code>[[nodiscard]] T interp(const T x) noexcept;\n</code></pre>\n\n<p>Suppose I want to discard the result? Maybe I only want to store every nth item? <code>interp</code> is not a const member function (one might want the mutation to happen...) and T is not an \"undiscardable\" type. I don't see why this needs to be here.</p>\n\n<hr>\n\n<p>I don't think you've separated your interests very well between <code>ListLerp::interp</code> and the free function <code>interp</code>.</p>\n\n<p>I think there are two good options:</p>\n\n<ul>\n<li><p>make <code>ListLerp::interp</code> a const member function and get rid of <code>ListLerp::b</code>. Then the free function <code>interp</code> just does a \"pure\" transformation of a single list.</p></li>\n<li><p>iterate all three lists in a single function (my preference).</p></li>\n</ul>\n\n<p>E.g.</p>\n\n<pre><code>auto interp(vec const& a, vec const& b, vec const& t) {\n for idx = each index in a, b {\n ... Possibly emit a value corresponding to t ...\n }\n}\n</code></pre>\n\n<p>This is very basic pseudo code, but the key idea is you iterate everything in one go rather than doing some iteration in a free function and some iteration in a class that holds potentially dangerous references.</p>\n\n<hr>\n\n<pre><code>const std::vector<T>& xp;\n</code></pre>\n\n<p>This (and the lines like it) is moderately dangerous since you need to ensure the vector that is passed in outlives the class. </p>\n\n<p>E.g. you cannot do this:</p>\n\n<pre><code>auto fn() {\n vector<double> v;\n ListLerp ll(v); // take reference to local variable v\n return ll; // v goes out of scope; ll has dangling reference to dead v\n}\n</code></pre>\n\n<p>Often times the best option is to take the <code>const&</code> and be careful about how you use it, but in this case I think it's easy enough to compute the full result in a function, not expose a class that can hold a reference to a ctor argument, and make it impossible to end up with a dangling reference.</p>\n\n<hr>\n\n<blockquote>\n <p>It assumes everything is sorted before hand - x and f(x) are the same length.</p>\n</blockquote>\n\n<p>How about <code>assert</code>ing this?</p>\n\n<hr>\n\n<pre><code>// find b position\nwhile (x > *b) b++;\n</code></pre>\n\n<p>If your input is sorted, this could be a binary search. May or may not be better.</p>\n\n<hr>\n\n<p>I think your calculation at the end would be simpler if you use indices rather than iterators. Many of the lines are basically \"find the iterator in A that has the same index as this iterator in B\" ... easier to say \"A[i]\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T06:35:19.983",
"Id": "475026",
"Score": "0",
"body": "Thanks for your answer. I will play around with the suggestions. I have 2 questions. One about your note in the separation between ListLerp::interp - if you could give me an example. The reason ListLerp exists as a class in general is not to do a linear search in every item. Also if you could explain the co st reference issue a bit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T12:44:04.830",
"Id": "475060",
"Score": "0",
"body": "I made a few edits in the answer. Lmk what you think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T14:35:54.610",
"Id": "475078",
"Score": "0",
"body": "I see what you mean now, thx"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T02:57:12.120",
"Id": "242059",
"ParentId": "242030",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "242059",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T08:53:18.057",
"Id": "242030",
"Score": "3",
"Tags": [
"c++",
"vectors",
"numerical-methods",
"c++20"
],
"Title": "Linear Interpolation for sorted arrays"
}
|
242030
|
<p>I've just learned about custom wrapper classes and I'm a bit confused about a couple of things.
First, what's the utility of such tool? From what I understand you can mimic the copied class behaviour but with slight modifications. Is this tool used often?</p>
<p>Also, could you please have a look at my code? I know I'm suppose to close streams with "try with resources", but I'm not sure where it fits inside a constructor. Any other suggestions about the quality of my code are appreciated, please tear it apart!</p>
<pre><code>/*
UnsupportedFileName
Change the TxtInputStream class so that it only works with txt files (* .txt).
For example, first.txt or name.1.part3.txt.
If a non-txt file is passed (e.g. file.txt.exe), then the constructor should throw
an UnsupportedFileNameException.
Think about what else you need to do if an exception is thrown.
Requirements:
x 1. The TxtInputStream class must inherit the FileInputStream class.
2. If a txt file is passed to the constructor, TxtInputStream should behave like a regular FileInputStream.
3. If a non-txt file is passed to the constructor, an UnsupportedFileNameException should be thrown.
4. If an exception is thrown, then you must also call super.close().
*/
public class TxtInputStream extends FileInputStream {
private FileInputStream original;
public static String fileName;
public TxtInputStream(String fileName) throws IOException, UnsupportedFileNameException {
super(fileName);
if(fileName.substring(fileName.length()-4).equals(".txt")) {
this.fileName = fileName;
} else {
super.close();
throw new UnsupportedFileNameException();
}
}
public static void main(String[] args) {
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T09:10:19.543",
"Id": "474987",
"Score": "3",
"body": "Welcome to code review. *\" I know I'm suppose to close streams with \"try with resources\", but I'm not sure where it fits inside a constructor.\"* **---** In a **constructor** you should only assign its **parameters** to **member variables**. Especially you should **not** do anything that could result in an `Exception` to be thrown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T09:13:07.467",
"Id": "474988",
"Score": "0",
"body": "@TimothyTruckle so this is a poorly designed exercise I suppose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T09:13:46.133",
"Id": "474989",
"Score": "2",
"body": "*\"so this is a poorly designed exercise?\"* **---** I strongly agree to that statement. ;o)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T21:52:12.263",
"Id": "490185",
"Score": "0",
"body": "\"Especially you should not do anything that could result in an Exception to be thrown.\" @TimothyTruckle there is nothing wrong with performing argument validation in a constructor and throwing an exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T06:43:29.403",
"Id": "490202",
"Score": "0",
"body": "@Marcono1234 *\"there is nothing wrong with performing argument validation in a constructor\"* -- It depends. As long as no additional dependency is needed to do some simple validation (e.g. check for `null`) *might* be acceptable but usually the constructor arguments should be checked *before* calling the constructor. Especially when talking about DTOs this can dramatically simplify unit test configurations where you often don't deed these DTOs having consistent configuration. Business classes should not have constructor parameters that need to be consistent beyond not being `null` anyway. ;o)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T06:47:14.893",
"Id": "490203",
"Score": "0",
"body": "@Marcono1234 *\"there is nothing wrong with performing argument validation in a constructor\"* -- Another Point is: what will the caller do with such exception? If the calling code does something else then just showing the error to the user and fail, chances are that you misuse the exception mechanism as control flow."
}
] |
[
{
"body": "<p>The cleanest way to solve this would probably be to check the argument <em>before</em> calling the super constructor. This allows the code to fail fast and prevents it from opening the file, rendering the <code>close()</code> call unnecessary:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class TxtInputStream extends FileInputStream {\n public TextInputStream(String fileName) {\n // super call must be first statement so have to call validation method\n // as argument to super call\n super(checkFileName(fileName));\n }\n\n private static String checkFileName(String fileName) {\n if (!fileName.endsWith(".txt")) {\n throw new UnsupportedFileNameException();\n }\n return fileName;\n }\n}\n</code></pre>\n<p>However, this is a pretty bad example for wrappers since the <code>TxtInputStream</code> does not add any functionality at all.</p>\n<p>If you want to see some good examples have at look at which JDK classes implement <code>InputStream</code>:</p>\n<ul>\n<li><a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/BufferedInputStream.html\" rel=\"nofollow noreferrer\"><code>BufferedInputStream</code></a>: Buffers data, this can be useful when you are only consuming small amounts of data at a time, but reading such small amounts of data would be inefficient, e.g. for a network connection. Instead it reads larger chunks from the wrapped InputStream and when you then consume data it first serves it from the buffer.</li>\n<li><a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/crypto/CipherInputStream.html\" rel=\"nofollow noreferrer\"><code>CipherInputStream</code></a>: Decrypts the data</li>\n<li><a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/InflaterInputStream.html\" rel=\"nofollow noreferrer\"><code>InflaterInputStream</code></a>: Uncompresses data</li>\n</ul>\n<p>So assuming you read encrypted, compressed data over the network you could have:</p>\n<pre class=\"lang-java prettyprint-override\"><code>InputStream networkInputStream = ...\nBufferedInputStream bufferedInputStream = new BufferedInputStream(networkInputStream);\nCipherInputStream cipherInputStream = new CipherInputStream(bufferedInputStream, cipher);\nInflaterInputStream inflaterInputStream = new InflaterInputStream(cipherInputStream);\n</code></pre>\n<p>Then you can simply use <code>inflaterInputStream</code> like any other <code>InputStream</code> and do not even have to worry about all the previous processing steps which are taking place.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T22:10:53.210",
"Id": "249931",
"ParentId": "242031",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T08:53:41.947",
"Id": "242031",
"Score": "1",
"Tags": [
"java"
],
"Title": "Java FileInputStream exercise"
}
|
242031
|
<p>The rules of John Conway's <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">Game of Life</a> are simple: </p>
<ul>
<li>An OFF pixel that has 3 live neighbours is turned ON.</li>
<li>An ON pixel that has anything other than 2 or 3 live neighbours is turned OFF.</li>
</ul>
<p>Many people that program this game select the easiest of video modes: the 320x200 256-color mode. To satisfy my desire for a smooth animation and to really challenge myself, I chose to run the game on the legacy video mode with the highest spatial resolution. So mode 12h, a 640x480 16-color mode. That's a lot more pixels!</p>
<h2>Key features</h2>
<p>I never read the video memory (VRAM) because that would be extremely slow. <strong>I store info about what is displayed on the screen in a couple of matrices in regular memory</strong>. Both these matrices have the same dimensions and during the game, in preparation for the next generation, the contents of the 'WriteMatrix' is copied onto the 'ReadMatrix'. Although this is a fairly big copy, my tests have shown that using SIMD instructions wasn't worthwhile. What a pity!</p>
<p>I don't output a pixel at a time because on a planar video mode it would involve reading from the video memory in order to combine the new pixel with what is already displayed. <strong>My program outputs 32 pixels at once</strong>. And because the game is intrinsically monochrome it's enough to simply write to the video aperture. No need to use any of the VGA specifics (like ports).</p>
<p>Instead of counting the number of neighbours that are alive, <strong>I maintain info about how many live neighbours a pixel has in a 3-bit counter</strong> stored adjacent to the pixel's ON/OFF state.
To enhance data density <strong>I store the information for 2 pixels in every byte-sized matrix element</strong>, using next layout:</p>
<pre class="lang-none prettyprint-override"><code> Pixel with an even X Pixel with an odd X
----------------------------- ----------------------------
bit 7 bits 6-4 bit 3 bits 2-0
ON/OFF state Neighbour count ON/OFF state Neigbour count
</code></pre>
<p>The 3-bit field can not store the full neighbour count which ranges from 0 to 8, but the count can easily be completed using the state bit of the special 'closest' neighbour (held within the same matrix element).</p>
<p>The game's surface doesn't end at the edges of the screen! e.g. When a pixel moves off the screen's right edge, it re-enters via the left edge. This is true for all the edges. <strong>Think of the opposing edges of the screen being stitched together, producing a toroidal surface</strong>. This is the most interesting approach but also a little more involved. It's also the reason why my 2 matrices have an extra top and bottom line.</p>
<h2>Running the program</h2>
<p>The game begins with drawing approx. 50 % of ON pixels. As a leftover from experimentation (you are invited to experiment on this further) I leave the edges of the screen free from pixels. At this point the WriteMatrix is also initialized. After inspection of the initial screen a keypress is expected. I have not wasted any time optimizing this initialization phase.</p>
<p>When I do the matrix copying, I use <code>rep movsw</code> because that was the fastest. For the copies of the top and bottom lines, that require corrections because they are stitched to the opposite edges, I've unrolled the loop for best performance. Using the SIMD <code>paddb</code> instruction was marginally better, but I judged against it so that people that can't run this program from real address mode, could still run it from an emulator like DOSBox. Optimizing this part of the program is unlikely to speed up much, since it accounts for little over 1% of the execution time.</p>
<p>To produce the next generation I use a couple of nested loops. The outer loop runs in the Y direction and in order to minimize changing the segment registers I subdivided the operation in 3 bands that each process 160 lines. Because the pixel at the far left and the pixel at the far right are special in that they make changes at the opposite edges, I've peeled these off from the inner loop. The inner loop runs in the X direction and has been unrolled foremost because processing pixels at an even X or at an odd X is different anyway. These loops (and their subroutines) were heavily optimized to the extent that it's no longer nice code to look at. Hopefully the experts here can still give me some pointers.</p>
<p>The user can control the game via the keyboard. Pressing any key will halt the game and display in the upper left corner of the screen the number of pixels that changed state (in green) in the most recent generation (in red). The key that the user presses next decides about what happens then. <kbd>ESC</kbd> exits the program, <kbd>SPC</kbd> will rapidly produce the next generation and halt again, and any other key will continue the game at full speed.</p>
<hr>
<p>I ran the program on a 1.73 GHz Pentium dual-core T2080.<br>
The table below summarizes my tests (<em>gps</em> is GenerationsPerSecond):</p>
<pre class="lang-none prettyprint-override"><code>Resolution Total time First sec. Last sec. Average
---------- ---------- ---------- --------- --------
640x480 24 s 216 gps 379 gps 352 gps ; Pulsar appears after 15 seconds!
640x400 16 s 268 gps 453 gps 410 gps
640x350 10 s 316 gps 516 gps 454 gps
320x200 4 s 1324 gps 1776 gps 1580 gps
</code></pre>
<p>The game 'ends' when there's but <em>still-live</em> and <em>oscillators</em> left.</p>
<hr>
<p>I was somewhat disappointed about the speed gain from using SIMD instructions.<br>
Does anyone know of a solution that leans more on using SIMD (up to SSE3)?</p>
<p>What would be a good method to detect that the game has fallen into merely oscillatting? I have tried the method of discovering a repeating pattern in the number of changed pixels. It works fine for my test data, but is this the way to go in general?</p>
<pre class="lang-none prettyprint-override"><code>; John Conway's Game of Life (c) 2020 Sep Roland
; ----------------------------------------------
; assemble with FASM
SW=640 ; ScreenWidth
SH=480 ; ScreenHeight
LL=SW/2 ; LineLength (Matrices store 2 pixels
BW=SH/3 ; BandWidth per byte-sized element)
ORG 256
cld
mov ax, 0A000h
mov gs, ax ; CONST VideoSegment
mov bx, cs
add bx, 256 ; Align 4096 on matrices
mov dx, 2*(LL*(SH+2))/16 ; ReadMatrix and WriteMatrix
mov ax, [0002h] ; PSP.NXTGRAF
sub ax, dx
cmp ax, bx
jb Exit
mov [InitSRegs+2], bx ; MemoryBase
mov sp, 0100h
mov ax, 0012h ; BIOS.SetVideo graphics mode 640x480x4
int 10h
call GameOfLife
mov ax, 0003h ; BIOS.SetVideo text mode 80x25
int 10h
Exit: mov ax, 4C00h ; DOS.Terminate
int 21h
; --------------------------------------
ALIGN 4
X1 dw 1 ; Window for initial pixels
Y1 dw 1
X2 dw SW-2
Y2 dw SH-2
; --------------------------------------
db (16-($+5)) and 15 dup 90h ; To align .NextG
; IN (bx,dx)
GameOfLife:
call InitMatricesAndScreen ; -> (EAX BX..BP DS ES)
xor dx, dx ; Number of generations
.NextG: inc dx
call CopyMatrices ; -> (AX..CX SI..BP DS..FS)
call ProduceNextGeneration ; -> CX (EAX BX SI..BP DS ES)
; Pause the game on presence of any key
mov ah, 01h ; BIOS.CheckKey
int 16h ; -> AX ZF
jz .NextG
mov ah, 00h ; BIOS.GetKey
int 16h ; -> AX
.ShowI: mov bx, 000Ch ; DisplayPage and LightRedOnBlack
mov ax, dx ; DX is number of generations
call .PrintNumber
mov bl, 0Ah ; LightGreenOnBlack
mov ax, cx ; CX is number of changed pixels
call .PrintNumber
mov ax, 0E0Dh ; BIOS.Teletype
int 10h
; Decide what to do next based on specific keys
mov ah, 00h ; BIOS.GetKey
int 16h ; -> AX
cmp al, 27 ; ESC is EndOfGame
je .End
cmp al, 32 ; SPC is SingleStep
jne .NextG
mov cx, ax
mov ah, 05h ; BIOS.WriteKey
int 16h
jmp .NextG
.End: ret
; - - - - - - - - - - - - - - - - - - -
; IN (ax) OUT ()
.PrintNumber:
pusha
mov di, 10
push " " ; Sentinel and separator
@@: xor dx, dx
div di
add dl, "0"
push dx
test ax, ax
jnz @b
@@: pop ax
mov ah, 0Eh ; BIOS.Teletype
int 10h
cmp al, 32
jne @b
popa
ret
; --------------------------------------
; IN (bx,dx) OUT () MOD (eax,bx,cx,dx,si,di,bp,ds,es)
InitMatricesAndScreen:
shr dx, 1 ; Leave ReadMatrix alone
; Clear WriteMatrix
mov bp, 4096 ; CONST
xor di, di
xor ax, ax
jmp .b
.a: mov cx, 65536/2 ; Clear 64KB
rep stosw
add bx, bp ; BX is alias for ES
.b: mov es, bx
sub dx, bp
ja .a ; Have more than 64KB
add dx, bp
imul cx, dx, 16/2
rep stosw
; Fill WriteMatrix and Screen with approx. 50% of ON pixels
xor bp, bp ; GS:BP is VideoPointer
xor si, si ; Random Seed
mov dx, SH-1 ; Y
mov cx, SW-1 ; X
xor bx, bx ; Offset (paragraphs) in WriteMatrix
.c: push bx ; (1)
call InitSRegs ; -> AX=DS BX=ES
mov di, LL ; Current position in a 3-line window
.d: call .InitEvenPixel ; -> EAX CX DX SI
call .InitOddPixel ; -> EAX CX DX SI
inc di
test di, 15
jnz .e
call .WritePixels ; -> BP (EAX)
.e: cmp di, LL*2 ; At end of line ?
jb .d ; No
pop bx ; (1)
add bx, LL/16 ; Window travels down in WriteMatrix
cmp bp, (SW/8)*SH ; At end of screen ?
jb .c ; No
; Inspect the initial screen
mov ah, 00h ; BIOS.GetKey
int 16h ; -> AX
ret
; - - - - - - - - - - - - - - - - - - -
; IN (eax,cx,dx,si,ds:di) OUT (eax,cx,dx,si)
.InitEvenPixel:
shl eax, 1
call .DecideAboutPixel ; -> CX DX SI SF
js @f
inc ax ; ON pixel
add word [di-1-LL], 0001'0001'0000'0001b
add word [di-1], 1000'0000'0000'0001b
add word [di-1+LL], 0001'0001'0000'0001b
@@: ret
; - - - - - - - - - - - - - - - - - - -
; IN (eax,cx,dx,si,ds:di) OUT (eax,cx,dx,si)
.InitOddPixel:
shl eax, 1
call .DecideAboutPixel ; -> CX DX SI SF
js @f
inc ax ; ON pixel
add word [di-LL], 0001'0000'0001'0001b
add word [di], 0001'0000'0000'1000b
add word [di+LL], 0001'0000'0001'0001b
@@: ret
; - - - - - - - - - - - - - - - - - - -
; IN (cx,dx,si) OUT (cx,dx,si,SF)
.DecideAboutPixel:
inc cx ; Go to next (X,Y)
cmp cx, SW
jb @f
xor cx, cx
inc dx
cmp dx, SH
jb @f
xor dx, dx
@@: cmp cx, [cs:X1] ; Confine to (X1,Y1)-(X2,Y2)
js @f
cmp dx, [cs:Y1]
js @f
cmp [cs:X2], cx
js @f
cmp [cs:Y2], dx
js @f
imul si, 25173 ; Next random number
add si, 13849
xor si, 62832
@@: ret
; - - - - - - - - - - - - - - - - - - -
; IN (eax,gs:bp) OUT (bp) MOD (eax)
.WritePixels:
bswap eax
mov [gs:bp], eax ; Writing 32 pixels at once
add bp, 4
ret
; --------------------------------------
ALIGN 16
; IN (bx) OUT (ax=ds,bx=es)
InitSRegs: ; BX is optional offset in paragraphs
add bx, word 0 ; SMC, MemoryBase
lea ax, [bx+(LL*(SH+2))/16]
xchg ax, bx
mov ds, ax ; DS refers to WriteMatrix or higher up
mov es, bx ; ES refers to ReadMatrix or higher up
ret
LEA BX, [WORD BX+0]
LEA BX, [WORD BX+0]
; --------------------------------------
; IN () OUT () MOD (ax,bx,cx,si,di,bp,ds,es,fs)
CopyMatrices: ; Copies from WriteMatrix to ReadMatrix
; Copy all lines between top and bottom unmodified
push dx ; (1)
mov bx, (LL*2)/16
call InitSRegs ; -> AX=DS BX=ES
mov bp, 4096 ; CONST
mov di, 0
mov si, 0
mov dx, (LL*(SH-2))/16 ; Number of paragraphs to copy
sub dx, bp ; between matrices
jbe .b
.a: mov cx, 65536/2 ; Copy 64KB
rep movsw
add bx, bp ; BX is alias for ES
add ax, bp ; AX is alias for DS
mov es, bx
mov ds, ax
sub dx, bp
ja .a ; Have more than 64KB
.b: add dx, bp
imul cx, dx, WORD 16/2
rep movsw
pop dx ; (1)
; Copy the top line with corrections because it is stitched to the bottom line
mov bx, 0
mov cx, (LL*SH)/16
mov si, LL
call .Copy1
; Copy the bottom line with corrections because it is stitched to the top line
mov bx, cx
neg cx
xor si, si
.Copy1: call InitSRegs ; -> AX=DS BX=ES
add ax, cx
mov fs, ax
lea bx, [si+LL]
.c: mov bp, [si+2]
mov ax, [si]
add bp, [fs:si+2]
add ax, [fs:si]
mov [es:si+2], bp
mov [es:si], ax
add si, 4
cmp si, bx
jb .c
ret
LEA BX, [WORD BX+0]
; --------------------------------------
; IN () OUT (cx) MOD (eax,bx,si,di,bp,ds,es)
ProduceNextGeneration:
; Conditions in ReadMatrix define what changes in WriteMatrix
xor bp, bp ; GS:BP is VideoPointer
xor cx, cx ; Number of changed pixels
xor bx, bx
RepeatOuterLoop:
push bx ; (1)
call InitSRegs ; -> AX=DS BX=ES
mov di, LL ; Current place in a couple of
OuterLoop: ; (BW+2)-line windows on both matrices
lea si, [di+LL-1] ; End of current line in matrix
mov bl, [es: WORD di+0] ; ReadMatrix
shl eax, 1
and bx, 00F0h ; Even X=0
jmp word [cs:TableA+bx] ; -> EAX
BackA: call InnerLoop ; -> EAX DI BP (BL)
mov bl, [es:di] ; ReadMatrix
shl eax, 1
shl bx, 1
and bx, 001Eh ; Odd X=SW-1
jmp word [cs:TableD+bx] ; -> EAX
BackD: bswap eax
mov [gs:bp], eax ; Writing 32 pixels at once
add bp, WORD 4
inc di
cmp di, LL+(LL*BW) ; Process BW count matrix lines
jb OuterLoop ; w/o changing segment registers
pop bx ; (1)
add bx, (LL/16)*BW ; Windows travel down in both matrices
cmp bp, (SW/8)*SH ; At end of screen ?
jb RepeatOuterLoop ; No
ret
; --------------------------------------
ALIGN 16
; Pixels on even X=0 coordinates
TableA: dw BackA, 7 dup 0 ; 0 OFF pixel with 0 or 1 neighbour
dw BackA, 7 dup 0 ; 1 OFF pixel with 1 or 2 neighbours
dw .TST2, 7 dup 0 ; 2 OFF pixel with 2 or 3 neighbours
dw .TST3, 7 dup 0 ; 3 OFF pixel with 3 or 4 neighbours
dw BackA, 7 dup 0 ; 4 OFF pixel with 4 or 5 neighbours
dw BackA, 7 dup 0 ; 5 OFF pixel with 5 or 6 neighbours
dw BackA, 7 dup 0 ; 6 OFF pixel with 6 or 7 neighbours
dw BackA, 7 dup 0 ; 7 OFF pixel with 7 or 8 neighbours
dw .OFF, 7 dup 0 ; 8 ON pixel with 0 or 1 neighbour
dw .TST9, 7 dup 0 ; 9 ON pixel with 1 or 2 neighbours
dw .STAY, 7 dup 0 ; 10 ON pixel with 2 or 3 neighbours
dw .TST11, 7 dup 0 ; 11 ON pixel with 3 or 4 neighbours
dw .OFF, 7 dup 0 ; 12 ON pixel with 4 or 5 neighbours
dw .OFF, 7 dup 0 ; 13 ON pixel with 5 or 6 neighbours
dw .OFF, 7 dup 0 ; 14 ON pixel with 6 or 7 neighbours
dw .OFF, 7 dup 0 ; 15 ON pixel with 7 or 8 neighbours
; - - - - - - - - - - - - - - - - - - -
; An OFF pixel with 2 registered neighbours
.TST2: test byte [es:di], 0000'1000b
jz BackA ; One neighbour short to turn ON
.ON: inc cx
add byte [di-LL], 0001'0001b
add byte [di], 1000'0000b
add byte [di+LL], 0001'0001b
add byte [di-1], 0000'0001b
add byte [di-1+LL], 0000'0001b
add byte [di-1+LL*2], 0000'0001b
inc ax
jmp BackA
; - - - - - - - - - - - - - - - - - - -
ALIGN 16
; An OFF pixel with 3 registered neighbours
.TST3: test byte [es:di], 0000'1000b
jz .ON ; Has 3 neighbours
jmp BackA
; - - - - - - - - - - - - - - - - - - -
db (16-($+6)) and 15 dup 90h ; To align .OFF
; An ON pixel with 1 registered neighbour
.TST9: test byte [es:di], 0000'1000b
jnz .STAY ; Has 2 neighbours
.OFF: inc cx
sub byte [di-LL], 0001'0001b
sub byte [di], 1000'0000b
sub byte [di+LL], 0001'0001b
sub byte [di-1], 0000'0001b
sub byte [di-1+LL], 0000'0001b
sub byte [di-1+LL*2], 0000'0001b
jmp BackA
; - - - - - - - - - - - - - - - - - - -
; An ON pixel with 3 registered neighbours
.TST11: test byte [es:di], 0000'1000b
jnz .OFF ; Has more than 3 neighbours
; --- --- --- --- --- --- --
.STAY: inc ax
jmp BackA
; --------------------------------------
ALIGN 64
InnerLoop:
mov bl, [es:di] ; ReadMatrix
shl eax, 1
and bx, 000Fh ; Odd X
shl bx, 1
jmp word [cs:TableB+bx] ; -> EAX
BackB: movzx bx, byte [es:di+1] ; ReadMatrix
inc di
and bx, 00F0h ; Even X
test di, 15
jz Plot
shl eax, 1
jmp word [cs:TableC+bx] ; -> EAX
BackC: cmp di, si ; Just before the end of line ?
jb InnerLoop ; No
ret
Plot: bswap eax
mov [gs:bp], eax ; Writing 32 pixels at once
add bp, 4
xor eax, eax
jmp word [cs:TableC+bx] ; -> EAX
NOP
; --------------------------------------
ALIGN 16
; Pixels on odd X<>SW-1 coordinates
TableB: dw BackB ; 0 OFF pixel with 0 or 1 neighbour
dw BackB ; 1 OFF pixel with 1 or 2 neighbours
dw .TST2 ; 2 OFF pixel with 2 or 3 neighbours
dw .TST3 ; 3 OFF pixel with 3 or 4 neighbours
dw BackB ; 4 OFF pixel with 4 or 5 neighbours
dw BackB ; 5 OFF pixel with 5 or 6 neighbours
dw BackB ; 6 OFF pixel with 6 or 7 neighbours
dw BackB ; 7 OFF pixel with 7 or 8 neighbours
dw .OFF ; 8 ON pixel with 0 or 1 neighbour
dw .TST9 ; 9 ON pixel with 1 or 2 neighbours
dw .STAY ; 10 ON pixel with 2 or 3 neighbours
dw .TST11 ; 11 ON pixel with 3 or 4 neighbours
dw .OFF ; 12 ON pixel with 4 or 5 neighbours
dw .OFF ; 13 ON pixel with 5 or 6 neighbours
dw .OFF ; 14 ON pixel with 6 or 7 neighbours
dw .OFF ; 15 ON pixel with 7 or 8 neighbours
; - - - - - - - - - - - - - - - - - - -
; An OFF pixel with 2 registered neighbours
.TST2: test byte [es:di], 1000'0000b
jns BackB ; One neighbour short to turn ON
.ON: inc cx
add word [di-LL], 0001'0000'0001'0001b
add word [di], 0001'0000'0000'1000b
add word [di+LL], 0001'0000'0001'0001b
inc ax
jmp BackB
; - - - - - - - - - - - - - - - - - - -
ALIGN 16
; An OFF pixel with 3 registered neighbours
.TST3: test byte [es:di], 1000'0000b
jns .ON ; Has 3 neighbours
jmp BackB
; - - - - - - - - - - - - - - - - - - -
db (16-($+6)) and 15 dup 90h ; To align .OFF
; An ON pixel with 1 registered neighbour
.TST9: test byte [es:di], 1000'0000b
js .STAY ; Has 2 neighbours
.OFF: inc cx
sub word [di-LL], 0001'0000'0001'0001b
sub word [di], 0001'0000'0000'1000b
sub word [di+LL], 0001'0000'0001'0001b
jmp BackB
; - - - - - - - - - - - - - - - - - - -
; An ON pixel with 3 registered neighbours
.TST11: test byte [es:di], 1000'0000b
js .OFF ; Has more than 3 neighbours
; --- --- --- --- --- --- --
.STAY: inc ax
jmp BackB
; --------------------------------------
ALIGN 16
; Pixels on even X<>0 coordinates
TableC: dw BackC, 7 dup 0 ; 0 OFF pixel with 0 or 1 neighbour
dw BackC, 7 dup 0 ; 1 OFF pixel with 1 or 2 neighbours
dw .TST2, 7 dup 0 ; 2 OFF pixel with 2 or 3 neighbours
dw .TST3, 7 dup 0 ; 3 OFF pixel with 3 or 4 neighbours
dw BackC, 7 dup 0 ; 4 OFF pixel with 4 or 5 neighbours
dw BackC, 7 dup 0 ; 5 OFF pixel with 5 or 6 neighbours
dw BackC, 7 dup 0 ; 6 OFF pixel with 6 or 7 neighbours
dw BackC, 7 dup 0 ; 7 OFF pixel with 7 or 8 neighbours
dw .OFF, 7 dup 0 ; 8 ON pixel with 0 or 1 neighbour
dw .TST9, 7 dup 0 ; 9 ON pixel with 1 or 2 neighbours
dw .STAY, 7 dup 0 ; 10 ON pixel with 2 or 3 neighbours
dw .TST11, 7 dup 0 ; 11 ON pixel with 3 or 4 neighbours
dw .OFF, 7 dup 0 ; 12 ON pixel with 4 or 5 neighbours
dw .OFF, 7 dup 0 ; 13 ON pixel with 5 or 6 neighbours
dw .OFF, 7 dup 0 ; 14 ON pixel with 6 or 7 neighbours
dw .OFF, 7 dup 0 ; 15 ON pixel with 7 or 8 neighbours
; - - - - - - - - - - - - - - - - - - -
; An OFF pixel with 2 registered neighbours
.TST2: test byte [es:di], 0000'1000b
jz BackC ; One neighbour short to turn ON
.ON: inc cx
add word [di-1-LL], 0001'0001'0000'0001b
add word [di-1], 1000'0000'0000'0001b
add word [di-1+LL], 0001'0001'0000'0001b
inc ax
jmp BackC
; - - - - - - - - - - - - - - - - - - -
ALIGN 16
; An OFF pixel with 3 registered neighbours
.TST3: test byte [es:di], 0000'1000b
jz .ON ; Has 3 neighbours
jmp BackC
; - - - - - - - - - - - - - - - - - - -
db (16-($+6)) and 15 dup 90h ; To align .OFF
; An ON pixel with 1 registered neighbour
.TST9: test byte [es:di], 0000'1000b
jnz .STAY ; Has 2 neighbours
.OFF: inc cx
sub word [di-1-LL], 0001'0001'0000'0001b
sub word [di-1], 1000'0000'0000'0001b
sub word [di-1+LL], 0001'0001'0000'0001b
jmp BackC
; - - - - - - - - - - - - - - - - - - -
; An ON pixel with 3 registered neighbours
.TST11: test byte [es:di], 0000'1000b
jnz .OFF ; Has more than 3 neighbours
; --- --- --- --- --- --- --
.STAY: inc ax
jmp BackC
; --------------------------------------
ALIGN 16
; Pixels on odd X=SW-1 coordinates
TableD: dw BackD ; 0 OFF pixel with 0 or 1 neighbour
dw BackD ; 1 OFF pixel with 1 or 2 neighbours
dw .TST2 ; 2 OFF pixel with 2 or 3 neighbours
dw .TST3 ; 3 OFF pixel with 3 or 4 neighbours
dw BackD ; 4 OFF pixel with 4 or 5 neighbours
dw BackD ; 5 OFF pixel with 5 or 6 neighbours
dw BackD ; 6 OFF pixel with 6 or 7 neighbours
dw BackD ; 7 OFF pixel with 7 or 8 neighbours
dw .OFF ; 8 ON pixel with 0 or 1 neighbour
dw .TST9 ; 9 ON pixel with 1 or 2 neighbours
dw .STAY ; 10 ON pixel with 2 or 3 neighbours
dw .TST11 ; 11 ON pixel with 3 or 4 neighbours
dw .OFF ; 12 ON pixel with 4 or 5 neighbours
dw .OFF ; 13 ON pixel with 5 or 6 neighbours
dw .OFF ; 14 ON pixel with 6 or 7 neighbours
dw .OFF ; 15 ON pixel with 7 or 8 neighbours
; - - - - - - - - - - - - - - - - - - -
; An OFF pixel with 2 registered neighbours
.TST2: test byte [es:di], 1000'0000b
jns BackD ; 2 neighbours is not enough
.ON: inc cx
add byte [di-LL], 0001'0001b
add byte [di], 0000'1000b
add byte [di+LL], 0001'0001b
add byte [di+1-LL*2], 0001'0000b
add byte [di+1-LL], 0001'0000b
add byte [di+1], 0001'0000b
inc ax
jmp BackD
; - - - - - - - - - - - - - - - - - - -
ALIGN 16
; An OFF pixel with 3 registered neighbours
.TST3: test byte [es:di], 1000'0000b
jns .ON ; Has 3 neighbours
jmp BackD
; - - - - - - - - - - - - - - - - - - -
db (16-($+6)) and 15 dup 90h ; To align .OFF
; An ON pixel with 1 registered neighbour
.TST9: test byte [es:di], 1000'0000b
js .STAY ; Has 2 neighbours
.OFF: inc cx
sub byte [di-LL], 0001'0001b
sub byte [di], 0000'1000b
sub byte [di+LL], 0001'0001b
sub byte [di+1-LL*2], 0001'0000b
sub byte [di+1-LL], 0001'0000b
sub byte [di+1], 0001'0000b
jmp BackD
; - - - - - - - - - - - - - - - - - - -
; An ON pixel with 3 registered neighbours
.TST11: test byte [es:di], 1000'0000b
js .OFF ; Has more than 3 neighbours
; --- --- --- --- --- --- --
.STAY: inc ax
jmp BackD
; --------------------------------------
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T10:03:44.737",
"Id": "498459",
"Score": "0",
"body": "related: https://lemire.me/blog/2018/07/18/accelerating-conways-game-of-life-with-simd-instructions/ shows an AVX2 version. (If you want to keep using 16-bit mode, SSE is usable but VEX-encoded instructions like AVX / AVX2 aren't.)"
}
] |
[
{
"body": "<p>If you only want to detect oscillating between two states, you method will probably work, but it will have some false positives (think things are oscillating when they aren't, and abort too early). There are ways to improve it (add counts for each row and column comes to mind) but ultimately it'll be a heuristic and sometimes fail.</p>\n<p>A PERFECT method to detect oscillation (of any cycle length, not just length 2), is to use a cycle-finding algorithm. The easiest-to-understand one is Floyd's cycle-finding algorithm, also called the tortoise and the hare. It will use 2X the memory, and 3-4X the time.</p>\n<p>At each game step, increment board A one step (which you display) and board B two steps (which you never display). If board A == board B, the game is about to cycle. (IMO, if this is a screensaver, I would run it for a few cycles after you detect this, it's still nice to look at for a while)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:21:06.837",
"Id": "251585",
"ParentId": "242033",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T10:46:09.680",
"Id": "242033",
"Score": "3",
"Tags": [
"performance",
"assembly",
"game-of-life",
"x86"
],
"Title": "A very fast Game of Life"
}
|
242033
|
<p>Could you please tear my code apart? It's an exercise from CodeGym. Recently I changed a few things within my coding practices, namely:</p>
<ol>
<li>Not writing all my solutions on main. Instead, trying to create methods to make the code more organised. </li>
<li>Instantiating the class on main to call the methods.</li>
<li>Using try with resources</li>
<li>Pay close attention to indentation</li>
</ol>
<p>I have on specific question. What types of comments would you write on that code, if any. </p>
<p>Thanks!</p>
<pre><code>/*
ABCs
The first parameter of the main method is a file name.
Count the letters of the English alphabet in the file.
Display the number of letters.
Close the streams.
Requirements:
1. You don't need to read anything from the console.
2. Create a stream to read from the file passed as the first argument of the main method.
3. You need to count the letters of the English alphabet in the file and display the number.
4. You must count both uppercase and lowercase letters.
5. The stream used to read the file must be closed.
*/
import java.io.FileInputStream;
import java.io.IOException;
public class Solution {
private void countLetters (String args) {
char[] array = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int count = 0;
try (FileInputStream in = new FileInputStream(String.valueOf(args))) {
int ch;
while ((ch = in.read()) != -1) {
for (int i = 0; i < array.length; i++) {
if (ch == array[i]) {
count++;
}
}
}
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
}
printCount(count);
}
private void printCount (int count) {
System.out.println(count);
}
public static void main(String[] args) {
Solution solution = new Solution();
solution.countLetters(args[0]);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have one suggestion.</p>\n\n<h1>Instead of building your own character sets, use the provided methods</h1>\n\n<p>In your code, you build your own array to check if the values are either lower or upper case letters; I suggest that you use the provided <code>java.lang.Character#isLetter(int)</code>. This method will handle both types. Also, you will gain some performance, since in your implementation, you were not stopping the iteration, when finding the letter.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nwhile ((ch = in.read()) != -1) {\n for (int i = 0; i < array.length; i++) {\n if (ch == array[i]) {\n count++; // Here, you could break the loop, since you found the character.\n // break;\n }\n }\n}\n//[...]\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nwhile ((ch = in.read()) != -1) {\n if (Character.isLetter(ch)) {\n count++;\n }\n}\n//[...]\n</code></pre>\n\n<p>For the rest, you use the <code>java.lang.AutoCloseable</code> correctly (try) and your code encapsulation is good; good job!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T06:39:27.870",
"Id": "475027",
"Score": "2",
"body": "The assignment required counting letters in the English alphabet. Using Character.isLetter(char) includes letters in all locales, which breaks the specification."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T14:51:34.233",
"Id": "242038",
"ParentId": "242035",
"Score": "2"
}
},
{
"body": "<p><strong>Naming</strong></p>\n\n<p>Class name <code>Solution</code> does not describe the purpose of the class beyond it being a solution to some random assignment. For the sole purpose of archiving exercises I would name the package with the identifier of the assignment and use a more descriptive class name: <code>your.domain.codegym.exercise42.LetterCounter</code> and put the URL to the assignment in the JavaDoc (maybe package.html). BTW: If you haven't done already, I recommend setting up a GitLab repo for your exercises. One of my regrets is that I've lost so much code I wrote when I was young because broken hard disks and obsoleted hardware. We didn't have on-line repos then...</p>\n\n<p>The parameter name <code>args</code> in the <code>countLetters</code> method does not tell what it is supposed to contain and it is misleading as the plural suffix 's' implies that the parameter would contain multiple values. The parameter should be named as <code>fileName</code>.</p>\n\n<p><strong>Unnecessary object initialization</strong></p>\n\n<p>The method <code>countLetters</code> does not rely on any member variable from the <code>Solution</code> class and the counter does not hold any state between invocations to <code>countLetters</code>. There is no need for the method to require a the Solution class to be instantiated. It could very well be a <code>public static void countLetters(...)</code>. If the assignment required that an object is to be initialized, then the requirement is a bit artificial.</p>\n\n<p><strong>Inefficient algorithm</strong></p>\n\n<p>The array that contains the english alphabet letters never changes. It should be a static field in the Solution class. As it is now, your code allocates a new array for the alphabet every time your method is called. But an array like this is also a very inefficient way to look for a letter. As the US-ASCII charset fits in 7 bits and the upper and lower case letters form two consecutive blocks in the <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">character table</a>. You can simply compare the character to first and last letter:</p>\n\n<pre><code>if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {\n count++;\n}\n</code></pre>\n\n<p>Note that this approach does not work if the text in the file is in a character set that does not inherit US-ASCII. That would be very very rare these days.</p>\n\n<p><strong>Multiple responsibilities</strong></p>\n\n<p>The <code>countLetters</code> method is a utility method. It should have exactly one purpose so that it does not unnecessarily limit it's usability (also maintaining the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a> helps in maintainability and testability). You should not implement exception handling beyond closing the resources you have acquired in the method. So instead of printing out the error message, you should just let the exception escape and let caller decide how to handle the error.</p>\n\n<p>So the <code>countLetters</code> has three responsibilities: it counts the letters in a file, handles error logging and also implements output handling. Instead of printing the letter count the method should just return the number of letters and let the caller handle the output. Use long instead int. Files can be large.</p>\n\n<pre><code>private long countLetters (String args) throws IOException {\n ...\n return count;\n}\n</code></pre>\n\n<p><strong>Error handling</strong></p>\n\n<p>For future reference, it is almost never correct to write errors to <code>System.out</code>. The correct stream for errors is <code>System.err</code>. And logging n exception simply with the exeption message causes trouble when you're trying to debug problems, because all the important information in the exception is in the stack trace. If you have to log an exception to the console, simply write <code>ex.printStackTrace();</code>. In the real world you would use a loging framework but still you would log the full stack trace, never just the message.</p>\n\n<p>Add a check to see if the args array in the main method contains exactly one element. If you do not provide parameters to your program now you get an <code>ArrayIndexOutOfBoundsExceltion</code>.</p>\n\n<p><strong>Monolithic code</strong></p>\n\n<p>You've tried to not implement all your logic in the main method, but the attempt falls a bit short because the methods in the Solution class are all private. The only way to access the counter is is still via the main method only. Instead of implementing the main method to the <code>Solution</code>-class you should have two classes: one that implements the letter counting and one that has the main method, which invokes the letter counter class. I.e. separate the letter counting responsibility from the command line processing responsibility. This again follows the single responsiblity principle: the Solution-class is only responsible for counting. All other responsibilities are put into separate modules.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T04:49:08.573",
"Id": "475379",
"Score": "0",
"body": "Thanks for taking the time to write such a comprehensive review. It will take a bit of time to digest but I'll definitely have a look at everything you suggested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T03:23:28.557",
"Id": "476365",
"Score": "0",
"body": "TorbenPutkonen about your advice on creating a GitLab repo, is there any reason why you suggest Gitlab over Github? I'm working on the creation of a repo for my exercises now, thanks again for the advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T04:22:22.310",
"Id": "476371",
"Score": "1",
"body": "My reason is highly opinion based and not suitable to the StackExchange network."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T07:09:44.877",
"Id": "242065",
"ParentId": "242035",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "242065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T11:40:55.617",
"Id": "242035",
"Score": "3",
"Tags": [
"java"
],
"Title": "Handling exceptions with FileInputStream"
}
|
242035
|
<p>So I have just started to work with SQL and I have tested my script and is working very well when it comes to my database. </p>
<p>The database is used for shopping. What I mean by that is that I scrape a website that I love (Flowers etc) and then I collect each item that has been updated on the website and add it to my database if the product has not already been added in the database before (Reason why I have a checkIfExists function)</p>
<p>I also have different get Links, get Keywords functions and the reason I have </p>
<p><code>getLinks</code> = Is to see if there has been added new page in the website that is not in my DB</p>
<p><code>getBlackList</code> = In case they re-add same product and I don't want it to be too spammy with my logs then I can blacklist it inside the database.</p>
<p><code>getAllKeywords</code> = Sometimes I want to filter for specific flowers where I have a function that checks whats the name of the product and then compare if those keywords matches from my database</p>
<p>The code I have written is working as I want and very proud of it and I do feel like I have done some steps abit too much. What I mean by that is that for every function I call <code>cur = self.database.cursor()</code> and <code>cur.close()</code> which maybe is not important or there is a newer way to handle this better. In my eyes I have a feeling I am missing something more. </p>
<p>I would appreciate all kind of help, even if I might have asked wrong question in Code review (its my first time and tried to read the description on how to write good) and as I mentioned before... I appreciate all kind of help! :) </p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime
import psycopg2
class DataBaseAPI:
def __init__(self):
self.database = psycopg2.connect(host="test",
database="test",
user="test",
password="test"
)
def checkIfExists(self, store, link):
try:
cur = self.database.cursor()
sql = f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.title()}' AND visible='yes' AND link='{link}';"
cur.execute(sql)
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
return False
if cur.rowcount:
return True
else:
return False
def addProduct(self, product):
if self.checkIfExists(store=product["store"], link=product["url"]) is False:
link = product["url"],
store = product["store"],
name = product["name"],
image = product["image"]
visible = "yes"
cur = self.database.cursor()
sql = f"INSERT INTO public.store_items (store, name, link, image, visible, added_date) VALUES ('{store}', '{name}', '{link}', '{image}', '{visible}', '{datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}');"
cur.execute(sql)
# # Commit the changes to the database
self.database.commit()
# Close communication with the PostgreSQL database
cur.close()
return True
else:
return False
def getAllLinks(self, store):
cur = self.database.cursor()
sql = f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.title()}' AND visible='yes';"
cur.execute(sql)
cur.close()
return [link[0] for link in cur.fetchall()]
def getBlackList(self, store):
cur = self.database.cursor()
sql = f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.title()}' AND visible='no';"
cur.execute(sql)
cur.close()
return [link[0] for link in cur.fetchall()]
def getAllKeywords(self, filtered_or_unfiltered):
cur = self.database.cursor()
sql = f"SELECT DISTINCT keyword FROM public.keywords WHERE filter_type='{filtered_or_unfiltered}';"
cur.execute(sql)
cur.close()
return [keyword[0] for keyword in cur.fetchall()]
</code></pre>
<p>I think thats pretty much it. Just a simple Add and Get database :)</p>
|
[] |
[
{
"body": "<p>Before anything, read on SQL parameterization and avoid concatenating or interpolating variables directly in SQL statements. Otherwise you open your application to SQL injection and inefficiencies. The module, <code>psycopg2</code>, has much support for parameterizations as their <a href=\"https://www.psycopg.org/docs/usage.html\" rel=\"nofollow noreferrer\">docs indicate</a>.</p>\n<p>Secondly, save <code>cur</code> as another <code>self.</code> attribute and handle cursor and connection closings in a <code>__del__</code> method. Also <code>public.</code> is the default schema in PostgreSQL and hence can be omitted from table names.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from datetime import datetime\n\nimport psycopg2\n\nclass DataBaseAPI:\n\n def __init__(self):\n self.database = psycopg2.connect(host="test",\n database="test",\n user="test",\n password="test")\n\n self.cur = self.database.cursor()\n\n def checkIfExists(self, store, link):\n try:\n # PREPARED STATEMENT WITH %s PLACEHOLDERS\n sql = """SELECT DISTINCT link \n FROM store_items \n WHERE store=%s AND visible=%s AND link=%s;\n """\n # EXECUTE WITH BINDED PARAMS\n cur.execute(sql, (store.title(), 'yes', link))\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n return False\n\n if cur.rowcount:\n return True\n else:\n return False\n\n def addProduct(self, product):\n if self.checkIfExists(store=product["store"], link=product["url"]) is False:\n link = product["url"],\n store = product["store"],\n name = product["name"],\n image = product["image"]\n visible = "yes"\n\n # PREPARED STATEMENT WITH %s PLACEHOLDERS\n sql = """INSERT INTO store_items (store, name, link, image, visible, added_date)\n VALUES (%s, %s, %s, %s, %s, %s);"""\n\n # EXECUTE WITH BINDED PARAMS\n cur.execute(sql, (store, name, link, image, visible,\n datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')))\n\n # Commit the changes to the database\n self.database.commit()\n\n return True\n else:\n return False\n\n def getAllLinks(self, store):\n # PREPARED STATEMENT WITH %s PLACEHOLDERS\n sql = """SELECT DISTINCT link\n FROM store_items \n WHERE store=%s AND visible=%s;\n """\n\n # EXECUTE WITH BINDED PARAMS\n cur.execute(sql, (store.title(), 'yes'))\n\n return [link[0] for link in cur.fetchall()]\n\n def getBlackList(self, store):\n # PREPARED STATEMENT WITH %s PLACEHOLDERS\n sql = """SELECT DISTINCT link \n FROM store_items \n WHERE store=%s AND visible=%s;\n """\n\n # EXECUTE WITH BINDED PARAMS\n cur.execute(sql, (store.title(), 'no'))\n\n return [link[0] for link in cur.fetchall()]\n\n def getAllKeywords(self, filtered_or_unfiltered):\n # PREPARED STATEMENT WITH %s PLACEHOLDERS\n sql = """SELECT DISTINCT keyword \n FROM keywords \n WHERE filter_type=%s;\n """\n # EXECUTE WITH BINDED PARAMS\n # (INNER PARENS + COMMA IS NOT A TYPO BUT A ONE-ITEM TUPLE)\n cur.execute(sql, (filtered_or_unfiltered,)) \n \n return [keyword[0] for keyword in cur.fetchall()]\n\n def __del__(self):\n # CLOSE OBJECTS\n self.cur.close()\n self.database.close()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T11:19:48.320",
"Id": "501902",
"Score": "0",
"body": "Sorry for the late response! I was not expecting since I asked in May month! Thank you verym uch and really appreciate it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T17:31:37.540",
"Id": "501930",
"Score": "1",
"body": "No problem. Glad to help! Unfortunately, CodeExchange is not as active as StackOverflow!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T21:41:30.343",
"Id": "254394",
"ParentId": "242040",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254394",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T15:29:04.503",
"Id": "242040",
"Score": "4",
"Tags": [
"python",
"sql",
"postgresql"
],
"Title": "Postgres Shopping Database using Python"
}
|
242040
|
<p>Firstly, have a good day to all,
I've been trying to learn PyQt5 nowadays. I wrote a code about check box state changing depends on other check box. It looks work. I wonder your feed back.
Thank you for your time.</p>
<pre><code>from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class CheckBox(QWidget):
def __init__(self):
super(CheckBox, self).__init__()
self.features()
self.checkbox()
def features(self):
self.setWindowTitle("Check Box")
self.setGeometry(500, 200, 200, 200)
self.show()
def checkbox(self):
# Check Box
self.check_box1 = QCheckBox("Alive")
self.check_box2 = QCheckBox("Dead")
self.check_box3 = QCheckBox("No Idea")
# Check Box State
self.check_box3.setChecked(True)
self.check_box1.stateChanged.connect(self.onStateChange)
self.check_box2.stateChanged.connect(self.onStateChange)
self.check_box2.stateChanged.connect(self.onStateChange)
# Button
self.push_button1 = QPushButton("Send")
self.push_button1.clicked.connect(lambda: self.sendmessage(self.check_box1.isChecked(),
self.check_box2.isChecked(),
self.check_box3.isChecked(), self.label1))
# Label
self.label1 = QLabel("")
# Vertical Lay Out
v_box1 = QVBoxLayout()
v_box1.addWidget(self.check_box1)
v_box1.addWidget(self.check_box2)
v_box1.addWidget(self.check_box3)
v_box1.addWidget(self.push_button1)
v_box1.addWidget(self.label1)
# Horizontal Lay Out
h_box1 = QHBoxLayout()
h_box1.addStretch()
h_box1.addLayout(v_box1)
h_box1.addStretch()
# Set Lay Out
self.setLayout(h_box1)
def onStateChange(self, state):
if state == Qt.Checked:
if self.sender() == self.check_box1:
self.check_box2.setChecked(False)
self.check_box3.setChecked(False)
elif self.sender() == self.check_box2:
self.check_box1.setChecked(False)
self.check_box3.setChecked(False)
elif self.sender() == self.check_box3:
self.check_box1.setChecked(False)
self.check_box2.setChecked(False)
def sendmessage(self, cbox1, cbox2, cbox3, lab):
if cbox1:
lab.setText("Check Box 1")
elif cbox2:
lab.setText("Check Box 2")
elif cbox3:
lab.setText("Check Box 3")
else:
lab.setText("No Selection")
app = QApplication(sys.argv)
checkbox = CheckBox()
sys.exit(app.exec_())
</code></pre>
|
[] |
[
{
"body": "<p>I think there is a mistake, this line is defined twice (line 28):</p>\n\n<pre><code>self.check_box2.stateChanged.connect(self.onStateChange)\n</code></pre>\n\n<p>Therefore the event <code>onStateChange</code> is triggered twice when you check <code>check_box2</code>, which is logical.</p>\n\n<p>I think you did a copy paste and the last should be <code>check_box3</code>. But your <strong>naming conventions</strong> are not intuitive, give your objects some more <strong>meaningful names</strong>, otherwise how are you going to tell the difference from your code.</p>\n\n<p>If what you want is <strong>mutually exclusive</strong> checkboxes the implementation could be more straightforward. Personally I prefer to use radio buttons like in plain HTML because this is more intuitive (it is immediately obvious that only one answer is allowed).</p>\n\n<p>First approach: a generic method that loops on the checkboxes in your form and unchecks all of them except the sender. Then you can simplify code and get rid of <code>if/elif</code></p>\n\n<p>Second approach: use QT built-in features. You could wrap your checkboxes in a <code>QButtonGroup</code> container.</p>\n\n<blockquote>\n <p>A rectangular box before the text label appears when a QCheckBox\n object is added to the parent window. Just as QRadioButton, it is also\n a selectable button. Its common use is in a scenario when the user is\n asked to choose one or more of the available options.</p>\n \n <p>Unlike Radio buttons, check boxes are not mutually exclusive by\n default. In order to restrict the choice to one of the available\n items, the check boxes must be added to QButtonGroup.</p>\n</blockquote>\n\n<p>and:</p>\n\n<blockquote>\n <p><strong>As mentioned earlier, checkBox buttons can be made mutually exclusive\n by adding them in the <code>QButtonGroup</code> object.</strong></p>\n\n<pre><code>self.bg = QButtonGroup()\nself.bg.addButton(self.b1,1)\nself.bg.addButton(self.b2,2)\n</code></pre>\n \n <p><code>QButtonGroup</code> object, provides abstract container for buttons and\n doesn’t have a visual representation. It emits <code>buttonCliked()</code> signal\n and sends Button object’s reference to the slot function <code>btngroup()</code>.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://www.tutorialspoint.com/pyqt/pyqt_qcheckbox_widget.htm\" rel=\"nofollow noreferrer\">PyQt - QCheckBox Widget</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T09:27:37.197",
"Id": "475042",
"Score": "0",
"body": "Thank you for your feedback. It mean a lot for me. I will definetly not ignore your feedback"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T17:43:38.480",
"Id": "242045",
"ParentId": "242041",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242045",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T16:12:56.537",
"Id": "242041",
"Score": "1",
"Tags": [
"python",
"pyqt"
],
"Title": "PyQt 5 CheckBox State Efficient wAy"
}
|
242041
|
<p>Here is a "Roman Numerals" kata implementation. Given a decimal number one has to return a corresponding roman number.</p>
<p>I have following questions:</p>
<ol>
<li>Is memory management correct? Here I assume that the caller is responsible for freeing memory.</li>
<li>Does this code conform to <code>c</code> code style?</li>
<li>Does it look like idiomatic <code>c</code>?</li>
</ol>
<p>Thanks!</p>
<p><code>toRoman.h</code>:</p>
<pre><code>char * toRoman(int n);
typedef struct DecimalToRoman {
int decimal;
const char * roman;
} DecimalToRoman;
</code></pre>
<p><code>toRoman.c</code>:</p>
<pre><code>char * toRoman(int n) {
if (n < 1) return NULL;
const DecimalToRoman numbers[] = {
{ 1000, "M" },
{ 900, "CM" },
{ 500, "D" },
{ 400, "CD" },
{ 100, "C" },
{ 90, "XC" },
{ 50, "L" },
{ 40, "XL" },
{ 10, "X" },
{ 9, "IX" },
{ 5, "V" },
{ 4, "IV" },
{ 1, "I" }
};
size_t resultLen = 1;
int tmp = n;
for (size_t i = 0; i < sizeof numbers / sizeof(DecimalToRoman) && tmp; i++) {
while(tmp >= numbers[i].decimal) {
tmp -= numbers[i].decimal;
resultLen += strlen(numbers[i].roman);
}
}
char * result = malloc(resultLen);
if (result == NULL) {
perror("allocate");
return NULL;
}
memset(result, '\0', resultLen);
for (size_t i = 0, r = 0; r < sizeof numbers / sizeof(DecimalToRoman); r++) {
while (n >= numbers[r].decimal) {
n -= numbers[r].decimal;
int j = 0;
while (numbers[r].roman[j])
result[i++] = numbers[r].roman[j++];
}
}
return result;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T19:37:45.833",
"Id": "475009",
"Score": "1",
"body": "By \"Roman Numerals\", do you mean https://www.codewars.com/kata/51b62bf6a9c58071c600001b/c? Or did you try to solve the problem in general? Is the header part of Codewars provided code or your own?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T20:08:38.800",
"Id": "475097",
"Score": "1",
"body": "Yes, this is the kata. But I was practicing it here https://cyber-dojo.org/"
}
] |
[
{
"body": "<pre><code>toRoman.h\n</code></pre>\n\n<p>Is there any reason to expose <code>DecimalToRoman</code> to callers?</p>\n\n<hr>\n\n<pre><code>char * toRoman(int n)\n</code></pre>\n\n<p>Nit: it might be preferable to take <code>unsigned</code> rather than <code>int</code> as you cannot really handle negative numbers.</p>\n\n<hr>\n\n<pre><code>if (n < 1) return NULL;\n</code></pre>\n\n<p>Seems reasonable. If you took unsigned, then you would only have to handle 0. In that case, it might make sense to return <code>\"\"</code> so you always return a valid string.</p>\n\n<p>On second thought, there's sort of an upper-bound on what you can reasonably write as a roman numeral. Does it make sense to write two billion in terms of thousands? If you choose an upper bound, you can make assumptions about the length of your buffer.</p>\n\n<hr>\n\n<pre><code>const DecimalToRoman numbers[] = {\n....\n</code></pre>\n\n<p>I love that this is written out so clearly. Nice.</p>\n\n<hr>\n\n<pre><code>size_t resultLen = 1;\n</code></pre>\n\n<p>Help a reader out by saying why you init to 1. IMO it's not obvious until you get to malloc.</p>\n\n<pre><code>int tmp = n;\nfor (size_t i = 0; i < sizeof numbers / sizeof(DecimalToRoman) && tmp; i++) {\n while(tmp >= numbers[i].decimal) {\n tmp -= numbers[i].decimal;\n resultLen += strlen(numbers[i].roman);\n }\n}\n</code></pre>\n\n<p>How about making this a function? There's a common pattern:</p>\n\n<pre><code>Type thing = init;\n...actually figure out what thing is often with a loop...\n\n// don't change thing anymore!\n... use thing ...\n</code></pre>\n\n<p>This is almost always more clearly written as:</p>\n\n<pre><code>Type const thing = createThing(init);\n... use thing ...\n</code></pre>\n\n<p>But anyway back to this code.</p>\n\n<pre><code>sizeof numbers / sizeof(DecimalToRoman)\n</code></pre>\n\n<p>How about making this a variable named <code>lenNumbers</code> or something like that? Super nit: I like that you used parens for the type and not for the expression, but IMO it looks weird with the operator/. More clear: <code>(sizeof numbers) / sizeof(DecimalToRoman)</code>.</p>\n\n<hr>\n\n<pre><code>if (result == NULL) {\n perror(\"allocate\");\n return NULL;\n}\n</code></pre>\n\n<p>Good. I admit I usually <code>assert</code> in situations like this since there's not much you can do when you're out of memory (and it rarely happens in the things I do), but this is the party line.</p>\n\n<hr>\n\n<pre><code>memset(result, '\\0', resultLen);\n</code></pre>\n\n<p>Isn't this overkill? You're about to overwrite the memory anyway. Could just set the last character to '\\0` (and you might as well do that after you write the answer for cache locality).</p>\n\n<hr>\n\n<pre><code> int j = 0;\n while (numbers[r].roman[j])\n result[i++] = numbers[r].roman[j++];\n</code></pre>\n\n<p>Better option: a <code>for</code> loop. Best option: <code>strcpy</code>.</p>\n\n<hr>\n\n<p>You could remove the calls to strlen by storing the length in <code>DecimalToRoman</code>. The lengths are tiny so this is more a question of simplicity than optimization.</p>\n\n<hr>\n\n<p>There's a common pattern in C APIs for returning buffers. The idea is you let the user pass in the buffer and you return an error code. Something like:</p>\n\n<pre><code>int getRomanNumerals(int nInput, char* strOut, int* nLen);\n</code></pre>\n\n<p>The return value is either success, failure, or \"insufficient buffer\" (you probably want an enum or a preprocessor <code>#define</code> for this). In any case, the user passes in a buffer and the buffer's length. You always set <code>nLen</code> to the number of bytes needed, and you set <code>strOut</code> if you have enough space (maybe you start setting <code>strOut</code> assuming the buffer is long enough, but stop writing if you run out of space and only need to set <code>nLen</code>).</p>\n\n<p>This way the user can do crazy stuff like store the result in a weird place or maybe the user knows they don't have enough memory to store the whole thing etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T04:27:58.353",
"Id": "242062",
"ParentId": "242047",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>Is memory management correct? Here I assume that the caller is responsible for freeing memory.</p>\n</blockquote>\n\n<p>Yes. The allocated size needed is correct. Proper <code>NULL</code> allocation test done.</p>\n\n<blockquote>\n <p>Does this code conform to c code style?</p>\n</blockquote>\n\n<p><code>DecimalToRoman;</code> in .h unnecessarily exposes implementation. Format looks similar to the C spec.</p>\n\n<blockquote>\n <p>Does it look like idiomatic c?</p>\n</blockquote>\n\n<p>Not as much as it could. .h file lacks any indication that the caller needs to free anything. Consider that the .c file is opaque to the user. A return value of <code>NULL</code> is a surprise. Function name does not hint at allocation. The .h lacks useful info to understated the function.</p>\n\n<p>I see C moving more toward the caller supplying the buffer and size for such helper function. Also with size leading the pointer.</p>\n\n<hr>\n\n<p>3 ideas: together to form a nifty result:</p>\n\n<ol>\n<li><p>Consider passing in the destination buffer and its size and use <code>unsigned</code>. </p>\n\n<pre><code>char * toRoman(size_t sz, char *dest, unsigned n);\n</code></pre></li>\n<li><p>Roman numbers did employ <code>()</code> or the like for <a href=\"https://en.wikipedia.org/wiki/Roman_numerals#Large_numbers\" rel=\"nofollow noreferrer\">large numbers</a>. <code>\"N\"</code> is is reasonable result for 0.</p>\n\n<pre><code>5000 --> \"(V)\"\n0 --> \"N\"\n</code></pre></li>\n<li><p>Using #2, then for a given <code>UINT_MAX</code>, there is a small, pre-determinate max size needed.</p></li>\n</ol>\n\n<p>Now the <code>resultLen</code> pre-calculation is not needed. Just use a temp buffer of the max size and copy. This <code>ROMAN_SZ</code> belongs in the .h file so a caller may benefit knowing the max size.</p>\n\n<pre><code>#if UINT_MAX == 42949672965u\n #define ROMAN_SZ 52 /* (((III)))((DCCCLXXXVIII))(DCCCLXXXVIII)DCCCLXXXVIII */\n\n#else if ...\n</code></pre>\n\n<hr>\n\n<p>Putting this together</p>\n\n<pre><code>char * toRoman(char *dest, size_t, sz, unsigned n) {\n char tmp[ROMAN_SZ];\n\n // Fill tmp based on `n`, no worry about overrun.\n\n size_t needed = strlen(tmp) + 1;\n if (needed > sz) {\n Handle_error(); // could use NULL or \"\" to indicate error\n } else {\n return strcpy(dest, tmp);\n }\n</code></pre>\n\n<p>Now the fun part, use a macro and <em>compound literal</em> for an <code>malloc()</code>-less <code>TO_ROMAN()</code></p>\n\n<pre><code> #define TO_ROMAN(u) toRoman(ROMAN_SZ, (char [ROMAN_SZ]){\"\"}, (u))\n</code></pre>\n\n<p>Code can use <code>TO_ROMAN()</code> to form a <em>string</em> that is valid to the end of the block with no <code>*alloc(), free()</code> needed.</p>\n\n<pre><code>int main(void) {\n printf(\"%s %s\\n\", TO_ROMAN(42), TO_ROMAN(12345));\n}\n</code></pre>\n\n<p>This is akin to <a href=\"https://stackoverflow.com/a/34641674/2410359\">printing in any base</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T23:03:56.960",
"Id": "242103",
"ParentId": "242047",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T19:18:44.237",
"Id": "242047",
"Score": "1",
"Tags": [
"c"
],
"Title": "Roman Numerals Kata in C"
}
|
242047
|
<p>I have rewritten the Vector2 class that I usually use in my projects. The code looks as follows:</p>
<pre><code>#pragma once
#include <type_traits>
#include <utility>
#include <iostream>
namespace ae
{
// Does T support constexpr?
template <Literal T>
concept Literal = std::is_fundamental_v<T>;
template <Literal T>
class Vector2
{
public:
constexpr Vector2() noexcept :
x(T{}),
y(T{})
{}
constexpr Vector2(T x, T y) noexcept :
x(x),
y(y)
{}
constexpr Vector2(const Vector2<T>& other) noexcept :
x(other.x),
y(other.y)
{}
constexpr Vector2(const Vector2<T>&& other) noexcept :
x(std::move(other.x)),
y(std::move(other.y))
{}
constexpr void operator =(const Vector2<T>& rhs) noexcept
{
this->x = rhs.x;
this->y = rhs.y;
}
template <Literal T>
constexpr void operator =(const Vector2<T>&& rhs) noexcept
{
this->x = std::move(rhs.x);
this->y = std::move(rhs.y);
}
T x;
T y;
};
template <Literal T>
[[nodiscard]] constexpr Vector2<T> operator -(const Vector2<T>& rhs) noexcept
{
return { -rhs.x, -rhs.y };
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T>& operator +=(Vector2<T>& lhs, const Vector2<T>& rhs) noexcept
{
lhs.x += rhs.x;
lhs.y += rhs.y;
return lhs;
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T>& operator -=(Vector2<T>& lhs, const Vector2<T>& rhs) noexcept
{
lhs.x -= rhs.x;
lhs.y -= rhs.y;
return lhs;
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T> operator +(const Vector2<T>& lhs, const Vector2<T>& rhs) noexcept
{
return { lhs.x + rhs.x, lhs.y + rhs.y };
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T> operator -(const Vector2<T>& lhs, const Vector2<T>& rhs) noexcept
{
return { lhs.x - rhs.x, lhs.y - rhs.y };
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T> operator *(const Vector2<T>& lhs, T rhs) noexcept
{
return { lhs.x * rhs, lhs.y * rhs };
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T> operator *(T lhs, const Vector2<T>& rhs) noexcept
{
return { rhs.x * lhs, rhs.y * lhs };
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T>& operator *=(Vector2<T>& lhs, T rhs) noexcept
{
lhs.x *= rhs;
lhs.y *= rhs;
return lhs;
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T> operator /(const Vector2<T>& lhs, T rhs) noexcept
{
return { lhs.x / rhs, lhs.y / rhs };
}
template <Literal T>
[[nodiscard]] constexpr Vector2<T>& operator /=(Vector2<T>& lhs, T rhs) noexcept
{
lhs.x /= rhs;
lhs.y /= rhs;
return lhs;
}
template <Literal T>
[[nodiscard]] constexpr bool operator ==(const Vector2<T>& lhs, const Vector2<T>& rhs) noexcept
{
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
template <Literal T>
[[nodiscard]] constexpr bool operator !=(const Vector2<T>& lhs, const Vector2<T>& rhs) noexcept
{
return (lhs.x != rhs.x) || (lhs.y != rhs.y);
}
template <Literal T>
std::ostream& operator <<(std::ostream& os, const Vector2<T>& rhs) noexcept
{
return os << "{" << rhs.x << ", " << rhs.y << "}";
}
}
</code></pre>
<p>Looking for any feedback, perhaps especially style wise. Note that the class does not represent a 'mathematical vector' just a 2d coordinate / pair.</p>
<p>I have a Vector3 and Vector4 class as well, so any improvements that apply here, should also apply there.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T21:19:59.080",
"Id": "475011",
"Score": "0",
"body": "Why do you have `[[nodiscard]]` on your compound assignment operators (`+=`, `-=`, etc.)? Those are often used for the side effect and ignore the returned value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T21:31:53.353",
"Id": "475012",
"Score": "0",
"body": "That is a mistake. I copy pasted the declartions and edited the names afterwards. Thank you for pointing it out :P."
}
] |
[
{
"body": "<pre><code>// Does T support constexpr?\ntemplate <Literal T>\nconcept Literal = std::is_fundamental_v<T>;\n</code></pre>\n\n<p>I see what you're going for. This isn't bad, but imagine someone tries to make a Vector2 with a custom type... they'll have to find this comment to understand why compilation failed. If you just use <code>typename T</code> and get rid of the concept, then the compiler will show a traceback and say \"T is not constexpr\" which is a lot more helpful to the user. TL;DR: I'd get rid of this concept.</p>\n\n<hr>\n\n<p>This is a lot of constructors. Is there any reason not to use the default ones?</p>\n\n<hr>\n\n<p>Can you leverage <code>std::pair</code> to define the constructors/the comparison operators for you? Maybe you can inherit from it?</p>\n\n<hr>\n\n<pre><code>constexpr Vector2<T> operator *(const Vector2<T>& lhs, T rhs)\n</code></pre>\n\n<p>This has the same semantics as converting <code>rhs</code> into <code>Vector2<T>(rhs, rhs)</code> ... maybe it makes sense to have a constructor from a single T to a Vector2 with the same T in each dimension?</p>\n\n<p>This would also allow you to define a single <code>operator*</code> and rely on implicit conversion for scalar values.</p>\n\n<hr>\n\n<p>Overall this looks pretty good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T03:54:59.977",
"Id": "242061",
"ParentId": "242048",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T19:54:46.850",
"Id": "242048",
"Score": "4",
"Tags": [
"c++",
"c++20"
],
"Title": "Simple pair/vector2 utility class for c++20"
}
|
242048
|
<p>In a bash 3 script for OSX machines, I needed the functional equivalent of the <a href="http://man7.org/linux/man-pages/man1/realpath.1.html" rel="nofollow noreferrer"><code>realpath</code> command</a>, complete with support for the <code>--relative-to</code> and <code>--relative-base</code> options.</p>
<p>I would normally just install the <a href="https://formulae.brew.sh/formula/coreutils" rel="nofollow noreferrer">homebrew <code>coreutils</code> formula</a>, but I need this script to work when bootstrapping a new machine with no network or XCode available yet. So the code below includes a replacement implementation that's only used when the command is not already installed. Normal usage would be</p>
<pre class="lang-bsh prettyprint-override"><code>for resolved_path in $(realpath [--relative-to=...] [--relative-base=...] [one or more paths]); do
# ...
done
</code></pre>
<p>It's meant to be used as a sourced library (<code>. realpathlib.bash</code>), but if run directly with <code>bash realpathlib.bash</code> it runs a simple test suite.</p>
<p>I've been picking up bash best practices as I went along, but would love feedback on all aspects, such as naming conventions and other coding style aspects, techniques, problems I've overlooked, etc.</p>
<pre class="lang-bsh prettyprint-override"><code># shellcheck shell=bash
set -euo pipefail
_contains() {
# return true if first argument is present in the other arguments
local elem value
value="$1"
shift
for elem in "$@"; do
if [[ $elem == "$value" ]]; then
return 0
fi
done
return 1
}
_canonicalize_filename_mode() {
# resolve any symlink targets, GNU readlink -f style
# where every path component except the last should exist and is
# resolved if it is a symlink. This is essentially a re-implementation
# of canonicalize_filename_mode(path, CAN_ALL_BUT_LAST).
# takes the path to canonicalize as first argument
local path result component seen
seen=()
path="$1"
result="/"
if [[ $path != /* ]]; then # add in current working dir if relative
result="$PWD"
fi
while [[ -n $path ]]; do
component="${path%%/*}"
case "$component" in
'') # empty because it started with /
path="${path:1}" ;;
.) # ./ current directory, do nothing
path="${path:1}" ;;
..) # ../ parent directory
if [[ $result != "/" ]]; then # not at the root?
result="${result%/*}" # then remove one element from the path
fi
path="${path:2}" ;;
*)
# add this component to the result, remove from path
if [[ $result != */ ]]; then
result="$result/"
fi
result="$result$component"
path="${path:${#component}}"
# element must exist, unless this is the final component
if [[ $path =~ [^/] && ! -e $result ]]; then
echo "$1: No such file or directory" >&2
return 1
fi
# if the result is a link, prefix it to the path, to continue resolving
if [[ -L $result ]]; then
if _contains "$result" "${seen[@]+"${seen[@]}"}"; then
# we've seen this link before, abort
echo "$1: Too many levels of symbolic links" >&2
return 1
fi
seen+=("$result")
path="$(readlink "$result")$path"
if [[ $path = /* ]]; then
# if the link is absolute, restart the result from /
result="/"
elif [[ $result != "/" ]]; then
# otherwise remove the basename of the link from the result
result="${result%/*}"
fi
elif [[ $path =~ [^/] && ! -d $result ]]; then
# otherwise all but the last element must be a dir
echo "$1: Not a directory" >&2
return 1
fi
;;
esac
done
echo "$result"
}
_realpath() {
local relative_to relative_base seenerr path
relative_to=
relative_base=
seenerr=
while [[ $# -gt 0 ]]; do
case $1 in
"--relative-to="*)
relative_to=$(_canonicalize_filename_mode "${1#*=}")
shift 1;;
"--relative-base="*)
relative_base=$(_canonicalize_filename_mode "${1#*=}")
shift 1;;
*)
break;;
esac
done
if [[
-n $relative_to
&& -n $relative_base
&& ${relative_to#${relative_base}/} == "$relative_to"
]]; then
# relative_to is not a subdir of relative_base -> ignore both
relative_to=
relative_base=
elif [[ -z $relative_to && -n $relative_base ]]; then
# if relative_to has not been set but relative_base has, then
# set relative_to from relative_base, simplifies logic later on
relative_to="$relative_base"
fi
for path in "$@"; do
if ! real=$(_canonicalize_filename_mode "$path"); then
seenerr=1
continue
fi
# make path relative if so required
if [[
-n $relative_to
&& ( # path must not be outside relative_base to be made relative
-z $relative_base || ${real#${relative_base}/} != "$real"
)
]]; then
local common_part parentrefs
common_part="$relative_to"
parentrefs=
while [[ ${real#${common_part}/} == "$real" ]]; do
common_part="$(dirname "$common_part")"
parentrefs="..${parentrefs:+/$parentrefs}"
done
if [[ $common_part != "/" ]]; then
real="${parentrefs:+${parentrefs}/}${real#${common_part}/}"
fi
fi
echo "$real"
done
if [[ $seenerr ]]; then
return 1
fi
}
if ! command -v realpath > /dev/null 2>&1; then
# realpath is not available on OSX unless you install the `coreutils` brew
realpath() { _realpath "$@"; }
fi
if [[ $0 == "${BASH_SOURCE[0]}" ]]; then
assert_equal() {
local result
while read -r result; do
if [[ $result != "$1" ]]; then
echo -e "\033[0;31mFAIL\033[0m"
echo -e "expected\n\t$1\ngot\n\t$result"
exit 2
fi
shift 1
done
# any expected results left over?
if [[ $# -gt 0 ]]; then
echo -e "\033[0;31mFAIL\033[0m"
echo "expected more results"
printf '\t- %s\n' "$@"
exit 2
fi
echo -e "\033[0;32mOK\033[0m"
}
testdir=$(mktemp -d -t "${0##*/}_tests")
# canonicalize testdir with pwd -P (no .. components, so sufficient)
pushd "$testdir"
testdir=$(pwd -P)
popd >/dev/null
cleanup() {
rm -rf "$testdir"
}
trap cleanup EXIT
mkdir -p "$testdir/foo/bar/baz"
mkdir -p "$testdir/foobar"
touch "$testdir/target"
touch "$testdir/foo/target"
touch "$testdir/foo/bar/target"
touch "$testdir/foobar/target"
ln -s "../link" "$testdir/foo/bar/baz/link"
ln -s "../link" "$testdir/foo/bar/link"
ln -s "../target" "$testdir/foo/link"
ln -s "circular2" "$testdir/foo/circular1"
ln -s "circular1" "$testdir/foo/circular2"
ln -s "../foo/bar" "$testdir/foobar/dirlink"
echo -en "chained symlinks:\t"
_realpath "$testdir/foo/bar/baz/link" \
| assert_equal "$testdir/target"
echo -en "circular symlinks:\t"
{ _realpath "$testdir/foo/circular1" 2>&1 || echo "error exit"; } \
| assert_equal \
"$testdir/foo/circular1: Too many levels of symbolic links" \
"error exit"
echo -en "symlink and .. combo:\t"
_realpath "$testdir/foobar/dirlink/../target" \
| assert_equal \
"$testdir/foo/target"
echo -en "non-existing path:\t"
{ _realpath "$testdir/nonesuch/foo" 2>&1 || echo "error exit"; } \
| assert_equal \
"$testdir/nonesuch/foo: No such file or directory" \
"error exit"
echo -en "file as directory:\t"
{ _realpath "$testdir/target/foo" 2>&1 || echo "error exit"; } \
| assert_equal \
"$testdir/target/foo: Not a directory" \
"error exit"
echo -en "relative paths:\t\t"
pushd "$testdir/foo" > /dev/null
_realpath \
"bar/target" \
"../target" \
"target" \
"$testdir/./foo/../foobar/target" \
| assert_equal \
"$testdir/foo/bar/target" \
"$testdir/target" \
"$testdir/foo/target" \
"$testdir/foobar/target"
popd > /dev/null
echo -en "relative-base inside:\t"
_realpath --relative-base="$testdir/foo" "$testdir/foo/bar/target" \
| assert_equal "bar/target"
echo -en "relative-base outside:\t"
_realpath --relative-base="$testdir/foo/bar" "$testdir/foo/target" \
| assert_equal "$testdir/foo/target"
echo -en "--r-base name prefix:\t"
_realpath --relative-base="$testdir/foo" "$testdir/foobar/target" \
| assert_equal "$testdir/foobar/target"
echo -en "--r-base extra /-s:\t"
_realpath --relative-base="$testdir//foo//" "$testdir/foo/target" \
| assert_equal "target"
echo -en "--r-base relative:\t"
pushd "$testdir/foo/bar" > /dev/null
_realpath --relative-base="../../foo" "$testdir/foo/bar/target" \
| assert_equal "bar/target"
popd > /dev/null
echo -en "multiple --r-base:\t"
_realpath --relative-base="$testdir/foo" \
"$testdir/foo/target" \
"$testdir/target" \
"$testdir/foo/bar/target" \
| assert_equal \
"target" \
"$testdir/target" \
"bar/target"
echo -en "--r-base divergent:\t"
_realpath --relative-base="$testdir" "/dev/null" \
| assert_equal "/dev/null"
echo -en "relative-to inside:\t"
_realpath --relative-to="$testdir/foo" "$testdir/foo/bar/target" \
| assert_equal "bar/target"
echo -en "relative-to outside:\t"
_realpath --relative-to="$testdir/foo/bar" "$testdir/target" \
| assert_equal "../../target"
echo -en "--r-to name prefix:\t"
_realpath --relative-to="$testdir/foo" "$testdir/foobar/target" \
| assert_equal "../foobar/target"
echo -en "--r-to extra /-s:\t"
_realpath --relative-to="$testdir//foo//" "$testdir/foo/target" \
| assert_equal "target"
echo -en "--r-to relative:\t"
pushd "$testdir/foo" > /dev/null
_realpath --relative-to="../foobar" "$testdir/foo/target" \
| assert_equal "../foo/target"
popd > /dev/null
echo -en "multiple --r-to:\t"
_realpath --relative-to="$testdir/foo" \
"$testdir/foo/target" \
"$testdir/target" \
"$testdir/foo/bar/target" \
| assert_equal \
"target" \
"../target" \
"bar/target"
echo -en "combined inside both:\t"
_realpath --relative-base="$testdir" --relative-to="$testdir/foo" "$testdir/foo/bar/target" \
| assert_equal "bar/target"
echo -en "combined outside one:\t"
_realpath --relative-base="$testdir" --relative-to="$testdir/foo/bar" "$testdir/target" \
| assert_equal "../../target"
echo -en "combined outside both:\t"
_realpath --relative-base="$testdir/foo" --relative-to="$testdir/foo/bar" "$testdir/target" \
| assert_equal "$testdir/target"
echo -en "multiple combined:\t"
_realpath --relative-base="$testdir/foo" --relative-to="$testdir/foo/bar" \
"$testdir/foo/target" "$testdir/target" "$testdir/foo/bar/target" \
| assert_equal \
"../target" \
"$testdir/target" \
"target"
echo -en "combined errorcase:\t"
# -base should be a parent path of -to. If not, the arguments are ignored
_realpath --relative-base="$testdir/foo/bar" --relative-to="$testdir/foo" "$testdir/foo/bar/target" \
| assert_equal "$testdir/foo/bar/target"
fi
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T23:23:57.563",
"Id": "475111",
"Score": "0",
"body": "To me this seems like an XY problem. Why can't you just use the \"[Multiple installations](https://docs.brew.sh/Installation)\" section to get homebrew? Ship the install script with the tarball and you can bootstrap from there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T07:28:13.427",
"Id": "475129",
"Score": "0",
"body": "@Peilonrayz that’d still require a network connection or a lot more work to package up all dependent bottles: https://discourse.brew.sh/t/installing-homebrew-without-internet/3321/4. Bootstrapping can’t always rely on a network connection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T10:15:54.897",
"Id": "475141",
"Score": "0",
"body": "I wouldn't call 'compiling with a `--build-from-source` flag once and reusing the same pre-installed package' a lot more work. Seems like a lot less work then writing your own bootstrap ecosystem. With some use of chroot you could probably remove any need for the flag either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T10:51:50.070",
"Id": "475144",
"Score": "0",
"body": "@Peilonrayz: packaging up and maintaining a minimal network-less homebrew and xcode setup would be more work. This is ~150 lines (not counting tests), and was the only missing tool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T12:44:43.740",
"Id": "475152",
"Score": "0",
"body": "I fail to see how this <20 lines script (not counting tests) I have is _more work_ than maintaining a ~150 line script (not counting tests). Takes about 10 minutes to build the package and once built the 382M package runs even without internet. I guess I just lack the ability to do real bootstrapping."
}
] |
[
{
"body": "<blockquote>\n<pre><code># shellcheck shell=bash\n</code></pre>\n</blockquote>\n<p>You're using Shellcheck. That makes me happy. :-)</p>\n<blockquote>\n<pre><code>set -euo pipefail\n</code></pre>\n</blockquote>\n<p>Similarly, this is a good set of options to enable.</p>\n<blockquote>\n<pre><code> for elem in "$@"; do\n</code></pre>\n</blockquote>\n<p><code>in "$@"</code> is redundant here (though it does no harm).</p>\n<blockquote>\n<pre><code> [[ $elem == "$value" ]]\n</code></pre>\n</blockquote>\n<p>I'd use plain <code>[</code> there, and quote both variables, as this is the kind of function I might later want to transplant to a plain POSIX shell script.</p>\n<blockquote>\n<pre><code> case $1 in\n "--relative-to="*)\n relative_to=$(_canonicalize_filename_mode "${1#*=}")\n shift 1;;\n "--relative-base="*)\n relative_base=$(_canonicalize_filename_mode "${1#*=}")\n shift 1;;\n</code></pre>\n</blockquote>\n<p>The argument to <code>shift</code> is redundant, and wasn't used in the other function. Try to be consistent!</p>\n<hr />\n<h1 id=\"the-tests-a0xc\">The tests</h1>\n<p>... seem happy here:</p>\n<pre class=\"lang-none prettyprint-override\"><code>/tmp/user/1000/242050.sh_tests.CbF6 ~/stackexchange/review\nchained symlinks: [0;32mOK[0m\ncircular symlinks: [0;32mOK[0m\nsymlink and .. combo: [0;32mOK[0m\nnon-existing path: [0;32mOK[0m\nfile as directory: [0;32mOK[0m\nrelative paths: [0;32mOK[0m\nrelative-base inside: [0;32mOK[0m\nrelative-base outside: [0;32mOK[0m\n--r-base name prefix: [0;32mOK[0m\n--r-base extra /-s: [0;32mOK[0m\n--r-base relative: [0;32mOK[0m\nmultiple --r-base: [0;32mOK[0m\n--r-base divergent: [0;32mOK[0m\nrelative-to inside: [0;32mOK[0m\nrelative-to outside: [0;32mOK[0m\n--r-to name prefix: [0;32mOK[0m\n--r-to extra /-s: [0;32mOK[0m\n--r-to relative: [0;32mOK[0m\nmultiple --r-to: [0;32mOK[0m\ncombined inside both: [0;32mOK[0m\ncombined outside one: [0;32mOK[0m\ncombined outside both: [0;32mOK[0m\nmultiple combined: [0;32mOK[0m\ncombined errorcase: [0;32mOK[0m\n</code></pre>\n<blockquote>\n<pre><code> echo -e "\\033[0;31mFAIL\\033[0m"\n</code></pre>\n</blockquote>\n<p>Please don't hard-code terminal codes in messages like that - you don't know that it will be run in the same terminal type (it looks very ugly in my Emacs <code>compilation</code> buffer). And avoid non-standard <code>echo -e</code>.</p>\n<p>On my (Debian) system, <code>mktemp -d -t "${0##*/}_tests"</code> fails:</p>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mktemp: too few X's in template ‘242050.sh_tests’\n</code></pre>\n</blockquote>\n<p>It's easily fixed:</p>\n<pre><code>testdir=$(mktemp -d -t "${0##*/}_tests.XXXX")\n</code></pre>\n\n<blockquote>\n<pre><code>pushd "$testdir"\ntestdir=$(pwd -P)\npopd >/dev/null\n</code></pre>\n</blockquote>\n<p><code>pushd</code> and <code>popd</code> are good for interactive use, but less well suited to scripts (as evident by the need to discard output). Use plain <code>cd</code> instead:</p>\n<pre><code>testdir=$(cd "$testdir" && pwd -P)\n</code></pre>\n<p>I'm surprised not to see any tests with <code>.</code> or <code>..</code> components in <code>--relative-*</code> options.</p>\n<p>I'm also surprised that we don't enter the test directory and provide arguments that are relative rather than absolute.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-16T13:37:05.723",
"Id": "264117",
"ParentId": "242050",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T21:34:22.950",
"Id": "242050",
"Score": "6",
"Tags": [
"bash",
"macos"
],
"Title": "realpath substitute with --relative-to and --relative-base support"
}
|
242050
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.