body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have a symmetric matrix and I want to loop over its elements. Currently, I'm using:</p>
<pre><code>import torch
# sample symmetric matrix
W = torch.tensor([[0., 3., 0., 0., 0., 0., 0., 0., 0.],
[3., 0., 1., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 1., 1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 1., 0., 1., 0.],
[0., 0., 0., 0., 1., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 1., 0.],
[0., 0., 0., 0., 1., 0., 1., 0., 2.],
[0., 0., 0., 0., 0., 0., 0., 2., 0.]])
for ix, row in enumerate(W):
for iy, element in enumerate(row):
if iy <= ix:
continue
print(element)
</code></pre>
<p>I was wondering whether is this the most efficient way or if it can be written in a better way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T20:45:43.617",
"Id": "477974",
"Score": "0",
"body": "This matrix doesn't look symmetric. The first row starts with `3., 0., 1.` but the first column starts with `3.0, 0., 0.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T21:26:03.007",
"Id": "477976",
"Score": "1",
"body": "@vnp That's not the first row . . ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:05:57.260",
"Id": "480498",
"Score": "0",
"body": "Why do you omit main diagonal elements from the output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T11:11:29.513",
"Id": "480580",
"Score": "0",
"body": "@JosefZ Because this symmetric matrix is representing an adjacency matrix for an undirected graph with no self-loops. Having no self-loops means that the node is not connected to itself, so the diagonal is zero anyways and does not need to be processed in the loop in my case. Nothing fancy..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T17:10:49.677",
"Id": "243523",
"Score": "1",
"Tags": [
"python"
],
"Title": "Iterating over symmetric matrix in python"
}
|
243523
|
<p>I am creating a social network and I've been told a few times a lot of things are outdated and prone to SQL injections so I am going over everything with a very fine comb and checking what's good and what's not good enough to launch on the web.</p>
<p>I have my login and signup pages and I want to know if it's good to hold sensitive things like: <code>username</code>, <code>first and last name</code>, <code>email</code> and <code>password</code>. And maybe an age.</p>
<p>Register.php:</p>
<pre><code><nav>
<form action="process2.php" method="post">
<input type="text" id="luname" required name="username" placeholder="Username...">
<input type="password" id="lpw" required name="pw" placeholder="Password..." >
<button id="bt2" type="submit" name="signin">Login</button>
</form>
</nav>
<h1 style="font-size: 40px; color: #cce6ff;">Join TheSocial</h1>
<form action="process.php" method="post">
<input id="uname" type="text" name="username" required placeholder="Username..."><p/>
<br>
<input id="pww" type="password" name="pw" required placeholder="Password..."><p />
<br>
<input id="cpw" type="password" name="pw2" required placeholder="Confirm Password..."><p />
<br>
<button type="submit" id="bt1" name="Register">Register</button>
</form>
</code></pre>
<p>process.php(signup page):</p>
<pre><code><?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//Initializing variable
$pw = "";
//$pw2 = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0 When you want to add numbers later
//isset()
$pw = isset($_POST['pw']) ? $_POST['pw'] : '';
$pw2 = isset($_POST['pw2']) ? $_POST['pw2'] : '';
$success = array(); //holds success messages
$username = trim( isset($_SESSION['username']) ? $_SESSION['username'] : "" );
//check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {
// looks like a hack, send to index.php
//header('Location: index.php');
//die();
}
require 'config/connect.php';
$errors = [];
// and so on...
if ($pw !== $pw2) {
$errors[] = "The passwords do not match.";
}
if (!$errors) {
//An SQL statement template is created and sent to the database
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
// This function binds the parameters to the SQL query and tells the database what the parameters are.
$stmt->bind_param("s", $_POST['username']);
// the database executes the statement.
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if ($row && $row['username'] == $_POST['username']) {
$errors[] = "Username exists";
}
}
if (!$errors) {
$pw = password_hash($pw, PASSWORD_BCRYPT, array('cost' => 14));
$stmt = $conn->prepare("INSERT INTO users (username, pw) VALUES(?, ?)");
$stmt->bind_param("ss", $_POST['username'], $pw );
$stmt->execute();
$_SESSION["username"] = $_POST['username'];
header('Location: profile.php');
//die();
} else {
// The foreach construct provides an easy way to iterate over arrays.
foreach ($errors as $error) {
echo "$error <br /> \n";
}
echo '<a href="index.php">Try again</a><br />';
}
?>
</code></pre>
<p>process2.php(login):</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'config/connect.php';
$username = trim( isset($_SESSION['username']) ? $_SESSION['username'] : "" );
//check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['signin'])) {
// looks like a hack, send to index.php
header('Location: index.php');
die();
}
if (empty($_POST["username"])) {
echo 'Fill in username to sign in. <a href= index.php>Try again</a><br />';
die();
}
if (empty($_POST["pw"])) {
echo 'Fill in password to sign in. <a href= index.php>Try again</a><br />';
die();
}
$sql = "SELECT pw FROM users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql);
if ( !$stmt ) {
echo mysqli_error($conn);
die();
}
$stmt->bind_param('s', $_POST['username']);
if ( !$stmt->execute() ) {
echo mysqli_error($conn);
die();
}
// we found a row with that username,
// now we need to check the password is correct
// get the password from the row
$stmt->bind_result($hashed_pwd); // Binds variables to a prepared statement for result storage
$stmt->fetch(); // Fetch results from a prepared statement into the bound variables
if ( password_verify($_POST['pw'], $hashed_pwd) ) {
// password verified
$_SESSION["username"] = $_POST['username'];
header('Location: profile.php');
} else {
echo 'Incorrect username or Password. <a href= index.php>Try again</a><br />';
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T20:48:45.407",
"Id": "477975",
"Score": "0",
"body": "What is `password_verify`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T21:39:27.833",
"Id": "477977",
"Score": "0",
"body": "To verify the hashed password"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T21:53:38.213",
"Id": "477978",
"Score": "0",
"body": "I figured that much. Can you provide the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T22:08:37.170",
"Id": "477979",
"Score": "0",
"body": "That's really all there is"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T23:16:55.017",
"Id": "477985",
"Score": "1",
"body": "@vnp: Just read the manual: https://www.php.net/manual/en/function.password-verify.php"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T23:27:15.773",
"Id": "478404",
"Score": "0",
"body": "Your question's title is meant to describe what your script(s) do(es). Please reword your title to describe the action that your script undertakes instead of what your concern is."
}
] |
[
{
"body": "<p>Just a few remarks.</p>\n\n<p>You constantly use <code>$_POST</code> across your code eg <code>$_POST['username']</code></p>\n\n<p>Example:</p>\n\n<pre><code>if (empty($_POST[\"username\"])) {\n $errors[] = \"Fill in username to sign up\";\n}\n</code></pre>\n\n<p>You should collect the form fields to variables, sanitize them etc once, then reuse the variables in the rest of the code.</p>\n\n<p>What I mean is something like this:</p>\n\n<pre><code><?php\n\n// init variables\n$username = '';\n\n// collect form fields\nif (isset($_POST['username'])) {\n $username = trim($POST['username']);\n}\n\n// input validation\nif (empty($username)) {\n echo \"Username is empty\";\n}\n?>\n</code></pre>\n\n<p>You have this line:</p>\n\n<pre><code>$username = trim( isset($_SESSION['username']) ? $_SESSION['username'] : \"\" );\n</code></pre>\n\n<p>but you are not doing anything with the variable ? And why trim a session variable ??? This makes no sense. Trimming the username is something that should be done on the POST request. But the username should be fixed after login.</p>\n\n<p>You have this code:</p>\n\n<pre><code>$sql = \"SELECT pw FROM users WHERE username = ?\";\n$stmt = mysqli_prepare($conn, $sql);\nif ( !$stmt ) {\n\n echo mysqli_error($conn);\n die();\n\n}\n</code></pre>\n\n<p>Note: instead of mysqli you could use PDO to make code more portable.</p>\n\n<p>It's a bad idea to print raw error messages, not only because it does not look professional but it is <strong>information disclosure</strong> that can be used to leverage possible vulnerabilities. Nobody should gain insight into your tables or PHP code. If something goes wrong, show a generic message, handle the error and make sure you get notified one way or the other, then fix the error. Having an application-wide error handler would be nice.</p>\n\n<p>Still, this code looks strange to me:</p>\n\n<pre><code>$stmt->fetch(); // Fetch results from a prepared statement into the bound variables\n</code></pre>\n\n<p>I haven't tested it, but what happens if no matching row is found ? You still try to fetch one row ? Have you tested your code with non-existent user names ?</p>\n\n<p>The most interesting, and possibly the more critical thing you've not shown yet is the <strong>login form</strong>.</p>\n\n<p>While this is not the most pressing issue here, I think you should consider learning a <strong>PHP framework</strong> to bring your skills up to date. The frameworks exist for a reason: to accelerate development, to produce reusable code, so that you don't reinvent the wheel and come up with poor solutions. </p>\n\n<p>This is still the old way of coding. In 2020 I would not start a new project based on old development patterns. There is no added value and you are already accruing <strong>technical debt</strong> since the code can be considered outdated by today's standards.</p>\n\n<p>Presentation could be improved too, just using tabulations would make the code more readable. This is important, because a proper outline of the code can make logical flaws or branching errors more visible. For example incorrectly nested ifs. I don't know how you feel, but I find it hard to parse poorly-formatted code, even when it's yours. You are tempted to skim code instead of concentrating on it because it is an eyesore.</p>\n\n<p>I would like to end on a more positive note but I found out that many tutorials found online are outdated and dangerous. The worst is that the best ranking pages are those that promote bad/deprecated practices.</p>\n\n<p>For instance when I type 'php secure login form' in a search engine this is what I get: <a href=\"https://itsourcecode.com/free-projects/php-project/secure-login-page-using-phpmysql/\" rel=\"nofollow noreferrer\">How to Create a Secure Login Page in PHP with MySQL</a>. Outdated code that contains <strong>SQL injections</strong>. This is exactly the stuff we are telling you to avoid.</p>\n\n<pre><code> $email = trim($_POST['email']);\n $upass = trim($_POST['password']);\n $h_upass = sha1($upass);\nif ($upass == ''){\n ?> <script type=\"text/javascript\">\n alert(\"Password is missing!\");\n window.location = \"login.php\";\n </script>\n <?php\n}else{\n//create some sql statement \n $sql = \"SELECT * FROM `tblmember` WHERE `email` = '\" . $email . \"' AND `password` = '\" . $h_upass . \"'\";\n $result = mysqli_query($conn, $sql);\n</code></pre>\n\n<p>The worst is that the code was posted less than a year ago and is not some relic of the venerable past boosted by 20 years of SEO.</p>\n\n<p>Note to self: do not assume good page ranking = credibility.</p>\n\n<p>So it's no wonder you are struggling to find decent tutorials. I have found other examples that weren't nearly as bad but used <code>mysql_escape_string</code> (deprecated, then removed in PHP7).</p>\n\n<p>A more reasonable example: <a href=\"https://www.codingcage.com/2015/04/php-login-and-registration-script-with.html\" rel=\"nofollow noreferrer\">PHP Login and Registration Script with PDO and OOP</a>. But I still do not consider it satisfactory: it does not verify that the POST fields for username/passwords are set:</p>\n\n<pre><code>if(isset($_POST['btn-signup']))\n{\n $uname = trim($_POST['txt_uname']);\n $umail = trim($_POST['txt_umail']);\n $upass = trim($_POST['txt_upass']);\n</code></pre>\n\n<p>That means the resulting variables are unset. That may not be a vulnerability but that is not so great.</p>\n\n<p>You cannot assume that the form being submitted will be complete and not tampered with. You have to verify that every expected element is there and do not make lazy assumptions. Any server on the net is going to be subjected to incessant automated attacks. Script kiddies are after the low-hanging fruit. So you have to be paranoid.</p>\n\n<p>I don't know why it is so difficult to find a decent example. Maybe it's because developers are expected to use frameworks - <a href=\"https://www.tutsmake.com/laravel-6-custom-login-and-registration-example-tutorial/\" rel=\"nofollow noreferrer\">Laravel example</a></p>\n\n<p>Yes there is a learning curve. But you will become more productive afterward and produce better.</p>\n\n<p>You said you are building a social network, so this is an ambitious project and not a one-page script. It needs to be better structured. You need some kind of common code base.</p>\n\n<p>In conclusion I think you should not even try to fix this code although it is good to understand the pitfalls. Relearn PHP, get up to speed with modern development tools.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T01:11:14.860",
"Id": "477990",
"Score": "0",
"body": "So do you think Laravel would be a good framework to learn ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T01:17:26.963",
"Id": "477991",
"Score": "0",
"body": "It's not the only one but probably the most established today and it is free, open-source. [Some others](https://hackernoon.com/8-popular-php-frameworks-for-web-development-in-2020-od3f38ez). Happy shopping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T03:25:37.700",
"Id": "478000",
"Score": "0",
"body": "I already told you. Don't sanitize user input. Validate it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T06:38:33.853",
"Id": "478006",
"Score": "0",
"body": "\"You still try to fetch one row ?\" Yes, this is how database APIs work. You fetch, and then if it returned anything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T15:04:47.080",
"Id": "478076",
"Score": "0",
"body": "Is there a big problem with always using `$_POST` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T16:08:31.143",
"Id": "478081",
"Score": "0",
"body": "Well the problem is the **redundancy**. For example if you **trim** certain fields you would have to repeat the trim every time you refer to that POST field in your code, which is repetitive and wasteful. Also, you'd have to check if the POST field is set... are you going to repeat `if(isset(...` every time ? That's why I prefer to assign variables at the very beginning. Note in my example I set default values. Even if some POST fields are missing, I still have variables that are always set no matter what."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T17:17:39.157",
"Id": "478085",
"Score": "0",
"body": "So things like these are good enough ? `$_SESSION['reg_email2'] = $em2; // stores email2 in session variable` and `$pw = \"\"; ` together ?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T00:42:44.343",
"Id": "243533",
"ParentId": "243524",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243533",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T17:11:27.517",
"Id": "243524",
"Score": "3",
"Tags": [
"php",
"html",
"sql",
"html5",
"mysqli"
],
"Title": "How secure is my login and signup code"
}
|
243524
|
<p>I'm learning C, so as a practice problem I implemented Conway's Game of Life. For anyone unfamiliar, the problem is set out <a href="https://en.wikipedia.org/wiki/Conway's_Game_of_Life" rel="nofollow noreferrer">here</a>. To summarize, there is a grid of "cells" that can be either alive or dead. This grid is updated in "steps". In each step, live cells with 2 or 3 live neighbors survive, dead cells with 3 live neighbors come alive, and live cells with less than 2 or more than 3 live neighbors die.</p>
<p>I'm mostly looking for C advice (anything I might be doing badly in terms of pointers, references, memory management etc.). That said, architecture and control flow critiques are 100% welcome as well.</p>
<p>One of the specific things I'm wondering about is my logic for not checking neighbors that don't exist on the edges (my implementation assumes cells that are off the board to be dead). Specifically, I'm wondering if there's a more elegant way to implement that than the way I've done it?</p>
<p>Code: </p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
int i;
int j;
bool** emptyBoard();
void initialPosition(bool** board, char startPos[]);
void printArray(bool** board);
void freeArray(bool** board);
bool** step(bool** board);
void wait(float s);
int width = 50;
int height = 50;
void initialPosition(bool** emptyBoard, char startPos[] ) {
for(i=0; i < width; i++) {
for(j = 0; j < height; j++) {
*(emptyBoard[i] + j) = (bool) (startPos[(i * width) + j] - '0');
}
}
}
bool** emptyBoard() {
bool **board;//pointer to pointer
board = malloc(sizeof (bool *) * width);//array of pointers (each pointer to array of ints)
for (i = 0; i < width; i++) {
*(board + i) = malloc(sizeof (bool) * height);
}
for (i = 0; i < width; i++) {
for (j = 0; j < height; j++){
bool c = 0;
*(board[i] + j) = c;
}
}
return(board);
}
void printArray(bool** board) {
for (i = 0;i < width; i++) {
for (j = 0; j < height; j++){
if(*(*(board + i) + j) == 0) {
printf(" ");
} else {
printf(" o ");
}
//printf("%i ", *(*(board + i) + j));
}
printf("\n");
}
}
void freeArray(bool** board){
for (i = 0; i < width; i++) {
free(board[i]);
}
free(board);
}
bool** step(bool** board) {
bool** newBoard = emptyBoard();
int neighbors;
int k;
for(i=0; i < width; i++) {
for(j = 0; j < height; j++) {
neighbors = 0;
if(i > 0) {
if (*(*(board + i - 1) + j) == 1) {//i-1, j if i > 0
neighbors++;
}
if(j > 0) {//i-1, j if i > 0 and j > 0
if (*(*(board + i - 1) + j - 1) == 1) {
neighbors++;
}
}
if (j < width - 1) {
if (*(*(board + i - 1) + j + 1) == 1) {//i-1, j+1 if j > 0 and j < width - 1
neighbors++;
}
}
}
if(j > 0) {
if (*(*(board + i) + j - 1) == 1) {//i, j-1 if j > 0
neighbors++;
}
if (i < height - 1){
if (*(*(board + i + 1) + j - 1) == 1) {//i + 1, j -z if j > 0 and i < height - 1
neighbors++;
}
}
}
if(j < width - 1) {
if (*(*(board + i) + j + 1) == 1) {//i, j+1 if j < width -
neighbors++;
}
}
if(i < height - 1) {
if (*(*(board + i + 1) + j) == 1) {
neighbors++;
}
if(j < width - 1){
if (*(*(board + i + 1) + j + 1) == 1) {//if i < height - 1 and j < width - 1, i+1, j+1
neighbors++;
}
}
}
if (*(*(board + i) + j) == 0) {
if(neighbors == 3) {
*(*(newBoard + i) + j) = (bool) 1;
} else {
*(*(newBoard + i) + j) = (bool) 0;
}
} else if (*(*(board + i) + j) == 1) {
if(neighbors < 2) {
*(*(newBoard + i) + j) = (bool) 0;
} else if (neighbors == 2 || neighbors == 3) {
*(*(newBoard + i) + j) = (bool) 1;
} else if (neighbors > 3) {
*(*(newBoard + i) + j) = (bool) 0;
}
}
}
}
freeArray(board);
return(newBoard);
}
void wait(float s) {
int now = clock();
int then = clock() + (CLOCKS_PER_SEC * s);
while(clock() != then) {
}
}
int main() {
bool** board = emptyBoard();
printArray(board);
printf("--------------\n");
initialPosition(board, "0000000000000000000000000000000000000000000000000"
"0000000000000000000000000100000000000000000000000"
"0000000000000000000000010100000000000000000000000"
"0000000000000110000001100000000000011000000000000"
"0000000000001000100001100000000000011000000000000"
"0110000000010000010001100000000000000000000000000"
"0110000000010001011000010100000000000000000000000"
"0000000000010000010000000100000000000000000000000"
"0000000000001000100000000000000000000000000000000"
"0000000000000110000000000000000000000000000000000");
printArray(board);
while(true){
//sleep(1);
wait(0.25);
printf("\e[1;1H\e[2J");
board = step(board);
printArray(board);
}
freeArray(board);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:04:41.643",
"Id": "478070",
"Score": "1",
"body": "Eric Lippert is currently writing a blog series about game of life in C#, specifically about how different algorithms have wildly different performances. Might be worth a read. https://ericlippert.com/2020/05/28/life-part-13/"
}
] |
[
{
"body": "<p>When accessing array elements, don't use the clunky <code>*(board + i)</code> notation. Use <code>board[i]</code>. (You're already doing this in some places, and you should be consistent.)</p>\n\n<p>Eliminate the use of global <code>i</code> and <code>j</code> variables as loop variables. Use local variables instead. This can help with optimization, and avoids problems where a function called while in a loop in another function can mess up the latter's looping.</p>\n\n<p>There is no verification that the <code>startPos</code> string in <code>initialPosition</code> is long enough. You can read past the end of it. If the string is not long enough, you can either set the rest of the elements to 0 (false) and continue, or report an error. Rather than computing the index into <code>startPos</code> all the time, you can increment the pointer with <code>*startPos++</code>. This would also make it easier to check for reaching the end of the string.</p>\n\n<p>You need to clarify to yourself if your <code>board</code> matrix is row major or column major. Your usage in most of the code has it as column major, but your <code>printArray</code> function will display it transposed, with the columns running horizontally. While this is not apparent with a square board, you can see the difference when <code>width</code> does not equal <code>height</code>.</p>\n\n<p>For readability, in <code>emptyBoard</code> your initialization of the board elements should be <code>board[i][j] = false;</code>. You don't need to use the <code>c</code> local variable. And you should check the value returned by <code>malloc</code> for errors (it can return NULL). The two loops here can be combined into one, by initializing each new allocated <code>board[i]</code> element when it is allocated.</p>\n\n<p><code>printArray</code> can be simplified with <code>puts(board[i][j] == 0 ? \" \" : \" o \");</code>. Or, since <code>board[i][j]</code> is a <code>bool</code> (which will have a value of 0 or 1), you can use an array reference to pick which string to output.</p>\n\n<p>The <code>step</code> function can make use of a bool's <code>0</code> or <code>1</code> values by using addition instead of if statements. <code>neighbors += board[i][j];</code> The assignments to the new board elements should use the predefined <code>true</code> and <code>false</code> macros rather than typecasting integer values. Then we can compress that big nested if chunk with one line:</p>\n\n<pre><code>newboard[i][j] = neighbors == 3 || (neighbors == 2 && board[i][j] == true);\n</code></pre>\n\n<p>The way to avoid having all those <code>if</code> checks when updating the board is to create board with a border around it. This border (top, left, bottom, and right) will be one extra row/column that is always 0. It is never written to. So during the board you can access adjacent elements without having to check for out-of-bounds array accesses. Appropriate changes to your loop indexing would need to be made (e.g., looping from 1 to width inclusive).</p>\n\n<p>In <code>wait</code>, the typical way to compute the end time is as an offset from the already saved <code>now</code>, so you'd have <code>int then = now + (CLOCKS_PER_SEC * s);</code>. This avoids a second call to a library function that will probably return the same value, and avoid longer delays if the value returned has increased (possibly because the system is busy and some other process was using the CPU).</p>\n\n<p>The indentation of the string passed to <code>initialPosition</code> is slightly off. This string could be potentially be stored in a static or global variable, or read from input (a file or from the command line).</p>\n\n<p>Note that many console windows these days do not support the ANSI escape sequences. A comment to explain what they are doing would be helpful for future readers. I remember what the <code>J</code> escape sequence is, but not <code>H</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T20:44:04.193",
"Id": "243527",
"ParentId": "243526",
"Score": "4"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The code currently includes this line in <code>initialPosition</code>:</p>\n\n<pre><code>*(emptyBoard[i] + j) = (bool) (startPos[(i * width) + j] - '0');\n</code></pre>\n\n<p>Since each row is <code>width</code> cells wide, we should be multiplying by <code>j</code> rather than <code>i</code>. </p>\n\n<pre><code>*(emptyBoard[i] + j) = (bool) (startPos[j * width + i] - '0');\n</code></pre>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The variable <code>k</code> in <code>step</code> is declared code but never used. Similarly, <code>now</code> in <code>wait</code> is defined but unused. Since unused variables are a sign of poor code quality, you should seek to eliminate them. Your compiler is probably smart enough to warn you about such things if you know how to ask it to do so.</p>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error. Eliminating global variables where practical is always a good idea. In this case, I would suggest you keep them as global but make them both <code>const</code> to clearly signal to the reader that these are fixed constants. However <code>i</code> and <code>j</code> should simply be declared within each loop. Specifically instead of this:</p>\n\n<pre><code>for(i=0; i < width; i++) {\n</code></pre>\n\n<p>Write this:</p>\n\n<pre><code>for(int i=0; i < width; i++) {\n</code></pre>\n\n<h2>Use consistent formatting</h2>\n\n<p>The code as posted has inconsistent indentation (e.g. the loop in <code>freeArray</code>) and inconsistent use of whitespace (the spacing within each <code>for</code> loop is inconsistent) which makes it harder to read and understand. Pick a style and apply it consistently. </p>\n\n<h2>Try to write portable code</h2>\n\n<p>It's a subtle point, but the <code>\\e</code> escape sequence is not actually defined in the ISO standard for C. For that reason, a safer alternative would be to use <code>\\x1b</code>.</p>\n\n<h2>Simplify expressions</h2>\n\n<p>I've already mentioned this line in <code>initialPosition</code>:</p>\n\n<pre><code>*(emptyBoard[i] + j) = (bool) (startPos[(i * width) + j] - '0');\n</code></pre>\n\n<p>The left side could simply be <code>emptyBoard[i][j] =</code> which is much clearer. The right side could be simplified a bit as well. I'd write the line like this:</p>\n\n<pre><code>emptyBoard[i][j] = startPos[j * width + i] != '0';\n</code></pre>\n\n<p>Note also that I've changed it mathematically per the first point. However, see the suggestion below for an alternative scheme. </p>\n\n<h2>Prefer a single block to pointer-to-pointers schemes</h2>\n\n<p>The code would likely be much simpler and easier to read if, instead of the current pointer-to-pointers approach the whole board is simply allocated in a single structure. Then you can use the same sort of indexing as shown above with <code>board[i + j * width]</code>. I think that would be easier for most people to read and understand as contrasted with lines like this:</p>\n\n<pre><code>if(*(*(board + i) + j) == 0) {\n</code></pre>\n\n<p>For instance the <code>emptyBoard()</code> function could be reduced to a single line:</p>\n\n<pre><code>bool* emptyBoard() {\n return calloc((width + 2) * (height + 2), sizeof(bool));\n}\n</code></pre>\n\n<h2>Check the return value of <code>malloc</code></h2>\n\n<p>If the program runs out of memory, a call to <code>malloc</code> can fail. The only indication for this is that the call will return a <code>NULL</code> pointer. You should check for this and avoid dereferencing a <code>NULL</code> pointer (which typically causes a program crash). </p>\n\n<h2>Simplify range checking by eliminating the need for it</h2>\n\n<p>The existing <code>step</code> code does a lot of checking to make sure that all of the checked neighbors are in range. That's much better than not checking and overrunning the bounds of the board, but there's a simpler way to accomplish the same effect. The way to do it is to allocate a slightly larger array with two additional rows and two additional columns to act as a frame around the real board. If you then iterate only over the real board, there is no need for further range checking.</p>\n\n<h2>Separate functions into small chunks</h2>\n\n<p>The <code>step</code> function does three things. It allocates a new array, computes the neighbor counts for each cell and then exchanges the old and new arrays. I'd suggest that computing the neighbor count for a particular cell would be better done as a separate function. </p>\n\n<p>If you follow these suggestions, the <code>step</code> and its helper function are much simpler:</p>\n\n<pre><code>static int getNeighborCount(const bool *location) {\n static const ssize_t deltas[8] = {\n -2-1-width, -2-width, -2+1-width,\n -1, +1,\n +2-1+width, +2+width, +2+1+width,\n };\n int neighbors = 0;\n for (int i=0; i < 8; ++i) {\n neighbors += *(location + deltas[i]);\n }\n return neighbors;\n}\n\nbool* step(bool* board) {\n bool* newBoard = emptyBoard();\n if (newBoard == NULL) {\n return NULL;\n }\n bool* dst = newBoard + 3 + width;\n bool* src = board + 3 + width; \n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n int livingNeighbors = getNeighborCount(src);\n *dst = (livingNeighbors == 3) || (livingNeighbors == 2 && *src); \n ++src;\n ++dst;\n }\n src += 2;\n dst += 2;\n }\n freeArray(board);\n return(newBoard);\n}\n</code></pre>\n\n<h2>Use library functions</h2>\n\n<p>The code includes this function:</p>\n\n<pre><code>void wait(float s) {\n int then = clock() + (CLOCKS_PER_SEC * s);\n while(clock() != then) {\n }\n}\n</code></pre>\n\n<p>It's probably better to use <code>nanosleep</code> here. That function is a POSIX function, rather than a C standard library call, but it appears that you are running on a POSIX machine anyway, judging by the inclusion of <code>unistd.h</code> in the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T23:39:25.457",
"Id": "243531",
"ParentId": "243526",
"Score": "8"
}
},
{
"body": "<h2>Reallocation</h2>\n\n<p>I will recommend against repeatedly allocating and deleting boards. Allocate two up front, pass both into step(), returning void, and then swap them in main. First off, this will be faster, as you don't have to do the allocations and frees. Second, this will avoid potential memory fragmentation or issues involving sub-optimal implementations of malloc. Third, this will allow you to, if needed, completely eliminate malloc and free usage. (This might be needed if you want to move the implementation to a microcontroller, like <a href=\"https://www.adafruit.com/product/89\" rel=\"nofollow noreferrer\">Adafruit's</a>.)</p>\n\n<p>This might not be appropriate if you are dynamically sizing the board, but you aren't doing that. If you do dynamic sizing, you might want to make the board a structure including the width, height, and data pointer, and other things may get interesting.</p>\n\n<p>I might suggest (inside step()) the names current and next instead of board and newBoard, but that's a matter of taste.</p>\n\n<h2>Accessors</h2>\n\n<p>Depending on your usage, you might want a macro or inline-able function to access a particular numbered cell in the board. Done right, this could greatly simplify adding dynamic sizing at a later time. For instance, with your original layout:</p>\n\n<pre><code>/* macro version */\n#define CELL(board,x,y) (((x)>=0)&&((y)>=0)&&((x)<width)&&((y)<height)&&board[x][y])\n/* inline-able version */\nbool CELL(bool**board,int x,int y){return (x>=0)&&(y>=0)&&(x<width)&(y<height)&&board[x][y]; }\nstatic bool dummycell;\nbool*CELL_ptr(bool**board,int x,int y){\n if ((x>=0)&&(y>=0)&&(x<width)&(y<height)) {\n return &board[x][y];\n } else {\n dummycell = false;\n return &dummycell;\n }\n}\n</code></pre>\n\n<p>You could make a set_CELL as well, or write *CELL_ptr(board,x,y) = newvalue;</p>\n\n<p>Using @Edward's variant, the bounds checks could be dropped, and the array access becomes <code>board[x + y*width]</code>.\nIf the board then becomes a structure, the accessors would then receive that structure and do the relevant work.</p>\n\n<h2>printArray</h2>\n\n<p>The function printArray() includes the line </p>\n\n<pre><code>if(*(*(board + i) + j) == 0) {\n</code></pre>\n\n<p>Do <strong>not</strong> compare bool values with int constants.\n(There is a classic bug of writing <code>if (boolvalue == 1)</code> and having boolvalue be 2.)\nUse the boolean operators, so this line could be:</p>\n\n<pre><code>if(!*(*(board + i) + j)) {\n</code></pre>\n\n<p>You might want to do the true case first instead of the false, which would make that line:</p>\n\n<pre><code>if(*(*(board + i) + j)) {\n</code></pre>\n\n<p>The current printing uses three character positions per cell. This means your 50x50 board requires 50 lines by 150 columns. I suggest using fewer characters per cell.</p>\n\n<p>This function could also benefit from @Edward's technique with variable <code>bool *src</code>, even if only on a line by line basis.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T15:36:14.927",
"Id": "478080",
"Score": "0",
"body": "could you expand on why allocating and freeing boards worse than allocating two and switching back and forth between them? is that a performance issue, or a style issue?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:52:55.817",
"Id": "243563",
"ParentId": "243526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243531",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T19:08:02.403",
"Id": "243526",
"Score": "5",
"Tags": [
"c",
"game-of-life"
],
"Title": "Learning C: Conway's Game of Life"
}
|
243526
|
<blockquote>
<p>this code is for return duplicates after sorted them, and also to
return the missed value between the limits of the given array, it's
executed correctly, but i need to optimize it so it excecute in less
time than it execute can any one help?</p>
</blockquote>
<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 findDupsMiss(arr) {
// your code here
var noDuplicates = [];
var missedNum;
var duplicates = [];
var sortedDuplicates =[]
arr.forEach((el, i) => {
if(noDuplicates.includes(el) == false){
noDuplicates.push(el)
}
})
var sortedArr = noDuplicates.sort((a,b) => a-b);
for(var i=0 ; i<sortedArr.length -1 ; i++){
if((sortedArr[i]+1) !== sortedArr[i+1]){
missedNum = sortedArr[i] + 1
}
}
arr.forEach( el => {
if(arr.indexOf(el) != arr.lastIndexOf(el)){
duplicates.push(el)
}
})
duplicates.forEach(el => {
if(sortedDuplicates.includes(el) == false){
sortedDuplicates.push(el)
}
})
var lastdup = sortedDuplicates.sort((a,b) => a-b);
return [missedNum , lastdup]
}
findDupsMiss([10,9,8,9,6,1,2,4,3,2,5,5,3])</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T03:19:37.610",
"Id": "477998",
"Score": "2",
"body": "Can you give us a better description of what the code does? Maybe add sample input and output. What are \"the limits of given array\"? What is \"the missed value between limits\"?"
}
] |
[
{
"body": "<p>On the small 13 element array your implementation appears to be fairly performant, but since you request a \"faster\" implementation I took a stab at one myself.</p>\n\n<h1>Implementation</h1>\n\n<p>In this implementation I wanted to remove the multiple loops and use a data structure that lent itself to faster lookups, so I used plain javascript objects as maps. I also defined each array function callback outside where it'd be used to only instantiate a single copy.</p>\n\n<pre><code>function findDupsMiss2(arr) {\n const processedNumbers = {};\n const duplicates = {};\n const noDuplicates = {};\n\n const checkDupOrNot = (el, i) => {\n if (processedNumbers[el]) {\n duplicates[el] = el;\n delete noDuplicates[el];\n } else {\n noDuplicates[el] = el;\n }\n processedNumbers[el] = el;\n };\n\n arr.forEach(checkDupOrNot);\n\n const missedReduceFn = (missed, el, i, arr) =>\n el + 1 !== arr[i + 1] ? el : missed;\n const missed = [\n ...Array(\n processedNumbers[Object.values(processedNumbers).length - 1]\n ).keys()\n ].reduce(missedReduceFn, null);\n\n return [missed, Object.values(duplicates)];\n}\n</code></pre>\n\n<h1>Testing</h1>\n\n<p>This is the function I defined to measure how performant a function is:</p>\n\n<pre><code>const measurePerf = (fn, data, runs = 1000000) =>\n [...Array(runs).keys()]\n .map(() => {\n const start = performance.now();\n fn(data);\n const end = performance.now();\n return end - start;\n })\n .reduce((total, current) => total + current) / runs;\n</code></pre>\n\n<p>This takes a function and measures how long it takes to execute, sums the total time then divides by the # of runs to get an average execution time.</p>\n\n<p>Used as such </p>\n\n<pre><code>measurePerf(findDupsMiss, data); // uses default 1 million iterations\nmeasurePerf(findDupsMiss, data, 1000);\n</code></pre>\n\n<h1>Initial Results</h1>\n\n<p>Using the default 1-million iteration performance measure</p>\n\n<pre><code>findDupsMiss1\n[7, Array[4]]\n0: 7\n1: Array[4]\n0: 2\n1: 3\n2: 5\n3: 9\n0.0021040050006413367\n\nfindDupsMiss2\n[7, Array[4]]\n0: 7\n1: Array[4]\n0: 2\n1: 3\n2: 5\n3: 9\n0.0023690749967063313\n</code></pre>\n\n<p>At first this may seem like your code is already faster (or my implementation is slower), but this isn't the entire story.</p>\n\n<p>If we analyze the <strong>Big-O</strong> complexity of your implementation we find it is <strong>O(n^2)</strong>. Of the outer loops (3x <strong>O(n)</strong> forEach loops and 2x <strong>O(nLog_n)</strong> sorts) each of the forEach loops has an additional <strong>O(n)</strong> search loop to find either an index or if an element is already included, bumping the <strong>Big-O</strong> to <strong>O(n^2)</strong>.</p>\n\n<p>The other implementation has also 4x loops (1x forEach, 1x array spread, 1x array reduce, 1x object.values), but has no inner loops, each loop uses an <strong>O(1)</strong> lookup in a map, so has an <strong>O(n)</strong> complexity.</p>\n\n<blockquote>\n <p>But where is the sort?</p>\n</blockquote>\n\n<p>When using an object as a map with number-like keys, they are inserted in numerical order, so we get \"sorting\" for free. (in reality there is probably <em>some</em> minimal search though).</p>\n\n<h1>Further Results & Extended Examination</h1>\n\n<blockquote>\n <p>What does this Big-O <strong>O(n^2)</strong> vs <strong>O(n)</strong> mean?</p>\n</blockquote>\n\n<p>This has to do with how much work there is to do based upon input size. When an algorithm's Big-O complexity is <strong>O(n)</strong> then when the input size doubles the output should roughly double, i.e. something <em>like</em> <em><code>2n</code></em> (hand wavey), whereas when an algorithm's Big-O complexity is <strong>O(n^2)</strong> then the output size something more like <em><code>4n</code></em>.</p>\n\n<p>Here's a rough table of output. Because of performance I had to drop the test performance iterations to 100 (versus10^6), but figured 100 runs is still enough to gather enough data for decent comparisons.</p>\n\n<p><em>TBH the average is less relevant here as this table is more to illustrate the ratio between the two algorithms, with a secondary comparison in parenthesis to highlight the ratio of output from the previous iteration</em></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 measurePerf = (fn, data, runs = 1000000) =>\n [...Array(runs).keys()]\n .map(() => {\n const start = performance.now();\n fn(data);\n const end = performance.now();\n return end - start;\n })\n .reduce((total, current) => total + current) /runs;\n\nfunction findDupsMiss1(arr) {\n // your code here\n var noDuplicates = [];\n var missedNum;\n var duplicates = [];\n var sortedDuplicates = [];\n\n arr.forEach((el, i) => {\n if (noDuplicates.includes(el) == false) {\n noDuplicates.push(el);\n }\n });\n var sortedArr = noDuplicates.sort((a, b) => a - b);\n for (var i = 0; i < sortedArr.length - 1; i++) {\n if (sortedArr[i] + 1 !== sortedArr[i + 1]) {\n missedNum = sortedArr[i] + 1;\n }\n }\n arr.forEach(el => {\n if (arr.indexOf(el) != arr.lastIndexOf(el)) {\n duplicates.push(el);\n }\n });\n duplicates.forEach(el => {\n if (sortedDuplicates.includes(el) == false) {\n sortedDuplicates.push(el);\n }\n });\n\n var lastdup = sortedDuplicates.sort((a, b) => a - b);\n\n return [missedNum, lastdup];\n}\n\nfunction findDupsMiss2(arr) {\n const processedNumbers = {};\n const duplicates = {};\n const noDuplicates = {};\n\n const checkDupOrNot = (el, i) => {\n if (processedNumbers[el]) {\n duplicates[el] = el;\n delete noDuplicates[el];\n } else {\n noDuplicates[el] = el;\n }\n processedNumbers[el] = el;\n };\n\n arr.forEach(checkDupOrNot);\n\n const missedReduceFn = (missed, el, i, arr) =>\n el + 1 !== arr[i + 1] ? el : missed;\n const missed = [\n ...Array(\n processedNumbers[Object.values(processedNumbers).length - 1]\n ).keys()\n ].reduce(missedReduceFn, null);\n\n return [missed, Object.values(duplicates)];\n}\n\nconst data = [10, 9, 8, 9, 6, 1, 2, 4, 3, 2, 5, 5, 3];\n\nconst perf1 = measurePerf(findDupsMiss1, data);\nconsole.log(findDupsMiss1(data), perf1);\n\nconst perf2 = measurePerf(findDupsMiss2, data);\nconsole.log(findDupsMiss2(data), perf2);\n\nconst processIterations = async () => {\n const results = [];\n\n // # elements 1, 2, 4, 8, 16, 32, 64, ..., 262144, 524288\n for (let i = 0; i < 20; i++) {\n const dataLength = 1 << i;\n const randData = [...Array(dataLength).keys()].map(() =>\n Math.floor(Math.random)\n );\n\n const [t1, t2] = await Promise.all([\n // For your sanity, start skipping findDupsMiss1 here at 11.\n // Maybe don't go more than 15 unless you like creating space heaters.\n i < 11 ? measurePerf(findDupsMiss1, randData, 100) : \"skipped\",\n measurePerf(findDupsMiss2, randData, 100)\n ]);\n\n results.push({\n iteration: i,\n dataLength,\n t1: Number.isFinite(t1) ? Number(t1).toFixed(3) : t1,\n t2: Number.isFinite(t2) ? Number(t2).toFixed(3) : t2\n });\n }\n\n return results;\n};\n\nprocessIterations().then(results => {\n console.log(`\\t# Elements\\tt1\\tt2\\tt2:t1 ratio`);\n results.forEach(({ iteration, dataLength, t1, t2 }, i, arr) => {\n const prev = arr[i - 1] || {};\n const t2t1Ratio = Number(t2 / t1).toFixed(2);\n const t1Ratio = Number(t1 / prev.t1).toFixed(1);\n const t2Ratio = Number(t2 / prev.t2).toFixed(1);\n\n console.log(\n `${iteration}\\t${dataLength}\\t${t1}(${t1Ratio})\\t${t2}(${t2Ratio})\\t${t2t1Ratio}`\n );\n });\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<pre><code> # Elements t1 avg t2 avg t2:t1 ratio \n0 1 0.002(NaN) 0.003(NaN) 1.50 \n1 2 0.002(1.0) 0.004(1.3) 2.00 \n2 4 0.003(1.5) 0.005(1.3) 1.67 \n3 8 0.006(2.0) 0.006(1.2) 1.00 \n4 16 0.005(0.8) 0.012(2.0) 2.40 \n5 32 0.011(2.2) 0.016(1.3) 1.45 \n6 64 0.031(2.8) 0.029(1.8) 0.94 \n7 128 0.084(2.7) 0.048(1.7) 0.57 \n8 256 0.270(3.2) 0.094(2.0) 0.35 \n9 512 1.032(3.8) 0.186(2.0) 0.18 \n10 1024 4.696(4.6) 0.372(2.0) 0.08 \n11 2048 16.303(3.5) 0.749(2.0) 0.05 \n12 4096 67.092(4.1) 1.492(2.0) 0.02 \n13 8192 266.986(4.0) 3.018(2.0) 0.01 \n14 16384 1081.774(4.1) 6.785(2.2) 0.01 \n15 32768 skipped(NaN) 12.298(1.8) NaN \n16 65536 skipped(NaN) 25.941(2.1) NaN \n17 131072 skipped(NaN) 49.775(1.9) NaN \n18 262144 skipped(NaN) 99.556(2.0) NaN \n19 524288 skipped(NaN) 195.841(2.0) NaN \n</code></pre>\n\n<p><em>Notes:</em></p>\n\n<ul>\n<li>Average time is in milliseconds</li>\n<li>Item in <code>()</code> is the ratio to the previous time (i.e. line above)</li>\n<li>Each iteration 100 runs for performance measuring</li>\n<li>Stopped measuring algorithm 1 after 15 iterations, it's just too slow</li>\n</ul>\n\n<h1>Conclusion</h1>\n\n<p>As can be seen, the table confirms your algorithm, after a certain point, appears to settle into roughly a 4x output size based upon 2x input, where the other algorithm appears to settle around 2x, as expected. Also, a tipping point appears to consistently be around iteration #6 / 64 elements when algorithm #2 overtakes algorithm #1 and is more performant.</p>\n\n<p><a href=\"https://codesandbox.io/s/find-duplicates-and-last-missed-algorithm-comparison-f17zx?expanddevtools=1&fontsize=14&hidenavigation=1&module=%2Fsrc%2Findex.js&theme=dark\" rel=\"nofollow noreferrer\"><img src=\"https://codesandbox.io/static/img/play-codesandbox.svg\" alt=\"Edit find duplicates and last missed algorithm comparison\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T06:18:57.673",
"Id": "243543",
"ParentId": "243528",
"Score": "1"
}
},
{
"body": "<p>From a short review;</p>\n<ul>\n<li>I like variables to be either spelled out or Spartan (meaning 1 char)\n<ul>\n<li><code>missedNum</code> -> <code>missedNumber</code></li>\n<li><code>noDuplicates</code> -> <code>uniqueDuplicates</code>?</li>\n<li><code>el</code> -> <code>i</code> (since you expect numbers)</li>\n</ul>\n</li>\n<li>Comments, you only have 1 line, and it could go ;)</li>\n<li>Reducing loop counts is the way to reduce run time.</li>\n</ul>\n<p>This counter example has 3 'loops', 1 <code>map</code> because I dont want to mess with the original list, 1 <code>sort</code> because that's central to the functionality, and 1 <code>for</code> to analyze the data. The code is not sexy at all, but I think reads well and seems to perform better.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function analyzeNumberList(list) {\n\n let numbers = list.map(i=>i).sort((a,b)=>a-b);\n let missing, dupes = [];\n \n for(let i = 0; i < numbers.length; i++){\n let current = numbers[i];\n let last = numbers[i-1];\n let secondLast = numbers[i-2];\n \n if(current == last){\n if(current != secondLast){\n dupes.push(current);\n }\n }else if(current != last + 1){\n missing = last + 1;\n }\n }\n return [missing, dupes];\n}\nconsole.log(analyzeNumberList([10,9,8,9,6,1,2,4,3,2,5,5,3]))</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-07-08T12:19:54.353",
"Id": "245181",
"ParentId": "243528",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T20:50:10.063",
"Id": "243528",
"Score": "1",
"Tags": [
"javascript",
"performance",
"array",
"sorting"
],
"Title": "Sort, & find out duplicates and missing elements in an array"
}
|
243528
|
<p>I have implemented a console calculator.</p>
<ul>
<li><p>It has support for variables over a set of integers and the following operations: multiplication, integer division, exponentiation, addition and subtraction. You can use parentheses in expressions.</p></li>
<li><p>The <code>SyntacticalAnalizer</code> class implements parsing and syntactic validation of a string entered by the user, converting the expression into reverse polish notation.</p></li>
<li><p>The <code>Interpreter</code> class checks for <code>NameError</code> errors and calculates the result of the expression.</p></li>
<li><p>The <code>SmartCalculator</code> class contains the <code>SyntacticAnalizer</code> and <code>Interpreter</code> classes and provides the user interface.</p></li>
</ul>
<p>The code passed the tests, but the state processing turned out to be very noodle-like. I would be grateful for advice on improving the code architecture. Source on <a href="https://github.com/sergeVe/smart-calculator/blob/master/calculator.py" rel="nofollow noreferrer">GitHub</a></p>
<pre><code>from string import ascii_letters
from collections import deque
class SyntacticalAnalyzer:
`"""
The name of a variable (identifier) can contain only Latin letters.
A variable can have a name consisting of more than one letter.
The case is also important; for example, n is not the same as N.
The value can be an integer number or a value of another variable.
Addition and subtraction operations are allowed.
Commands begin with a slash and can be: /exit and /help
"""`
_digits_tags: str = '1234567890'
_commands = ['/exit', '/help']
left_part: str = None
expression_stack: list = []
operator_priority: dict = {
'(': 0,
'+': 2,
'-': 2,
'*': 3,
'/': 3,
'^': 4,
')': 0
}
rpn_stack: deque = deque()
@staticmethod
def check_ascii(name):
for letter in name:
if letter not in ascii_letters:
return False
return True
@property
def checked_string(self) -> str:
return self.__checked_string
@checked_string.setter
def checked_string(self, value: str):
self.__checked_string = value
@property
def check_result(self):
return self.res
def __init__(self):
self.__checked_string: str = ''
self._state: str = 'assignment operator'
# scan chain bypass rules
self.chain_rules: dict = dict(skip=False,
off=False
)
# check status
self._status = dict(checker='',
error=None,
check_res=False,
)
# object passed to the wrapper class
self.res = dict(error=None,
state=None,
command=None,
left=None,
rpn_expression=None
)
# list of test functions
self._check_chain: list = [self.check_not_empty,
self.check_command_tag,
self.check_command_incorrectness,
self.check_equality_tag,
self.check_left_part,
self.check_right_part,
self.to_rpn
]
def notify(self, checker: str, check_res: bool):
"""
Passes the function name and the result of its work to the self._status object
@param checker: name of the function passed
@type checker: str
@param check_res: result of the function passed
@type check_res: bool
@return: None
"""
self._status['checker'] = checker
self._status['check_res'] = check_res
def check_status_handler(self):
"""
Reads the modified self._status object, sets self._state
and modifies the self.chain_rules object
@return: None
"""
if self._status['checker'] == 'check_not_empty' and not self._status['check_res']:
self._status['error'] = 'empty'
self._state = 'empty'
if self._status['checker'] == 'check_command_tag':
if self._status['check_res']:
self._state = 'command'
else:
self.chain_rules['skip'] = True
if self._status['checker'] == 'check_command_incorrectness':
if not self._status['check_res']:
self._status['error'] = self.add_command()
self.chain_rules['off'] = True
else:
self.chain_rules['off'] = True
if self._status['checker'] == 'check_equality_tag':
if not self._status['check_res']:
self._state = 'expression'
self.chain_rules['skip'] = True
if self._status['checker'] == 'check_left_part':
if not self._status['check_res']:
self._status['error'] = 'Invalid identifier'
if self._status['checker'] == 'check_right_part':
if not self._status['check_res']:
if self._state == 'assignment operator':
self._status['error'] = 'Invalid assignment'
self.chain_rules['skip'] = True
else:
self._status['error'] = 'Invalid identifier'
self.chain_rules['skip'] = True
if self._status['checker'] == 'to_rpn':
if not self._status['check_res']:
if self._state == 'assignment operator':
self._status['error'] = 'Invalid assignment'
else:
self._status['error'] = 'Invalid expression'
def perform_res(self):
"""
Checks self._state and self._status. Fills out the dictionary self.res
@return: None
"""
self.res['state'] = self._state
if self._state == 'empty':
self.res['error'] = 'empty'
self.chain_rules['off'] = True
if self._state == 'command':
if self._status['error'] is None:
self.res['command'] = self.add_command()
else:
self.res['error'] = self._status['error']
if self._state == 'assignment operator':
if self._status['error'] is None:
self.res['left'] = self.left_part
self.res['rpn_expression'] = self.rpn_stack
else:
self.res['error'] = self._status['error']
if self._state == 'expression':
if self._status['error'] is None:
self.res['rpn_expression'] = self.rpn_stack
else:
self.res['error'] = self._status['error']
def clear_init_fields(self):
"""
Clears all constructor fields before checking for a new line
@return: None
"""
self._state = 'assignment operator'
self._status['checker'] = ''
self._status['error'] = None
self._status['check_res'] = False
self.chain_rules['skip'] = False
self.chain_rules['off'] = False
for key, value in self.res.items():
if type(value) != dict:
self.res[key] = None
self.expression_stack = []
def run_check_chain(self):
"""
Starts a string check chain. Reads objects self.chain_rules and
self._status, if the skip == True property skips the next check,
if the property off == True or one of the checks has completed
with an error, terminates its work
@return: None
"""
j = -1
self.clear_init_fields()
for i, check in enumerate(self._check_chain):
if j == i:
self.chain_rules['skip'] = False
if self.chain_rules['skip']:
j = i + 1 if i + 1 < len(self._check_chain) else -1
continue
self.run_check(check)
self.check_status_handler()
if self._status['error'] is not None:
break
if self.chain_rules['off']:
break
self.perform_res()
def run_check(self, check_func):
"""
@type check_func: function
"""
result = check_func()
self.notify(check_func.__name__, result)
def check_not_empty(self):
return self.checked_string != ''
def check_command_tag(self):
return self.checked_string.startswith('/')
def check_command_incorrectness(self):
return self.checked_string in self._commands
def add_command(self) -> str:
for _command in self._commands:
if self.checked_string == _command:
return _command
return 'Unknown command'
def check_equality_tag(self) -> bool:
return '=' in self.checked_string
def is_variable(self, name: str) -> bool:
return all([len(name) >= 1, self.check_ascii(name)])
def check_left_part(self):
if self._state == 'assignment operator':
self.left_part = self.checked_string.split('=')[0].strip()
return self.is_variable(self.left_part)
@staticmethod
def get_fragment_params(value: str, end):
out_str = ''
pos = 0
sym = value[0]
while sym not in end:
out_str += sym
try:
pos += 1
sym = value[pos]
except IndexError:
return out_str, None
return out_str, pos
@staticmethod
def is_operator(item: str):
item_list: list = item.strip().split(' ')
my_str = ''.join(item_list)
if my_str[0] in '+-':
for el in my_str:
if el not in '+-':
return False
if my_str[0] in '/*^':
if len(my_str) > 1:
return False
return True
@staticmethod
def is_digit(item: str):
if item[0] == '0':
if len(item) != 1:
return False
return True
for el in item:
if el not in '1234567890':
return False
return True
@staticmethod
def is_left_parenthesis(item: str):
for el in item:
if el not in '(':
return False
return True
@staticmethod
def is_right_parenthesis(item: str):
for el in item:
if el not in ')':
return False
return True
@staticmethod
def get_first(value: str):
return value[0] if value else None
@staticmethod
def get_tag(letter: str):
if letter in ascii_letters:
return 'variable'
if letter in '-+/*^':
return 'operator'
if letter in '1234567890':
return 'digit'
if letter in '()':
return 'left parenthesis' if letter == '(' else 'right parenthesis'
@staticmethod
def get_end_tag(tag: str) -> str:
if tag == 'variable':
return ' )+-/*^'
if tag == 'operator':
return '(0123456789' + ascii_letters
if tag == 'digit':
return ' )+-/*^'
if tag == 'left parenthesis':
return ' 0123456789' + ascii_letters + '+-'
if tag == 'right parenthesis':
return ' +-/*^'
@staticmethod
def transform_operator(el: str):
if '-' in el or '+' in el:
minus_cnt = el.count('-')
if minus_cnt:
return '-' if minus_cnt % 2 != 0 else '+'
return '+'
return el
@staticmethod
def transform_parenthesis(el: str):
return list(el)
def transform_element(self, el: str, tag: str):
if tag == 'operator':
return self.transform_operator(el)
if tag in ['left parenthesis', 'right parenthesis']:
return self.transform_parenthesis(el.rstrip())
return el.rstrip()
@staticmethod
def add_el(container: list, el):
if type(el) == list:
container += el
else:
container.append(el.rstrip())
def check_right_part(self):
next_pos = 0
if self._state == 'assignment operator':
input_str = self.checked_string.split('=', 1)[1].strip()
else:
input_str = self.checked_string.strip()
if not input_str:
return False
while True:
current: str = input_str[next_pos:]
sym: str = self.get_first(current)
name = self.get_tag(sym)
end_tag = self.get_end_tag(name)
el, offset = self.get_fragment_params(value=current, end=end_tag)
conditions = [
self.is_variable(el),
self.is_operator(el),
self.is_digit(el),
self.is_left_parenthesis(el),
self.is_right_parenthesis(el)
]
if not any(conditions):
return False
el = self.transform_element(el=el, tag=name)
if not self.expression_stack or self.expression_stack[-1] == '(':
if el in '+-':
self.expression_stack.append('0')
self.add_el(self.expression_stack, el)
if offset is None:
return True
temp = current[offset:]
offset += temp.find(temp.lstrip())
next_pos += offset
def to_rpn(self):
f = False
operators: list = []
for item in self.expression_stack:
if self.is_digit(item) or self.is_variable(item):
self.rpn_stack.append(item)
else:
if not operators:
operators.append(item)
else:
if item == '(' or self.operator_priority[item] > self.operator_priority[operators[-1]]:
operators.append(item)
else:
if not operators:
return False
while operators:
operator = operators.pop()
if operator == '(':
f = True
break
self.rpn_stack.append(operator)
if item == ')' and not f:
return False
if item != ')':
operators.append(item)
if operators:
if '(' in operators:
return False
else:
while operators:
self.rpn_stack.append(operators.pop())
return True
# End of class SyntacticalAnalyzer
class Interpreter:
bye_string = 'Bye!'
help_string = 'The program calculates expressions using addition, subtraction, multiplication, integer division' \
' and exponentiation over a set of integers, and also uses variables.'
def __init__(self, obj):
self.variables: dict = {}
self.obj = obj
self.error: str = None
self.res: int = None
self.rpn_stack: deque = deque()
def execute(self):
if not self.analysis_handler():
return False
return True
def analysis_handler(self):
"""
Читает self.obj.
@return:
"""
self.rpn_stack = deque()
self.res = None
self.error = None
if self.obj['state'] == 'empty':
pass
if self.obj['state'] == 'command':
if not self.command_handler(self.obj['command']):
return False
if self.obj['state'] == 'expression':
if not self.expression_handler():
print(self.error)
else:
print(self.res)
if self.obj['state'] == 'assignment operator':
if not self.assignment_handler():
print(self.error)
return True
def command_handler(self, param: str) -> bool:
if param == '/exit':
print(self.bye_string)
return False
if param == '/help':
print(self.help_string)
return True
def expression_handler(self):
if not self.check_variables():
return False
self.res = self.get_expression_result()
return True
@staticmethod
def calculate_this(one, two, sign):
one, two = [int(x) for x in [one, two]]
if sign == '+':
return one + two
if sign == '-':
return one - two
if sign == '*':
return one * two
if sign == '/':
return one // two
if sign == '^':
return one ** two
@staticmethod
def is_digit(item: str):
if item[0] == '0':
if len(item) != 1:
return False
return True
for el in item:
if el not in '1234567890':
return False
return True
def get_expression_result(self):
result_stack: list = []
while self.rpn_stack:
item = self.rpn_stack.popleft()
if self.is_digit(item):
result_stack.append(item)
else:
second, first = result_stack.pop(), result_stack.pop()
result_stack.append(self.calculate_this(first, second, item))
return result_stack[0]
def assignment_handler(self):
if not self.expression_handler():
return False
left = self.obj['left']
self.variables[left] = self.res
return True
def check_variables(self):
self.rpn_stack = self.obj['rpn_expression']
for i, item in enumerate(self.rpn_stack):
if item in self.variables:
self.rpn_stack[i] = self.variables[item]
else:
if item[0] in ascii_letters:
return False
return True
class SmartCalculator:
"""
The name of a variable (identifier) can contain only Latin letters.
A variable can have a name consisting of more than one letter.
The case is also important; for example, n is not the same as N.
The value can be an integer number or a value of another variable.
It should be possible to set a new value to an existing variable.
To print the value of a variable you should just type its name.
"""
_analyzer_methods = ['run_check_chain']
_interpreter_methods = ['execute', 'analysis_handler']
def __init__(self):
self._analyzer: SyntacticalAnalyzer = SyntacticalAnalyzer()
self.analyzer_result: dict = self._analyzer.check_result
self._interpreter: Interpreter = Interpreter(self.analyzer_result)
def __getattr__(self, item):
for item in self._analyzer_methods + self._interpreter_methods:
if item in self._analyzer_methods:
return getattr(self._analyzer, item)
if item in self._interpreter_methods:
return getattr(self._interpreter, item)
def run(self):
while True:
self._analyzer.checked_string = input().strip()
self._analyzer.run_check_chain()
if self._analyzer.res['error'] is not None and self._analyzer.res['error'] != 'empty':
print(self._analyzer.res['error'])
else:
if not self._interpreter.execute():
return None
calculator = SmartCalculator()
calculator.run()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T23:33:05.823",
"Id": "477986",
"Score": "0",
"body": "Thank you very much Serge Ve for adding a description. The question looks great now :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:01:51.193",
"Id": "478024",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:20:28.200",
"Id": "478074",
"Score": "0",
"body": "@Mast, Sorry, I have not read the rules."
}
] |
[
{
"body": "<p>Just a few thoughts in case I don't have time for a more thorough review later (must sign off soon).</p>\n\n<ul>\n<li>The program crashes too easily, for example if I type <kbd>.</kbd> or <kbd>*</kbd> or <code>(3+1)</code>. But this works: <code>3+(1+4)</code></li>\n<li>Don't you think it would be a good idea to use a <strong>regular expression</strong> to filter the list of allowed characters ?</li>\n<li>To simplify you could use the <a href=\"https://docs.python.org/3/library/functions.html#eval\" rel=\"nofollow noreferrer\"><code>eval</code></a> function, provided that you understand that it has the potential to run arbitrary and malicious code. But you could simplify parsing a lot.</li>\n<li>I have the impression that the built-in <code>argparse</code> module could have been useful for the purpose of parsing the input string. Because it is very flexible, you can require multiple arguments for a parameter and also create mutually-exclusive groups, which could be interesting here for example to allow only one operator out of a fixed list.</li>\n<li>So, if you for example require one digit, followed by an operator, followed by another digit, that is very easy to express and validate with <code>argparse</code>.</li>\n<li>But your needs are slightly more complex, I have to figure out all possible cases first</li>\n<li>I am not sure I understand how variable assignment is supposed to work but consider the following:</li>\n</ul>\n\n<pre>\n a=1\n a\n 1\n b=a+1\n b\n</pre>\n\n<p>Crash:</p>\n\n<pre>\nTraceback (most recent call last):\n File \"/tmp/calc.py\", line 561, in \n calculator.run()\n File \"/tmp/calc.py\", line 556, in run\n if not self._interpreter.execute():\n File \"/tmp/calc.py\", line 428, in execute\n if not self.analysis_handler():\n File \"/tmp/calc.py\", line 446, in analysis_handler\n if not self.expression_handler():\n File \"/tmp/calc.py\", line 467, in expression_handler\n self.res = self.get_expression_result()\n File \"/tmp/calc.py\", line 500, in get_expression_result\n if self.is_digit(item):\n File \"/tmp/calc.py\", line 486, in is_digit\n if item[0] == '0':\nTypeError: 'int' object is not subscriptable\n</pre>\n\n<p>But this works:</p>\n\n<pre>\na=1\na\n1\nb=a\nb\n1\n</pre>\n\n<p>So at this point I am thinking I might classify the input in two possible cases and evaluate accordingly:</p>\n\n<ol>\n<li>variable assignments</li>\n<li>regular calculations</li>\n</ol>\n\n<p>Then it seems to me that <code>eval</code> can help you a lot. Just have to strictly define what you want to allow, and what should not be permitted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T06:03:34.147",
"Id": "478004",
"Score": "4",
"body": "`eval` is just too dangerous to be useful here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T06:56:35.853",
"Id": "478008",
"Score": "0",
"body": "Thank you so much. Corrected the self.get_expression_result method. Now this error is gone.\n\n `def get_expression_result(self):\n result_stack: list = []\n\n while self.rpn_stack:\n item = self.rpn_stack.popleft()\n try:\n result_stack.append(int(item))\n except ValueError:\n second, first = result_stack.pop(), result_stack.pop()\n result_stack.append(self.calculate_this(first, second, item))\n\n return result_stack[0]`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T02:14:23.747",
"Id": "243536",
"ParentId": "243529",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "243536",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T22:02:56.900",
"Id": "243529",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"calculator"
],
"Title": "Command line calculator utilizing OOP and RPN"
}
|
243529
|
<p>We have 2 strings, say "JACK" and "DANIELS". We create two stacks from these strings, and then loop over them comparing first elements: whichever of the 2 goes first in lexicographic order gets popped from its stack and added to a string (the second value is left alone). So it goes, until we end up with a string containing all the elements from both stacks. In this example it would be "DAJACKNIELS"</p>
<p>My solution takes advantage of the fact that <code>min</code> function, when applied to <code>deque()</code> objects, returns the one whose first element goes lexicographically first. As it happens, it works well enough for small testcases, but fails large ones, <strong>for it takes all the memory it can get and then some.</strong></p>
<p>Perhaps, something can be improved in my code, or there's a better solution altogether (like, without a <code>while</code> loop).</p>
<pre><code>def morgan(a, b):
string = ""
stack_a = deque()
stack_b = deque()
stack_a.extend(a)
stack_b.extend(b)
while True:
if len(stack_a) != 0 and len(stack_b) != 0:
if stack_a == min(stack_a, stack_b):
string += stack_a.popleft()
else:
string += stack_b.popleft()
elif len(stack_a) == 0 and len(stack_b) == 0:
break
elif len(stack_a) == 0:
string += stack_b.popleft()
elif len(stack_b) == 0:
string += stack_a.popleft()
return(string)
</code></pre>
<p>Example of a large testcase:</p>
<pre><code>string a: https://pastebin.com/raw/pebMbcA6
string b: https://pastebin.com/raw/bwNEqJcr
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T06:31:41.823",
"Id": "478005",
"Score": "1",
"body": "See [heapq.merge()](https://docs.python.org/3.7/library/heapq.html#heapq.merge) from the standard library. Look at the library [source code](https://github.com/python/cpython/tree/3.7/Lib/heapq.py) to learn how it works. ''.join(heapq.merge(a, b))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T13:10:37.363",
"Id": "478054",
"Score": "2",
"body": "@tinstaafl: I don't understand your problem. To me it seems like the code works in general. It works specifically on my machine for both test cases but not on the server of the programming challenge in case of the larger, because it runs ot of memory (or there is a limit). Therefore it needs improvement, specifically in how memory-efficient it is. This is specifically on-topic here, which is why the tag [tag:memory-optimization] exists."
}
] |
[
{
"body": "<p>There is no need to read the whole string into a <code>deque</code>. Just iterate over the strings using iterators. The only gotcha is handling the fact that either of the strings can be empty at the beginning and that one can be exhausted before the other.</p>\n\n<pre><code>def _morgan(a, b):\n a, b = iter(a), iter(b)\n try:\n x = next(a)\n except StopIteration:\n yield from b\n return\n try:\n y = next(b)\n except StopIteration:\n yield x\n yield from a\n return\n while True:\n if x <= y: # `<=` because that's what `min` does\n yield x\n try:\n x = next(a)\n except StopIteration:\n yield y\n yield from b\n return\n else:\n yield y\n try:\n y = next(b)\n except StopIteration:\n yield x\n yield from a\n return\n\n\ndef morgan(a, b):\n return \"\".join(_morgan(a, b))\n</code></pre>\n\n<p>Note that both the original strings and the resulting string still need to fit into memory for this to work. If you only need to iterate over the resulting string, use only the private function. In that case the original strings still need to fit into memory, unless you also have them as generators (e.g. by streaming the contents from the URLs):</p>\n\n<pre><code>import requests\n\ndef stream(url, chunk_size=1000):\n with requests.get(url, stream=True) as r:\n for chunk in r.iter_content(chunk_size=chunk_size, decode_unicode=True):\n yield from iter(chunk)\n\nif __name__ == \"__main__\":\n a = stream(\"https://pastebin.com/raw/pebMbcA6\")\n b = stream(\"https://pastebin.com/raw/bwNEqJcr\")\n c = _morgan(a, b)\n while (chunk := \"\".join(islice(c, 1000))):\n print(chunk, end='')\n print()\n</code></pre>\n\n<p>This works on my machine with the given strings, but so does the <code>morgan</code> function I defined above.</p>\n\n<hr>\n\n<p>Note that you need Python 3.8+ for the walrus operator <code>:=</code>. With earlier Python versions it is slightly more verbose:</p>\n\n<pre><code> if __name__ == \"__main__\":\n a = stream(\"https://pastebin.com/raw/pebMbcA6\")\n b = stream(\"https://pastebin.com/raw/bwNEqJcr\")\n c = _morgan(a, b)\n chunk = \"\".join(islice(c, 1000))\n while chunk:\n print(chunk, end='')\n chunk = \"\".join(islice(c, 1000))\n print()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:42:19.497",
"Id": "478019",
"Score": "0",
"body": "`itertools.zip_longest` would probably help with handling the shorter iterable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:44:00.873",
"Id": "478020",
"Score": "0",
"body": "@AKX: Not really, because you don't need pairs. E.g. for `\"AAA\", \"BBB\"`, the output needs to be `\"AAABBB\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:45:07.313",
"Id": "478021",
"Score": "1",
"body": "Ah yeah, true. And here I thought I had a neat 3-line version of this... :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:47:08.797",
"Id": "478022",
"Score": "2",
"body": "@AKX: Yeah, right before posting I thought of that as well, thinking that my code was overkill. But then I realized it doesn't help. At least I can't see how :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:31:18.253",
"Id": "479403",
"Score": "0",
"body": "@Graipher, @RootTwo, hey guys, so I've finally found the time to test your code, and there's good news and bad news: good news it's fast, bad news it produces wrong result. This goes for both your versions - they return the same stuff (long strings; compared them with `==`), but it only sometimes coincides with HR's expected results for given testcases. Should I post this as a separate question here? CodeReview doesn't really seem to fit the issue, but I'm not sure. What say you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:08:13.177",
"Id": "479407",
"Score": "0",
"body": "@DenisShvetsov Do you have a (short) testcase that fails?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T08:57:32.803",
"Id": "479435",
"Score": "0",
"body": "@Graipher, nope, they are all pretty huge"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:36:05.803",
"Id": "243554",
"ParentId": "243530",
"Score": "2"
}
},
{
"body": "<h3>next(iterable, [ default ])</h3>\n\n<p>I find too many <code>try-except</code> block can be distracting. <a href=\"https://docs.python.org/3.7/library/functions.html#next\" rel=\"nofollow noreferrer\"><code>next()</code></a> takes an optional second argument--a default value to return when the iteration finishes. Here is @Graipher's <code>_morgan()</code> function using the 2-argument form of <code>next()</code> instead of <code>try-except</code>.</p>\n\n<pre><code>def _morgan(a, b):\n a = iter(a)\n x = next(a, None)\n\n b = iter(b)\n y = next(b, None)\n\n while x and y:\n if x <= y:\n yield x\n x = next(a, None)\n else:\n yield y\n y = next(b, None)\n\n if x:\n yield x\n yield from a\n else:\n yield y\n yield from b\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T20:33:58.510",
"Id": "478207",
"Score": "0",
"body": "very interesting concept (the `next()`). Thanks, I don't know how else I would've learned about it"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T06:40:37.833",
"Id": "243588",
"ParentId": "243530",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243554",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T22:58:54.163",
"Id": "243530",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"memory-optimization"
],
"Title": "Using deque for composing a string from 2 alternating stacks"
}
|
243530
|
<p>I have written a pretty simple hash table in C. It uses a prime modulus, linear probing, open addressing, and robin hood hashing.
The program can also be found <a href="https://github.com/Levalicious/ftable/blob/fb968268ed0cc9225f208f7e6d17584f1efa6d90/ftable.h" rel="noreferrer">on GitHub</a>.</p>
<p>For clarification, <code>uin</code> is a typedef that uses <code>uint32_t</code> or <code>uint64_t</code> depending on whether the system is x86 or x86_64.</p>
<p>I'd now like to optimize the performance as much as possible, but I'm unsure of how to do so.
I've considered using fastrange or fibonacci hashing instead of a prime modulus and consistent hashing to speed up the resizes. However, I'd like to streamline it beforehand. My apologies for the gotos, I know they are evil (but I kinda like them I'm sorry).
I'd appreciate any feedback.</p>
<pre><code>#ifndef FTABLE_FTABLE_H
#define FTABLE_FTABLE_H
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LOAD 0.5
/* Set uin as uint32_t or uint64_t depending on system */
#ifdef __x86
typedef uint32_t uin;
/* Table of prime number sizes, each approx double the prev, that fits
* into a uint32_t */
const uin tableSizes[] = {
5, 11, 23, 47, 97, 197, 397, 797, 1597,
3203, 6421, 12853, 25717, 51437, 102877,
205759, 411527, 823117, 1646237, 3292489,
6584983, 13169977, 26339969, 52679969,
105359939, 210719881, 421439783, 842879579,
1685759167, 3371518343 };
#elif __x86_64
typedef uint64_t uin;
/* Table of prime number sizes, each approx double the prev, that fits
* into a uint64_t */
const uin tableSizes[] = {
5, 11, 23, 47, 97, 197, 397, 797, 1597,
3203, 6421, 12853, 25717, 51437, 102877,
205759, 411527, 823117, 1646237, 3292489,
6584983, 13169977, 26339969, 52679969,
105359939, 210719881, 421439783, 842879579,
1685759167, 3371518343, 6743036717, 13486073473,
26972146961, 53944293929, 107888587883,
215777175787, 431554351609, 863108703229,
1726217406467, 3452434812973, 6904869625999,
13809739252051, 27619478504183, 55238957008387,
110477914016779, 220955828033581, 441911656067171,
883823312134381, 1767646624268779, 3535293248537579,
7070586497075177, 14141172994150357,
28282345988300791, 56564691976601587,
113129383953203213, 226258767906406483,
452517535812813007, 905035071625626043,
1810070143251252131, 3620140286502504283,
7240280573005008577, 14480561146010017169,
18446744073709551557};
#endif
/* Table of bitmasks to use */
const uin mask[] = {
0x7, 0xF,
0x1F, 0x3F, 0x7F, 0xFF,
0x1FF, 0x3FF, 0x7FF, 0xFFF,
0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF,
0x1FFFF, 0x3FFFF, 0x7FFFF, 0xFFFFF,
0x1FFFFF, 0x3FFFFF, 0x7FFFFF, 0xFFFFFF,
0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF,
0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,
0x1FFFFFFFF, 0x3FFFFFFFF, 0x7FFFFFFFF, 0xFFFFFFFFF,
0x1FFFFFFFFF, 0x3FFFFFFFFF, 0x7FFFFFFFFF, 0xFFFFFFFFFF,
0x1FFFFFFFFFF, 0x3FFFFFFFFFF, 0x7FFFFFFFFFF, 0xFFFFFFFFFFF,
0x1FFFFFFFFFFF, 0x3FFFFFFFFFFF, 0x7FFFFFFFFFFF, 0xFFFFFFFFFFFF,
0x1FFFFFFFFFFFF, 0x3FFFFFFFFFFFF, 0x7FFFFFFFFFFFF, 0xFFFFFFFFFFFFF,
0x1FFFFFFFFFFFFF, 0x3FFFFFFFFFFFFF, 0x7FFFFFFFFFFFFF, 0xFFFFFFFFFFFFFF,
0x1FFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFF,
0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
};
/* Linear probing max distance */
#define MAX_PROBES 10
/* Bucket States: Empty, Occupied, Tombstone */
#define EMPTY 0
#define OCCPD 1
#define TMBSTN 2
typedef struct sftbl_bckt ftbucket;
/* Hash table bucket: Key, value, distance from 'ideal' position,
* and data field indicating the bucket state */
struct sftbl_bckt {
uin key;
uin val;
uint8_t dist;
uint8_t data;
};
typedef struct sftbl ftable;
struct sftbl {
ftbucket* buckets;
uin size;
uin count;
uint8_t lvl;
};
ftable* alloc_ftable() {
ftable* out = malloc(sizeof(ftable));
memset(out, 0, sizeof(ftable));
return out;
}
ftable* insert(ftable* ft, uin key, uin val);
void free_table(ftable* ft);
ftable* resize(ftable* ft) {
ftable* nt = malloc(sizeof(ftable));
/* Increase the index in the prime table used for the size */
nt->lvl = ft->lvl + 1;
nt->size = tableSizes[nt->lvl];;
nt->count = 0;
nt->buckets = malloc(sizeof(ftbucket) * nt->size);
memset(nt->buckets, 0, sizeof(ftbucket) * nt->size);
/* Iterate through every valid entry and insert into new table */
for (uin i = 0; i < ft->size; i++) {
if (ft->buckets[i].data == OCCPD) {
nt = insert(nt, ft->buckets[i].key, ft->buckets[i].val);
}
}
/* Free old table and return new one */
free_table(ft);
return nt;
}
ftable* insert(ftable* ft, uin key, uin val) {
if (((float) ft->count + 1) / ((float) ft->size) > MAX_LOAD) {
ft = resize(ft);
}
binsert:;
/* Prime modulus */
uin index = key % ft->size;
uint8_t dist = 0;
while (1) {
/* If more than MAX_PROBES away from ideal location
* resize table and attempt to insert again (goto binsert) */
if (dist > MAX_PROBES) {
ft = resize(ft);
goto binsert;
}
// uin nind = (index + dist) % ft->size;
uin nind = (index + dist) & mask[ft->lvl];
/**
* Above line can be replaced with
* uin nind = (index + dist) & mask[ft->lvl];
* for worse memory usage but faster perf
**/
if (ft->buckets[nind].data == OCCPD) {
if (ft->buckets[nind].dist < dist) {
/* Robin hood hashing: If a 'richer' node is found,
* steal from it: swap */
uin tkey = ft->buckets[nind].key;
uin tval = ft->buckets[nind].val;
uint8_t tdist = ft->buckets[nind].dist;
ft->buckets[nind].key = key;
ft->buckets[nind].val = val;
ft->buckets[nind].dist = dist;
key = tkey;
val = tval;
dist = tdist;
}
}
if (ft->buckets[nind].data == EMPTY || ft->buckets[index + dist].data == TMBSTN) {
/* Occupy any empty or tombstone buckets */
ft->buckets[nind].data = OCCPD;
ft->buckets[nind].key = key;
ft->buckets[nind].val = val;
ft->buckets[nind].dist = dist;
ft->count++;
return ft;
}
dist++;
}
}
void delete(ftable* ft, uin key) {
uin index = key % ft->size;
uint8_t dist = 0;
while (1) {
if (dist > MAX_PROBES) {
/* Object not present in table. Return. */
return;
}
// uin nind = (index + dist) % ft->size;
uin nind = (index + dist) & mask[ft->lvl];
/**
* Above line can be replaced with
* uin nind = (index + dist) & mask[ft->lvl];
* for worse memory usage but faster perf
**/
if (ft->buckets[nind].data == OCCPD) {
if (ft->buckets[nind].key == key) {
/* Set bucket data to tombstone and
* clear key and value */
ft->buckets[nind].data = TMBSTN;
ft->buckets[nind].key = 0;
ft->buckets[nind].val = 0;
ft->count--;
return;
}
}
dist++;
}
}
uin get(ftable* ft, uin key) {
uin index = key % ft->size;
uint8_t dist = 0;
while (1) {
if (dist > MAX_PROBES) {
/* Object not present in table. Return. */
perror("Went over max probes!");
return -1;
}
// uin nind = (index + dist) % ft->size;
uin nind = (index + dist) & mask[ft->lvl];
/**
* Above line can be replaced with
* uin nind = (index + dist) & mask[ft->lvl];
* for worse memory usage but faster perf
**/
if (ft->buckets[nind].data == OCCPD) {
if (ft->buckets[nind].key == key) {
return ft->buckets[nind].val;
}
} else if (ft->buckets[nind].data == EMPTY) {
/* If empty, return early. Further elements
* would have been bridged by a tombstone or a
* occupied bucket. */
return -1;
}
dist++;
}
}
void free_table(ftable* ft) {
free(ft->buckets);
free(ft);
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T02:34:59.333",
"Id": "477993",
"Score": "1",
"body": "I suggest you to better write long names instead of short and cryptic ones (I used to do that so under my first year programing). In the future (perhaps) it would be difficult for you to understand those small names and using `typedef` does not help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T02:47:42.567",
"Id": "477994",
"Score": "0",
"body": "@MiguelAvila I'll keep that in mind for the future! For this piece of code, if the name isn't self explanatory, its probably something I just stuck a letter or 2 onto the front of. I'll add improving the variable names to my to do list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T03:09:38.563",
"Id": "477996",
"Score": "0",
"body": "In addition: I've since changed the implementation to use a bitmask inside of the while loops instead of the modulus. It's improved performance some and seems to not be affecting the average load of the table or memory usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T03:23:50.447",
"Id": "477999",
"Score": "1",
"body": "Do you have any unit tests that exercise the code, that would be good as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T03:55:34.940",
"Id": "478001",
"Score": "1",
"body": "In contrast to some interpreters in the dawn of HLLs in *home computing*, programs don't get any faster by omitting [comments](https://www.doxygen.nl/index.html), let alone algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T07:15:39.347",
"Id": "478011",
"Score": "0",
"body": "@greybeard I've edited to include some comments. I hope they help clarify the code somewhat. Thanks for pointing that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T12:40:35.330",
"Id": "478044",
"Score": "0",
"body": "Note to anyone on VTC, I have removed my VTC, there is now enough code to review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T13:44:46.423",
"Id": "478067",
"Score": "0",
"body": "For context, I was worried with the performance on this table and I couldn't figure out why it was as slow as it seemed to be. Turns out it was because I was printing microseconds instead of milliseconds for the benchmark and making myself think it was 1000x slower. I figured that out about 10 minutes ago. However I'm sure there's still a lot I could've written more efficiently, so I'm still interested in improving it."
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>It makes the code somewhat longer for a code review, but it's often very useful to separate the interface from the implementation. In C, this is usually done by putting the interface into separate <code>.h</code> files and the corresponding implementation into <code>.c</code> files. It helps users (or reviewers) of the code see and understand the interface and hides implementation details. The other important reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.c</code> file. In other words, split your existing <code>.h</code> file into a <code>.h</code> file and a <code>.c</code> file.</p>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>perror</code> but doesn't <code>#include <stdio.h></code>. Also, carefully consider which <code>#include</code>s are part of the interface (and belong in the <code>.h</code> file) and which are part of the implementation per the above advice.</p>\n\n<h2>Don't print from a library</h2>\n\n<p>Because you're creating something like a library that might be called by many different kinds of programs, the code should not print anything or assume that there even is anything on which to print. For that reason, I would strongly advise removing the <code>perror</code> line.</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used. Here's code I wrote to try out your functions:</p>\n\n<pre><code>#include \"ftable.h\"\n#include <assert.h>\n\nint main() {\n ftable *hash = alloc_ftable();\n for (unsigned i = 0; i < 100; ++i) {\n hash = insert(hash, i, i*i);\n }\n for (unsigned i = 0; i < 100; ++i) {\n assert(i*i == get(hash, i));\n }\n // delete odd keys\n for (unsigned i = 1; i < 100; i += 2) {\n delete(hash, i);\n }\n // verify that it's still correct\n for (unsigned i = 0; i < 100; ++i) {\n if (i & 1) {\n assert((uin)-1 == get(hash, i));\n } else {\n assert(i*i == get(hash, i));\n }\n }\n // resize hash table\n hash = resize(hash);\n // verify that it's still correct\n for (unsigned i = 0; i < 100; ++i) {\n if (i & 1) {\n assert((uin)-1 == get(hash, i));\n } else {\n assert(i*i == get(hash, i));\n }\n }\n free_table(hash);\n}\n</code></pre>\n\n<h2>Measure the performance before and after any changes</h2>\n\n<p>As with the test function above, you should write many different test functions for your hash and measure their performance. It's only by actually measuring before and after any change that you will be able to tell for certain whether you are improving or worsening the performance.</p>\n\n<h2>Consider using better naming</h2>\n\n<p>Although some of the names are quite brief, I didn't have much difficulty in understanding them, so I think the current names are adequate. However, although you as the programmer are interested in the hash table mechanism, from another programmer's point of view trying to <em>use</em> this code, it would probably be better to call it a <code>map</code> or <code>hashmap</code> or even <code>associative_array</code> because that's essentially what the code is for, even if the details happen to feature a hashing algorithm internally. Also, it seems to me that <code>resize</code> should probably not be used other than internally. For that reason, I'd suggest that it should be <code>static</code> and solely within <code>ftable.c</code>. Also <code>data</code> should clearly be <code>state</code> or <code>bucket_state</code>.</p>\n\n<h2>Combine <code>typedef</code> with <code>struct</code> declaration</h2>\n\n<p>It's purely a stylistic preference, but if you're going to use <code>typedef</code>s for your <code>struct</code>s, you should know that it's common practice to combine them for brevity and clarity:</p>\n\n<pre><code>typedef struct sftbl {\n ftbucket* buckets;\n unsigned size;\n unsigned count;\n uint8_t lvl;\n} ftable;\n</code></pre>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>In the <code>get</code> routine, the underlying structure is not modified and so that parameter should be declared <code>const</code> to signal that fact:</p>\n\n<pre><code>uin get(const ftable* ft, uin key);\n</code></pre>\n\n<h2>Check the return value of <code>malloc</code></h2>\n\n<p>If the system is running out of memory, <code>malloc</code> will return <code>NULL</code>. Code <strong>must</strong> check the return value to make sure it is not <code>NULL</code> before dereferencing the variable or the program will crash.</p>\n\n<h2>Consider <code>unsigned</code> instead of a custom type</h2>\n\n<p>The code currently won't compile for an ARM processor since neither <code>__x86</code> nor <code>__x86_64</code> are defined for that processor type. That's not really a necessary restriction, so I'd recommend instead simply using <code>unsigned</code> and making the <code>typedef</code> like this:</p>\n\n<pre><code>#include <limits.h>\n\n#if UINT_MAX == 4294967295u\n // 32-bit version\n#elif UINT_MAX == 18446744073709551615u\n // 64-bit version\n#else \n #error \"unsigned type does not appear to be 32- or 64-bit value.\"\n#endif\n</code></pre>\n\n<h2>Understand constant values</h2>\n\n<p>In C, when you write a value like <code>14480561146010017169</code> or <code>0x7FFFFFFFFFFFFFF</code> it is interpreted by the preprocessor as a signed value. If you want unsigned values, you must say so, so these constants should be written as <code>14480561146010017169u</code> or <code>0x7FFFFFFFFFFFFFFu</code> with the trailing <code>u</code> signifying unsigned. Also, your <code>mask</code> values should be sized appropriately as per the previous advice.</p>\n\n<h2>Goto is <strong>still</strong> considered dangerous</h2>\n\n<p>The <code>goto</code> in this code makes a difficult-to-understand control flow even more difficult to understand. That is not a good idea. So first let's look at the dubious <code>while(1)</code> loop. Does it <em>really</em> never exit? No, that's misleading. If we study the code, we see it exits when it's able to place the data in a bucket. So instead of <code>while(1)</code>, I would write this:</p>\n\n<pre><code>unsigned nind = index & mask[ft->lvl];\nfor (dist = 0;\n ft->buckets[nind].data != EMPTY && ft->buckets[index + dist].data != TMBSTN;\n ++dist) \n{ \n // the loop\n}\n\n/* Write the data in this bucket */\nft->buckets[nind].data = OCCPD;\nft->buckets[nind].key = key;\nft->buckets[nind].val = val;\nft->buckets[nind].dist = dist;\nft->count++;\nreturn ft;\n</code></pre>\n\n<p>Now we can eliminate the <code>goto</code> by rewriting the clause within the loop:</p>\n\n<pre><code>if (dist > MAX_PROBES) {\n ft = resize(ft);\n index = key % ft->size;\n nind = index & mask[ft->lvl];\n dist = 0;\n continue;\n}\n</code></pre>\n\n<p>A similar transformation can be applied elsewhere as with <code>get</code>:</p>\n\n<pre><code>unsigned get(const ftable* ft, unsigned key) {\n unsigned index = key % ft->size;\n unsigned retval = -1;\n for (uint8_t dist = 0; dist <= MAX_PROBES; ++dist) {\n unsigned nind = (index + dist) & mask[ft->lvl];\n if (ft->buckets[nind].data == OCCPD && ft->buckets[nind].key == key) {\n retval = ft->buckets[nind].val;\n break;\n } else if (ft->buckets[nind].data == EMPTY) {\n break;\n }\n }\n return retval;\n}\n</code></pre>\n\n<h2>Use library calls efficiently</h2>\n\n<p>Instead of these two lines:</p>\n\n<pre><code>nt->buckets = malloc(sizeof(ftbucket) * nt->size);\nmemset(nt->buckets, 0, sizeof(ftbucket) * nt->size);\n</code></pre>\n\n<p>I'd write this:</p>\n\n<pre><code>nt->buckets = calloc(nt->size, sizeof(ftbucket));\n</code></pre>\n\n<h2>Avoid C++ keywords</h2>\n\n<p>There may come a time that you or someone else wants to incorporate this C code into a C++ project. Unfortunately, the <code>delete</code> function sits atop the C++ reserved word <code>delete</code>. Rename it to <code>remove</code> to avoid such clashes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:06:24.403",
"Id": "478072",
"Score": "1",
"body": "If I could up vote twice, I would. You got everything I wanted to write about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:10:06.957",
"Id": "478073",
"Score": "0",
"body": "@pacmaninbw: you did good work too, guiding the OP toward creating a reviewable question. Kudos!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T17:01:23.850",
"Id": "478084",
"Score": "1",
"body": "Thank you both for your help! I appreciate the advice and will get to work on fixing up my code!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T13:54:33.973",
"Id": "243559",
"ParentId": "243534",
"Score": "4"
}
},
{
"body": "<p><strong>Use valid constants</strong></p>\n\n<p><code>14480561146010017169, 18446744073709551557</code> are typically outside the <code>long long</code> range. Append a <code>u</code>.</p>\n\n<p><strong>Simplify allocation sizing</strong></p>\n\n<p>Insptead of <code>p = some_alloc(sizeof(matching pointer type) * n)</code>, use <code>p = some_alloc(sizeof *p * n)</code>. It is easier to code right, review and maintain.</p>\n\n<pre><code>// nt->buckets = malloc(sizeof(ftbucket) * nt->size);\nnt->buckets = malloc(sizeof *(nt->buckets) * nt->size);\n</code></pre>\n\n<p><strong>Use <code>size_t</code> for indexing</strong></p>\n\n<p><code>uin</code> is not the best type for array index, it may be too narrow or wide for array indexing and sizing. Use <code>size_t</code>.</p>\n\n<p>I'd reccomend <code>unsigned long long</code> or <code>uintmax_t</code> for the <em>key</em> type though.</p>\n\n<p><strong>Avoid FP math</strong> for an integer problem.</p>\n\n<pre><code>//if (((float) ft->count + 1) / ((float) ft->size) > MAX_LOAD) {\n// ft = resize(ft);\n//}\n\n#define MAX_LOAD_N 1\n#define MAX_LOAD_D 2\n// if ((ft->count + 1) / ft->size > MAX_LOAD_N / MAX_LOAD_D) {\nif ((ft->count+1) / MAX_LOAD_N > ft->size / MAX_LOAD_D) {\n ft = resize(ft);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T17:15:58.617",
"Id": "243568",
"ParentId": "243534",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243559",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T01:44:45.993",
"Id": "243534",
"Score": "5",
"Tags": [
"performance",
"c",
"hash-map"
],
"Title": "C Hash table implementation"
}
|
243534
|
<p>I have a program that lists and downloads a year of history of two stock tickers (AMZN and GOOG). I download these to a SQL database, <code>C:\Databases\hist_prices.db</code>, inside a table called <code>hist_prices_tickers</code>.</p>
<p>How can I organize my code for a more Pythonic approach? </p>
<p>I intend to use this SQL database for a machine learning project later on. Is this method of calling the database the best way possible?</p>
<pre><code>import yfinance as yf
import pandas as pd
import sqlite3, shutil, glob, os
from pathlib import Path
NewFolderPath = r"C:\Databases\\"
isFile = os.path.exists(NewFolderPath)
if isFile is False:
Path(NewFolderPath).mkdir(parents=True, exist_ok=True)
df = pd.DataFrame()
df2 = pd.DataFrame()
tickers = ["AMZN","GOOG"]
#SQL Connect
conn = sqlite3.connect(NewFolderPath+'hist_prices.db')
c = conn.cursor()
dest = sqlite3.connect(':memory:')
conn.backup(dest)
conn.commit()
for ticker in tickers:
tkr = yf.Ticker(ticker)
hist = tkr.history(period="1y")
df2 = df2.append(hist)
df2['Ticker'] = ticker
df = df.append(df2.reset_index())
df.fillna(0, inplace=True)
df = df.applymap(str)
df = df.apply(lambda x: x.str.replace('.', ','))
df['Date'] = df['Date'].apply(pd.to_datetime)
df.to_sql('hist_prices_tickers', conn, index=False, if_exists='append')
df = pd.read_sql_query("SELECT * from hist_prices_tickers", conn)
df.drop_duplicates(subset=None, keep="last", inplace=True)
df.to_sql('hist_prices_tickers', conn, if_exists='replace', index=False)
print(df)
conn.close()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T02:01:44.947",
"Id": "243535",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Stock price history SQL database with Python, Pandas and yfinance"
}
|
243535
|
<p>I'm learning JS and Canvas. A friend of mine gave me the task to create a <a href="https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjrpJ3nj_HpAhUSbq0KHbVQAxgQFjAKegQIARAB&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FBattle_City&usg=AOvVaw2YXuRsd1I0DiHW3qzExJCn" rel="nofollow noreferrer">Battle City</a> replica. I've already managed to make the map and the player to move. Nothing fancy just some squares with a color, I tried to replicate the first map:</p>
<p><a href="https://i.stack.imgur.com/d6rZe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d6rZe.png" alt="enter image description here" /></a></p>
<p>My code currently creates the map using 26 x 26 little <code>square</code>s (I chosen that amount because there are 13 "cols" in the image above, but each brick col is destroyed partially by a certain amount per shot (if IRC that was about 2-4 shots in the original game), in my case that's 2 bullets, so 13x2 = 26), my player uses 2 x 2 which is not ideal, because it requires to check 2 blocks for every direction, if I wanted to use a bigger grid, the size of the player grid might increase as well, making the code unmaintainable, how could I improve this code in order to have my player a single entity instead of a 4-block entity?</p>
<p>I think my intersection logic is kind of rudimentary, is there a way to improve this as well?</p>
<p>And I also struggled a little bit with the map drawing, as it's drawn vertically so I had to change the <code>i</code> and <code>j</code> variables so that the map wouldn't be rotated 90 degrees, I'm also interested in other options to do this and not having to paint the map and player every time I move the player in one direction.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const mapGrid = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
[2, 2, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 2, 2],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
const canvas = document.getElementById('map');
const ctx = canvas.getContext('2d');
const width = 24;
const height = 24;
const Directions = {
up: 1,
left: 2,
right: 3,
down: 4,
};
Object.freeze(Directions);
const playerCoords = [
mapGrid.length - 2, 8,
];
const goalCoords = [6, 12];
const toRelativeCoord = (fromCoord) => fromCoord * width;
const drawMap = () => {
ctx.beginPath();
for (let i = 0; i < mapGrid.length; i += 1) {
for (let j = 0; j < mapGrid[i].length; j += 1) {
switch (mapGrid[i][j]) {
case 1: //Bricks
ctx.fillStyle = '#993333';
break;
case 2: //Iron-Bricks
ctx.fillStyle = '#C0C0C0';
break;
case 3: //Base
ctx.fillStyle = '#CCCC99';
break;
case 4: //Player
ctx.fillStyle = '#FFFF00';
break;
default: //Road
ctx.fillStyle = '#000000';
break;
}
ctx.fillRect(j * width, i * height, width, height);
}
}
};
const drawPlayer = () => {
ctx.beginPath();
ctx.fillStyle = '#FFFF00';
ctx.fillRect(toRelativeCoord(playerCoords[1]),
toRelativeCoord(playerCoords[0]), width * 2, height * 2);
};
const repaint = () => {
drawMap();
drawPlayer();
if (hasReachedGoal()) {
alert('Game Over')
}
};
const isMapEdge = (x, y, direction) => {
switch (direction) {
case Directions.up:
return x - 1 < 0;
case Directions.left:
return y - 1 < 0;
case Directions.right:
return y + 2 === mapGrid[0].length;
default: // back
return x + 2 === mapGrid.length;
}
};
const upIsClear = (x, y) => {
if (isMapEdge(x, y, Directions.up)) {
return false;
}
return mapGrid[x - 1][y] === 0 && mapGrid[x - 1][y + 1] === 0;
};
const leftIsClear = (x, y) => {
if (isMapEdge(x, y, Directions.left)) {
return false;
}
return mapGrid[x][y - 1] === 0 && mapGrid[x + 1][y - 1] === 0;
};
const rightIsClear = (x, y) => {
if (isMapEdge(x, y, Directions.right)) {
return false;
}
return mapGrid[x][y + 2] === 0 && mapGrid[x + 1][y + 2] === 0;
};
const downIsClear = (x, y) => {
if (isMapEdge(x, y, Directions.down)) {
return false;
}
return mapGrid[x + 2][y] === 0 && mapGrid[x + 2][y + 1] === 0;
};
const moveUp = () => {
if (upIsClear(playerCoords[0], playerCoords[1])) {
playerCoords[0] -= 1;
repaint();
}
};
const moveLeft = () => {
if (leftIsClear(playerCoords[0], playerCoords[1])) {
playerCoords[1] -= 1;
repaint();
}
};
const moveRight = () => {
if (rightIsClear(playerCoords[0], playerCoords[1])) {
playerCoords[1] += 1;
repaint();
}
};
const moveDown = () => {
if (downIsClear(playerCoords[0], playerCoords[1])) {
playerCoords[0] += 1;
repaint();
}
};
const listenToEvents = () => {
document.addEventListener('keypress', (event) => {
if (event.key === 'W' || event.key === 'w') {
moveUp();
} else if (event.key === 'A' || event.key === 'a') {
moveLeft();
} else if (event.key === 'S' || event.key === 's') {
moveDown();
} else if (event.key === 'D' || event.key === 'd') {
moveRight();
}
});
};
const intersects = (coord1, coord2) => {
return coord1 == coord2 || coord1 + 1 == coord2 || coord1 - 1 == coord2;
}
const hasReachedGoal = () => {
if ((intersects(playerCoords[0], goalCoords[0])) && intersects(playerCoords[1], goalCoords[1]) ||
(intersects(playerCoords[0], goalCoords[0])) && intersects(playerCoords[1] + 1, goalCoords[1]) ||
(intersects(playerCoords[0] + 1, goalCoords[0])) && intersects(playerCoords[1], goalCoords[1]) ||
(intersects(playerCoords[0] + 1, goalCoords[0])) && intersects(playerCoords[1] + 1, goalCoords[1])) {
alert('Hey!')
}
return false;
}
/**
* DEVELOPER NOTE
* x = rows
* y = columns
*
* 0, 0 = top left corner
*/
const initialize = () => {
drawMap();
drawPlayer();
listenToEvents();
};
initialize();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Tank</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="map" width="624" height="624"></canvas>
</body>
<script type="text/javascript" src="main.js"></script>
</html></code></pre>
</div>
</div>
</p>
<hr />
<h1>Edit</h1>
<p>I did some research on how to use classes, and I think the code is now more readable and more structured. I believe this is an improvement, but anyway I'd appreciate if someone could judge it with an expert and critic eye so that I can improve this code.</p>
<p>I'm still interested in how to paint the map horizontally instead of vertically, as currently I have to switch <code>X</code> and <code>Y</code> coords for some calculations.</p>
<p><strong>index.html</strong></p>
<pre><code><html>
<head>
<title>Tank</title>
</head>
<body>
<canvas id="map" width="624" height="624"></canvas>
</body>
<script type="text/javascript" src="cell.js"></script>
<script type="text/javascript" src="goal.js"></script>
<script type="text/javascript" src="tank.js"></script>
<script type="text/javascript" src="game.js"></script>
</html>
</code></pre>
<p><strong>cell.js</strong></p>
<pre><code>const CellTypes = {
road: 0,
bricks: 1,
ironBricks: 2,
base: 3,
player: 4,
goal: 5
}
class Cell {
static cellWidth = 24;
static cellHeight = 24;
constructor(x, y, color, type) {
this.color = color;
this.type = type;
this.width = Cell.cellWidth;
this.height = Cell.cellHeight;
this.x = x * this.width;
this.y = y * this.height;
}
}
</code></pre>
<p><strong>goal.js</strong></p>
<pre><code>class Goal extends Cell {
constructor(x, y, color) {
super(x, y, color, CellTypes.goal);
this.width = this.width * 2;
this.height = this.height * 2;
}
}
</code></pre>
<p><strong>tank.js</strong></p>
<pre><code>const Directions = {
up: 1,
left: 2,
right: 3,
down: 4,
};
class Tank extends Cell {
constructor(x, y, color) {
super(x, y, color, CellTypes.player)
this.direction = Directions.up;
this.speed = 12;
this.width = this.width * 2;
this.height = this.height * 2;
}
moveUp() {
this.y -= this.speed;
}
moveDown() {
this.y += this.speed;
}
moveLeft() {
this.x -= this.speed;
}
moveRight() {
this.x += this.speed;
}
}
</code></pre>
<p><strong>game.js</strong></p>
<pre><code>let maze = {
map: [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
[2, 2, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 2, 2],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
],
goals: {
goalColor: '#34EB9E',
coords: [
[12, 4], [0, 0]
]
}
}
let cells = new Array(maze.map.length);
let goals = new Array(maze.goals.coords.length);
//Player coords
let player = {
x: 8,
y: 24
}
const canvas = document.getElementById('map');
const ctx = canvas.getContext('2d');
let tank = new Tank(player.x, player.y, '#FFFF00');;
const initialize = () => {
configureMaze();
repaint();
listenToEvents();
}
//Sets the data as cells objects
const configureMaze = () => {
for(let i = 0; i < maze.map.length; i++) {
cells[i] = new Array(maze.map[i].length);
for(let j = 0; j < maze.map[i].length; j++) {
switch(maze.map[i][j]) {
case 1:
cells[i][j] = new Cell(j, i, '#993333', CellTypes.bricks);
break;
case 2:
cells[i][j] = new Cell(j, i, '#C0C0C0', CellTypes.ironBricks);
break;
case 3:
cells[i][j] = new Cell(j, i, '#CCCC99', CellTypes.base);
break;
default:
cells[i][j] = new Cell(j, i, '#000000', CellTypes.road);
break;
}
}
}
}
//Draws the maze based on the configuration
const drawMaze = () => {
ctx.beginPath();
cells.forEach(cellsArr => {
cellsArr.forEach(cell => {
ctx.fillStyle = cell.color;
ctx.fillRect(cell.x, cell.y, cell.width, cell.height)
})
})
}
//Goals are where some powerups will be
const drawGoals = () => {
let i = 0;
maze.goals.coords.forEach(coord => {
goals[i] = new Goal(coord[0], coord[1], '#34EB9E');
ctx.beginPath();
ctx.fillStyle = '#34EB9E';
ctx.fillRect(goals[i].x, goals[i].y, goals[i].width, goals[i].height);
i++;
})
}
//Draws the player's tank
const drawPlayerTank = () => {
ctx.beginPath();
ctx.fillStyle = tank.color;
ctx.fillRect(tank.x, tank.y, tank.width, tank.height);
}
//Repaints the UI
const repaint = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawMaze();
drawGoals();
drawPlayerTank();
}
//Checks if the tank is on the canvas limit
const isMapLimit = (direction) => {
switch (direction) {
case Directions.up:
return tank.y - 1 < 0;
case Directions.down:
return tank.y + 1 >= toCanvasCoord(maze.map.length - 2, Cell.cellWidth);
case Directions.left:
return tank.x - 1 < 0;
case Directions.right:
return tank.x + 1 >= toCanvasCoord(maze.map[0].length - 2, Cell.cellHeight);
}
}
//Transforms map coords to canvas coords
const toCanvasCoord = (coord, toValue) => {
return coord * toValue;
}
//Transforms canvas coords to map coords
const toMapCoord = (coord, toValue) => {
return Math.floor(coord / toValue);
}
//Checks for intersection of coords
const intersects = (x1, y1, x2, y2, width, height) => {
return x1 + width > x2 && y1 + height > y2 && x1 < x2 + width && y1 < y2 + height;
}
//Checks if we're standing in any of the goals zones
const isGoal = () => {
for (let i = 0; i < goals.length; i++) {
if (intersects(tank.x, tank.y, goals[i].x, goals[i].y, goals[i].width, goals[i].height)) {
return true;
}
}
return false;
}
//Checks if the cell that we're trying to move is a road cell
const isRoadCell = (direction) => {
let xCoord1; //xCoord for the top left corner
let yCoord1; //yCoord for the top left corner
let xCoord2; //xCoord for the tank's width
let yCoord2; //xCoord for the tank's height
switch (direction) {
case Directions.up:
xCoord1 = toMapCoord(tank.x, Cell.cellWidth);
yCoord1 = toMapCoord(tank.y - tank.speed, Cell.cellHeight);
xCoord2 = toMapCoord(tank.x + tank.width - 1, Cell.cellWidth);
yCoord2 = toMapCoord(tank.y - tank.speed, Cell.cellHeight);
break;
case Directions.down:
xCoord1 = toMapCoord(tank.x, Cell.cellWidth);
yCoord1 = toMapCoord(tank.y + tank.height, Cell.cellHeight);
xCoord2 = toMapCoord(tank.x + tank.width - 1, Cell.cellWidth);
yCoord2 = toMapCoord(tank.y + tank.height, Cell.cellHeight);
break;
case Directions.left:
xCoord1 = toMapCoord(tank.x - tank.speed, Cell.cellWidth);
yCoord1 = toMapCoord(tank.y, Cell.cellHeight);
xCoord2 = toMapCoord(tank.x - tank.speed, Cell.cellWidth);
yCoord2 = toMapCoord(tank.y + tank.height - 1, Cell.cellHeight);
break;
case Directions.right:
xCoord1 = toMapCoord(tank.x + tank.width, Cell.cellWidth);
yCoord1 = toMapCoord(tank.y, Cell.cellHeight);
xCoord2 = toMapCoord(tank.x + tank.width, Cell.cellWidth);
yCoord2 = toMapCoord(tank.y + tank.height - 1, Cell.cellHeight);
break;
}
if (maze.map[yCoord1][xCoord1] === CellTypes.road && maze.map[yCoord2][xCoord2] === CellTypes.road) {
return true;
}
return false;
}
//Listens to WASD key presses
const listenToEvents = () => {
document.addEventListener('keypress', (event) => {
if (event.key === 'W' || event.key === 'w') {
tank.direction = Directions.up;
if (!isMapLimit(tank.direction) && isRoadCell(tank.direction)) {
tank.moveUp();
repaint();
}
} else if (event.key === 'A' || event.key === 'a') {
tank.direction = Directions.left;
if (!isMapLimit(tank.direction) && isRoadCell(tank.direction)) {
tank.moveLeft();
repaint();
}
} else if (event.key === 'S' || event.key === 's') {
tank.direction = Directions.down;
if (!isMapLimit(tank.direction) && isRoadCell(tank.direction)) {
tank.moveDown();
repaint();
}
} else if (event.key === 'D' || event.key === 'd') {
tank.direction = Directions.right;
if (!isMapLimit(tank.direction) && isRoadCell(tank.direction)) {
tank.moveRight();
repaint();
}
}
if (isGoal()) {
alert('GOAL!')
}
});
}
initialize();
</code></pre>
|
[] |
[
{
"body": "<h2>Intersection logic</h2>\n<p>For the intersection logic, maybe it would be appropriate to make a method on the cell class that would determine if another cell (e.g. tank) overlaps with it. Refer to <a href=\"https://codereview.stackexchange.com/a/31564/120114\">this answer</a> for inspiration.</p>\n<h2>Review</h2>\n<p>Just as a POJO is created for the definition of <code>Directions</code> I'd recommend setting up a POJO for the colors used in <code>drawMap</code>. That way instead of using the <code>switch</code> statement, the code can check to see if the value exists as a key in the mapping and then set the value of <code>ctx.fillStyle</code> accordingly.</p>\n<p>The keypress handler can be simplified using <code>event.key.toLowerString()</code>, as well as a mapping of keys to directions.</p>\n<p><code>hasReachedGoal</code> calls <code>alert</code>. Some users may have disabled alerts in a browser setting. It is better to use HTML5 <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\" rel=\"nofollow noreferrer\"><code><dialog></code></a> element - it allows more control over the style and doesn't block the browser. Bear in mind that it <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#Browser_compatibility\" rel=\"nofollow noreferrer\">isn't supported by IE and Safari</a> but <a href=\"https://github.com/GoogleChrome/dialog-polyfill\" rel=\"nofollow noreferrer\">there is a polyfill</a></p>\n<p>In <code>game.js</code> the function <code>grawGoals()</code> uses <code>foreach</code> with a callback function that accepts <code>coord</code> as a parameter. Instead of manually setting and updating a counter variable i.e. <code>i</code> accept it as the second parameter because <code>forEach</code> passes three arguments<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Parameters\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n<p>In the original code <code>mapGrid</code> is declared with <code>const</code>, yet in <em>game.js</em> the <code>maze</code> is declared with <code>let</code>. It is better to use <code>const</code> as a default and then when you determine re-assignment is needed switch to <code>let</code>. This helps avoid accidental re-assignment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T18:32:02.087",
"Id": "479384",
"Score": "1",
"body": "The color thing is a really good suggestion, I didn't think of it. Would you say it's better to change `Directions` map, to something like `up: 'W', ...`? Those `alerts` were just for testing purposes actually, but I didn't know the `<dialog>` element existed. Thank you for this really helpful answer. I'll leave the question open until the bounty expires just in case someone else can provide some extra points."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:39:58.000",
"Id": "244144",
"ParentId": "243537",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T02:20:20.100",
"Id": "243537",
"Score": "10",
"Tags": [
"javascript",
"game",
"html5",
"canvas",
"collision"
],
"Title": "Battle City (Tank) replica"
}
|
243537
|
<p>I would like to speed up pandas apply function. I have been using swifter . It currently takes about 5 mins for 200000 records using multiprocessing as below . Is there any way to speed this up further .</p>
<pre><code>def partial_match(source_words, dest_words):
matched_words = ''
if any(word in dest_words for word in source_words) :
match_words_list = set(source_words)&set(dest_words)
matched_words = ",".join(match_words_list)
return matched_words
def exact_match(source_words, dest_words):
matched_words = ''
if all(word in dest_words for word in source_words) :
match_words_list = set(source_words)&set(dest_words)
matched_words = ",".join(match_words_list)
return matched_words
series_index = ['match_type', 'matched_words' ]
def perform_match(x):
match_series = pd.Series(np.repeat('', len(series_index)), index = series_index)
if x['remove_bus_ending'] == 'Y':
x['dest_words'] = x['dest_words_2']
else:
x['dest_words'] = x['dest_words_1']
# exact match
if (x['partial_match_flag'] == 'Y') :
match_series['matched_words'] = partial_match(x['source_words'], x['dest_words'])
if match_series['matched_words'] != '':
match_series['match_type'] = 'Partial Match'
elif (x['exact_match_2'] == 'Y'):
match_series['matched_words'] = exact_match(x['source_words'], x['dest_words'])
if match_series['matched_words'] != '':
match_series['match_type'] = 'Exact Match'
return match_series
from multiprocessing import Pool
from functools import partial
import numpy as np
def parallelize(data, func, num_of_processes=8):
data_split = np.array_split(data, num_of_processes)
pool = Pool(num_of_processes)
data = pd.concat(pool.map(func, data_split))
pool.close()
pool.join()
return data
def run_on_subset(func, data_subset):
return data_subset.swifter.apply(func, axis=1)
def parallelize_on_rows(data, func, num_of_processes=8):
return parallelize(data, partial(run_on_subset, func), num_of_processes)
df[match_series] = parallelize_on_rows(df, perform_match)
</code></pre>
<p>below is some sample data</p>
<pre><code>flag1 partial_match_flag exact_match_flag source_words dest_word_2 dest_words_1
0 N Y N [song, la] [urban, karamay, credit, city, co, kunlun, com... [ltd, urban, karamay, credit, city, co, kunlun...
1 N Y N [song, la] [al, abdulah, nasser] [al, abdulah, nasser]
2 N Y N [song, la] [al, abdulah, nasser] [al, abdulah, nasser]
3 N Y N [song, la] [abdulamir, mahdi] [abdulamir, mahdi]
4 N Y N [song, la] [abdullah, al, nasser] [abdullah, al, nasser]
5 N Y N [song, la] [abu, al, jud] [abu, al, jud]
6 N Y N [song, la] [al, herz, adam] [al, herz, adam]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:53:12.617",
"Id": "478031",
"Score": "0",
"body": "\"[However if you have CPU bound applications; one of the most important things you can known, is that if you add threading to a CPU bound application will it go faster or slower? Slower.](https://youtu.be/Bv25Dwe84g0?t=412)\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:54:30.407",
"Id": "478032",
"Score": "0",
"body": "Please edit your question so that you explain what your code does. Currently it is unclear."
}
] |
[
{
"body": "<h1>flag as boolean</h1>\n<p>If you change the flags from <code>'Y'</code> and <code>'N'</code> to <code>True</code> and <code>False</code> You can use boolean indexing. This should speed up a lot of things already</p>\n<h1>set</h1>\n<p>You check for each combination <code>word in dest_words for word in source_words</code> on a <code>list</code> of words. If the check matches, you convert to a <code>set</code>. The containment check would be sped up by checking against a list, but using <code>set</code> comparisons would speed this up a lot.</p>\n<pre><code>import typing\n\ndef partial_match(\n source_words: typing.Set[str], dest_words: typing.Set[str], index=None\n) -> typing.Tuple[typing.Any, typing.Optional[str]]:\n intersection = source_words & dest_words\n if intersection:\n return index, ", ".join(intersection)\n return index, None\n\ndef exact_match(\n source_words: typing.Set[str], dest_words: typing.Set[str], index=None\n) -> typing.Tuple[typing.Any, typing.Optional[str]]:\n if source_words == dest_words:\n return index, ", ".join(source_words)\n return index, None\n</code></pre>\n<p>The reason I chose to return the index along with it is to be able to reconstruct the series easier when reassembling everything.</p>\n<h1>Don't touch the original data</h1>\n<p>You change your source data inplace (by adding columns). Better would be to leave this untouched, and keep the destination words etc in separate series.</p>\n<h1><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html\" rel=\"nofollow noreferrer\"><code>Series.where</code></a></h1>\n<p>You can replace calls like this</p>\n<pre><code>if x['remove_bus_ending'] == 'Y':\n x['dest_words'] = x['dest_words_2']\n else:\n x['dest_words'] = x['dest_words_1']\n</code></pre>\n<p>with <code>Series.where</code></p>\n<pre><code>a = pd.Series(list("abcd"))\nb = pd.Series(list("efgh"))\nc = pd.Series([True, True, False, True])\nb.where(c, other=a)\n</code></pre>\n<blockquote>\n<pre><code>0 e\n1 f\n2 c\n3 h\ndtype: object\n</code></pre>\n</blockquote>\n<p>If your data looks like this:</p>\n<pre><code>from io import StringIO\n\nimport pandas as pd\n\ndef setify(s):\n return s.str.strip("[]").str.split(", ").apply(set)\n\ndf = pd.read_csv(StringIO(data_str), sep="\\s\\s+", index_col=False, engine='python')\ndf["source_words"] = setify(df["source_words"])\ndf["dest_words_1"] = setify(df["dest_words_1"])\ndf["dest_word_2"] = setify(df["dest_word_2"])\ndf["remove_bus_ending"] = df["remove_bus_ending"] == "Y"\ndf["partial_match_flag"] = df["partial_match_flag"] == "Y"\ndf["exact_match_flag"] = df["exact_match_flag"] == "Y"\n</code></pre>\n<h1>intermediate dataframe</h1>\n<p>If you want to split the dataframe with arraysplit, you'll need to provide an intermediate form with the info you need:</p>\n<pre><code>df_intermediate = pd.concat(\n [\n df["dest_word_2"]\n .where(df["remove_bus_ending"], other=df["dest_words_1"])\n .rename("dest_words"),\n df["source_words"],\n ],\n axis=1,\n)\n</code></pre>\n<p>You can even split it immediately according to what matching is needed</p>\n<pre><code>df_intermediate_partial = df_intermediate.loc[df["partial_match_flag"]]\ndf_intermediate_exact = df_intermediate.loc[df["exact_match_flag"]]\n</code></pre>\n<h1>applying the function</h1>\n<p>not parallel:</p>\n<pre><code>result_partial = list(\n map(\n partial_match,\n df_intermediate_partial["source_words"],\n df_intermediate_partial["dest_words"],\n df_intermediate_partial.index,\n )\n)\n\n\nresults_exact = list(\n map(\n exact_match,\n df_intermediate_exact["source_words"],\n df_intermediate_exact["dest_words"],\n df_intermediate_exact.index,\n )\n)\n\nresult = pd.Series(result_partial + results_exact)\n</code></pre>\n<p>This should be easy to parallelize. Since I'm no expert on that, I'll leave that to others.</p>\n<h1>context manager</h1>\n<p>Most of the examples I found in the <code>multiprocessing</code> documantation work with a context manager that takes care of the closing of the pool</p>\n<pre><code>with Pool(processes=4) as pool:\n ... # parallel part of the code\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T06:08:48.460",
"Id": "478332",
"Score": "0",
"body": "flagging as boolean and setifying data has improved speed drastically"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T13:39:21.590",
"Id": "243558",
"ParentId": "243541",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243558",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T05:59:37.333",
"Id": "243541",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"pandas"
],
"Title": "Speeding up pandas apply"
}
|
243541
|
<p>I have written an adapter for <code>RecyclerView</code>. It can handle onClicks for <code>RecyclerView</code> items and select the color name and edit <code>TextView</code> for the clicked item. By default the first item TextView name is the selected color.
When a user clicks another item the last item <code>TextView</code> is named black. When the the user clicks a color, such as granadier, then the <code>TextView</code> is changed to that color's name. And so on.</p>
<p>Can my code quality and code style be improved? Additionally I'm not a fan of, when a user clicks on new item, calling <code>notifyDataSetChanged</code> on all items.</p>
<p><code>AudioRecordsListAdapter.kt</code></p>
<pre><code>class AudioRecordsListAdapter :
RecyclerView.Adapter<AudioRecordsListAdapter.AudioRecordViewHolder>() {
var items: MutableList<AudioRecordUI> = ArrayList()
set(value) {
if (value.size > 0) {
value.first().isActive = true
}
items.clear()
items.addAll(value)
notifyDataSetChanged()
}
var isSelectableMode = false
var onAudioRecordClickListener: OnAudioRecordClickListener? = null
companion object {
var dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")
var timeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("mm::ss")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AudioRecordViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.sound_record_item, parent, false)
return AudioRecordViewHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: AudioRecordViewHolder, position: Int) {
holder.bind(items[position])
}
inner class AudioRecordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var audioRecordUI: AudioRecordUI? = null
fun bind(audioRecordUI: AudioRecordUI) {
this.audioRecordUI = audioRecordUI
val size = formatFileSize(itemView.context, audioRecordUI.getSize())
itemView.name.text = audioRecordUI.getName()
itemView.date.text = audioRecordUI.getDate().format(dateFormatter)
itemView.time.text = audioRecordUI.getTime().format(timeFormatter)
itemView.size.text = size
itemView.select.isChecked = audioRecordUI.isSelect
if (audioRecordUI.isActive)
itemView.name.setTextColor(itemView.context.getColor(R.color.grenadier))
else
itemView.name.setTextColor(itemView.context.getColor(R.color.black))
setClickListener(audioRecordUI)
setLongClickListener()
}
private fun setClickListener(audioRecorderUI: AudioRecordUI) {
itemView.setOnClickListener {
if (isSelectableMode) {
itemView.select.isChecked = !itemView.select.isChecked
} else {
onAudioRecordClickListener?.onClick(audioRecorderUI.audioRecorderEmpty)
clearActive()
audioRecorderUI.isActive = true
notifyDataSetChanged()
}
}
}
private fun clearActive() {
items.forEach { it.isActive = false }
}
private fun setLongClickListener() {
itemView.setOnLongClickListener {
isSelectableMode = !isSelectableMode
if (!isSelectableMode) {
clearSelect()
}
itemView.select.isChecked = !itemView.select.isChecked
true
}
}
private fun clearSelect() {
items.forEach { it.isSelect = false }
notifyDataSetChanged()
}
}
interface OnAudioRecordClickListener {
fun onClick(audioRecordEmpty: AudioRecordEmpty)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T12:19:14.327",
"Id": "478035",
"Score": "0",
"body": "I used this service to name my colors: http://chir.ag/projects/name-that-color/#C43E00. What word should I use to describe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T12:25:30.433",
"Id": "478037",
"Score": "0",
"body": "This site gave me the color name - C43E00"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T12:28:35.737",
"Id": "478040",
"Score": "0",
"body": "This site gave me the word grenadier as the name for the color with code # C43E00"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T12:37:14.513",
"Id": "478043",
"Score": "0",
"body": "Ok. Thank you, I understand what you mean now. Please can you ensure that my edits haven't changed the meaning of your question."
}
] |
[
{
"body": "<p>I like nitwitting about kotlin, therefor only feedback about the language.</p>\n<h1><a href=\"https://kotlinlang.org/docs/reference/functions.html#single-expression-functions\" rel=\"nofollow noreferrer\">single expression functions</a></h1>\n<p>If your function exists out of one expression, you can write it easier.<br />\nInstead of having to write:</p>\n<pre><code>override fun getItemCount(): Int {\n return items.size\n}\n</code></pre>\n<p>you can write:</p>\n<pre><code>override fun getItemCount() = items.size\n</code></pre>\n<h1>code duplication</h1>\n<p>Try to remove as much duplication as possible.</p>\n<pre><code>if (audioRecordUI.isActive)\n itemView.name.setTextColor(itemView.context.getColor(R.color.grenadier))\nelse \n itemView.name.setTextColor(itemView.context.getColor(R.color.black))\n</code></pre>\n<p>In the code above, you do three things:</p>\n<ol>\n<li>Choose a colorId</li>\n<li>Get the matching color</li>\n<li>set the itemview to the color</li>\n</ol>\n<p>Actions 2 and 3 are duplicated.<br />\nWith a simple variable, this code becomes much clearer.</p>\n<pre><code>val textColorId = if(audioRecordUi.isActive) R.color.grenadier else R.color.black\nitemView.name.setTextColor(itemView.context.getColor(textColorId))\n</code></pre>\n<h1>scoped functions</h1>\n<p>When you need to reuse a variable multiple times after eachother, you can use a scoped function, eg <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/also.html\" rel=\"nofollow noreferrer\">also</a> and <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html\" rel=\"nofollow noreferrer\">apply</a>.<br />\ninstead of writing:</p>\n<pre><code>itemView.select.isChecked = !itemView.select.isChecked\n</code></pre>\n<p>you can write:</p>\n<pre><code>itemView.select.also { it.isChecked = !it.isChecked }\n</code></pre>\n<p>or even:</p>\n<pre><code>itemView.select.apply { this.isChecked = !this.isChecked }\n</code></pre>\n<p>And as you don't have to write <code>this</code>:</p>\n<pre><code>itemView.select.apply { isChecked = !isChecked }\n</code></pre>\n<h1>Personal choice</h1>\n<p>I personally don't like the three lines for a simple if:</p>\n<pre><code>if (!isSelectableMode) {\n clearSelect()\n}\n</code></pre>\n<p>If it's this short, I would place it on one line.\nIf it would be a bit longer, two lines without brackets.</p>\n<pre><code>if (!isSelectableMode) clearSelect()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:42:47.293",
"Id": "244052",
"ParentId": "243542",
"Score": "3"
}
},
{
"body": "<p>**Note: A lot of these might be very similar to <a href=\"https://codereview.stackexchange.com/a/244052/225833\">tieskedh's answer</a> but I drafted before it was here so I thought I should add it **</p>\n<blockquote>\n<p>I'm not a fan of, when a user clicks on new item, calling notifyDataSetChanged on all items.</p>\n</blockquote>\n<p>You can use <code>notifyItemRangeChanged(index)</code> or <code>notifyItemChanged(index)</code> in order to specify which items have changed. This is incredibly useful/important with RecyclerViews with many items as the docs say <code>notifyDataSetChanged()</code> <a href=\"https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter#notifyDataSetChanged()\" rel=\"nofollow noreferrer\">is not very efficient</a></p>\n<h3>Other stuff</h3>\n<p><code>clearActive()</code> doesn't call <code>notifyDataSetChanged()</code> whereas <code>clearSelect()</code> does which seems inconstient but this might be intended behaviour</p>\n<p>Both <code>dateFormatter</code> and <code>timeFormatter</code> are public vals, they're never modified and I assume they're only used in this project so you can change them to <code>private val</code>.</p>\n<p><code>var items</code> has a custom setter which requires the whole array to be cleared and added each time. It might be worth considering adding methods to support removing and adding singular items from the RecyclerView if that fits your use case.</p>\n<p>This is very much a question of taste and personal prefrence, where you have mutliple accesses to the same object you can use a <a href=\"https://kotlinlang.org/docs/reference/scope-functions.html\" rel=\"nofollow noreferrer\"><strong>scope function</strong></a> (let, apply, with etc.)\nto make this block of code less verbose.</p>\n<pre><code>itemView.name.text = audioRecordUI.getName()\n itemView.date.text = audioRecordUI.getDate().format(dateFormatter)\n itemView.time.text = audioRecordUI.getTime().format(timeFormatter)\n itemView.size.text = size\n itemView.select.isChecked = audioRecordUI.isSelect\n</code></pre>\n<h3>Styling</h3>\n<p>As this is code style, this is subjective and often is something you might have agree on collabratively when working in a team.</p>\n<p><strong>Expression Body functions</strong>\nYou can use expression body functions (instead of normal/block body) in Kotlin for functions that return non <code>Unit</code> types to remove braces. These are often easier to read/more concise especially with small functions but it's a taste thing.</p>\n<p><code>override fun getItemCount() = items.size</code></p>\n<p><strong>mutableListOf()</strong>\nKotlin provides the methods <code>listOf()</code> & <code>mutableListOf()</code> so you could that instead of explictly instaniating an <code>ArrayList()</code> like so:\n<code>var items = mutableListOf<AudioRecordUI>()</code></p>\n<p><strong>Removing Explicit types</strong></p>\n<p>To make your code more concise, you can avoid explict time declerations like so</p>\n<pre><code>var dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")\nvar timeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("mm::ss")\n</code></pre>\n<p>It might be worth checking out Kotlin's <a href=\"https://kotlinlang.org/docs/reference/idioms.htmls\" rel=\"nofollow noreferrer\">idioms</a> & <a href=\"https://kotlinlang.org/docs/reference/coding-conventions.html\" rel=\"nofollow noreferrer\">coding-convention</a> pages for frequently used and "more tidy" ways of wrting code compared to Java. I can't see if this is the case but you seem to be using property getters for the <code>AudioRecordUi</code> the way Java would. Like <code>.getDate()</code> <code>audioRecordUI.getName()</code>, in Kotlin getters are generated automatically and you should access the properties if they are exposed <code>.name</code>, <code>.date</code> etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T22:33:58.617",
"Id": "245055",
"ParentId": "243542",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244052",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T06:02:59.043",
"Id": "243542",
"Score": "1",
"Tags": [
"beginner",
"android",
"kotlin"
],
"Title": "Adapter for RecyclerView with supported onClick handling and select color text on last clicked item"
}
|
243542
|
<h3>Problem</h3>
<blockquote>
<p>For the given binary tree return the list which has sum of every paths in a tree. i.e Every path from root to leaf.</p>
</blockquote>
<p>I've written following solution.</p>
<pre class="lang-java prettyprint-override"><code>void check()
{
List<Integer> out = new ArrayList<>();
leafsum(root, 0, out);
System.out.println(out);
}
void leafsum(TreeNode root, int curr , List<Integer> sum)
{
if(root != null)
{
leafsum(root.left, curr+root.data, sum);
if(root.left == null && root.right == null ) sum.add(curr+root.data);
leafsum(root.right, curr+root.data, sum);
}
}
</code></pre>
<blockquote>
<p>Inorder traversal of Tree</p>
</blockquote>
<h2>2 4 3 5 1 9 2 5 15</h2>
<pre><code>root = new TreeNode(5);
root.left = new TreeNode(4);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(3);
root.right = new TreeNode(9);
root.right.right = new TreeNode(5);
root.right.left = new TreeNode(1);
root.right.right.left = new TreeNode(2);
root.right.right.right = new TreeNode(15);
</code></pre>
<blockquote>
<p>Output</p>
</blockquote>
<h2>[11, 12, 15, 21, 34]</h2>
<p>I would like review about improvements and suggestions.</p>
|
[] |
[
{
"body": "<h1>Formatting</h1>\n<p>The formatting could be nicer and doesn't follow Java conventions.</p>\n<ul>\n<li>The indention isn't correct (maybe a copy and paste error).</li>\n<li>Opening braces belong on the same line as the method header/statement.</li>\n<li>There are random superfluous spaces (after <code>int curr</code> and <code>root.right == null</code>) and missing spaces around the <code>+</code> operator in <code>curr+root.data</code></li>\n<li>There should be a space between keywords and opening brackets (<code>if (...</code>).</li>\n<li>Braces should always be used around a conditional block, even if it only contains a single statement.</li>\n<li>There shouldn't be more than a single blank line at a time and there shouldn't any at all inside <code>leafsum</code> in my opinion.</li>\n</ul>\n<h1>Names</h1>\n<p>The parameter names could be better:</p>\n<ul>\n<li><code>root</code> should be <code>node</code>.</li>\n<li>There is no need to abbreviate <code>curr</code>. It should be <code>current</code> or maybe even <code>currentSum</code>.</li>\n<li>The list should have a plural name: <code>sums</code>.</li>\n</ul>\n<p>The method itself should also have a plural name such as <code>leafSums</code>.</p>\n<h1>Early return</h1>\n<p>In order to minimize indention depth return early out of <code>leafsum</code> instead of putting the complete method body inside the <code>if</code> block:</p>\n<pre><code>void leafsum(TreeNode root, int curr, List<Integer> sum) {\n if (root == null) {\n return;\n }\n // method body here.\n}\n</code></pre>\n<h1>DRY</h1>\n<p>You are repeating the sum <code>curr + root.data</code> three times.</p>\n<h1>Handling results</h1>\n<p>I'm not a big fan creating, carrying around and mutating a list for the results, however your way is probably the least convoluted way with Java's standard collection library. Personally I'd do something like:</p>\n<pre><code>static List<Integer> leafSums(TreeNode node, int currentSum) {\n if (node == null) {\n return Collections.emptyList();\n }\n\n int newSum = currentSum + node.data;\n\n List<Integer> leftSums = leafSums(node.left, newSum);\n List<Integer> rightSums = leafSums(node.right, newSum);\n\n List<Integer> sums = new ArrayList<>(leftSums);\n if (node.left == null && node.right == null) {\n sums.add(newSum);\n }\n sums.addAll(rightSums);\n\n return sums;\n}\n</code></pre>\n<p>except I'd look for alternative to <code>ArrayList</code> that allows more efficient list concatenation with a nicer API.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T12:21:55.497",
"Id": "243600",
"ParentId": "243544",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T07:52:24.863",
"Id": "243544",
"Score": "1",
"Tags": [
"java",
"tree",
"pathfinding",
"depth-first-search"
],
"Title": "Sum of all Paths in Binary Tree"
}
|
243544
|
<p>As part of an assignment for college summer classes, I was tasked with writing a program that solves roots of negative numbers. I've ran it through the test cases I was provided and it computes correctly. I'm looking for any feedback, especially about the <code>determine_factors</code> function, which really should be renamed. It looks messy and I don't like it, but it's all I could come up with. I'll be tweaking it since it's not due for a while, but I wanted to get some experienced eyes on this.</p>
<pre><code>"""
Helper tool for solving negative square roots.
@author Ben Antonellis
@date 06-08-2020
"""
from math import isqrt
from typing import List, Union, Tuple
def is_perfect(number: int) -> bool:
"""
Returns if a number is a perfect square.
"""
return number == isqrt(number) ** 2
def get_factors(number: int) -> List[List[int]]:
"""
Returns all the factors of a number.
"""
factors = [[x, number // x] for x in range(2, number + 1) if number % x == 0]
factors = factors[:len(factors) // 2] # Removes duplicates and any [1, x] pairs #
return factors
def determine_factors(factors: List[int], num: int) -> str:
"""
Determines what factors are left at the end of calculation.
"""
simplified, remainder = 0, 0
for number, times_in_number in factors:
if number == times_in_number:
return f"{number}i"
if get_factors(number) == [] and get_factors(times_in_number) == []:
return f"√({num})i"
if is_perfect(number):
simplified += isqrt(number)
if not is_perfect(times_in_number):
if get_factors(times_in_number) == [] or not any(is_perfect(x) or is_perfect(y) for [x, y] in get_factors(times_in_number)):
remainder += times_in_number
return f"{simplified}√({remainder})i"
elif is_perfect(times_in_number):
simplified += isqrt(times_in_number)
if not is_perfect(number):
if get_factors(number) == []:
remainder += number
return f"{simplified}√({remainder})i"
if not any(is_perfect(number) or is_perfect(times_in_number) for number, times_in_number in factors):
return f"√({num})i"
def solve(num: int) -> str:
"""
Solves a negative square root with the passed number.
"""
num = abs(num)
# Check for prime numbers #
if not any(num % i == 0 for i in range(2, num)):
return f"√({num})i"
# Find all factors #
factors = get_factors(num)
# Determine what factors to use and weed out perfect numbers #
return determine_factors(factors, num)
def main():
num = int(input("Enter negative inside square root: "))
result = solve(num)
print(result)
if __name__ == "__main__":
main()
</code></pre>
<p>Test cases are below</p>
<pre><code>Input -> Output
---------------
-52 -> 2√(13)i
-20 -> 2√(5)i
-35 -> √(35)i
-36 -> 6i
-30 -> √(30)i
-18 -> 3√(2)i
-70 -> √(70)i
-90 -> 3√(10)i
-100 -> 10i
</code></pre>
|
[] |
[
{
"body": "<h1>Style</h1>\n<p>You've done a great job of style from a technical point of view.</p>\n<ul>\n<li>You're following PEP-8 guidelines.</li>\n<li>The functions have type-hints</li>\n<li>The functions have docstrings</li>\n</ul>\n<p>Defects:</p>\n<ul>\n<li><p>The docstrings aren't very useful:</p>\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(get_factors)\n\nHelp on function get_factors in module __main__:\n\nget_factors(number: int) -> List[List[int]]\n Returns all the factors of a number.\n</code></pre>\n<p>This doesn't explain what the factors are going to be. A list of list of integers, yes, but no clue what that means, or to expect that <code>[1, x]</code> will be excluded.</p>\n</li>\n<li><p>the <code>determine_factors</code> method is a wall of code, with not a single comment insight describing how it is supposed to work.</p>\n</li>\n</ul>\n<h1><code>is_perfect()</code></h1>\n<p>This is actually pretty close to perfect. :-)</p>\n<h1><code>get_factors()</code></h1>\n<p>You are (without any indication to the caller) omitting <code>[1, x]</code> (should be at least mentioned in the docstring.</p>\n<p>You are finding all factors from <code>2</code> up to (and including!) <code>number</code>, which means the last pair generated is <code>[number, 1]</code>. Why do you skip generating <code>[1, number]</code> by starting at <code>2</code>, yet continue up to <code>number + 1</code>?</p>\n<p>How does <code>factors[:len(factors) // 2]</code> remove duplicates, when it is using truncating integer division, and you can have an odd number of factor pairs?</p>\n<p>Why bother generating the factor pairs if you are just going to discard half of them anyway? Just iterate from <code>2</code> up to (and including) <code>isqrt(number)</code>. Way more efficient.</p>\n<h1><code>determine_factors()</code></h1>\n<p>I have no idea how this function works. <code>simplified += ...</code> and <code>remainder += ...</code>? Multiplication of factors is not additive, so this doesn't make sense.</p>\n<p>Moreover, the function doesn't work. <code>-54</code> and <code>-96</code> return nothing:</p>\n<pre class=\"lang-none prettyprint-override\"><code>>>> solve(-54)\n>>> solve(-96)\n</code></pre>\n<h1>A better algorithm</h1>\n<p>Instead of computing all of the factors of <code>number</code>, determine the prime factorization of <code>number</code>. For instance:</p>\n<p><span class=\"math-container\">$$ \\sqrt {96} = \\sqrt { 2^5 * 3^1 } $$</span></p>\n<p>Any odd power will result in that factor to the power of 1 under the square root. After removing those, you've got primes raised to even powers, which can all be divided by two, and moved out from the square-root:</p>\n<p><span class=\"math-container\">$$ \\sqrt {96} = \\sqrt { 2^4 } * \\sqrt {2^1 * 3^1} = 2^2 * \\sqrt {2^1 * 3^1} $$</span></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T19:49:09.937",
"Id": "243575",
"ParentId": "243546",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T08:46:46.960",
"Id": "243546",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"mathematics",
"complex-numbers"
],
"Title": "Solving roots of negative numbers"
}
|
243546
|
<p>I'm using <a href="https://github.com/JKorf/Binance.Net" rel="nofollow noreferrer">Binance.Net</a> and I wanted to get historical candle data from start date to end date which is useful for backtesting. They don't really provide that functionality, so I have to do it myself. <a href="https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-data" rel="nofollow noreferrer">Their API</a> allows me to specify <code>startTime</code> (start date) and <code>endTime</code> (end date) and limit (cannot exceed 1000). I'm reading candles until I reach all of them between <code>start date</code> and <code>end date</code>, because of that limit.</p>
<h3>Two test cases (read the comments right next to <code>first</code> and <code>last</code>):</h3>
<p>I added them to the question so you can get the idea behind that REST point.</p>
<pre><code>BinanceClient client = new BinanceClient(new BinanceClientOptions()
{
ApiCredentials = new ApiCredentials(configuration["BinanceSettings:ApiKey"], configuration["BinanceSettings:SecretKey"]),
AutoTimestamp = true,
AutoTimestampRecalculationInterval = TimeSpan.FromMinutes(30)
});
var candles = _client.GetKlines(symbol: "TRXUSDT", interval: KlineInterval.ThirtyMinutes, startTime: new DateTime(2018, 06, 06), endTime: new DateTime(2020, 06, 16), limit: 1000).Data.SkipLast(1).ToList();
// Test case 1
var first = candles.First().OpenTime; // 6/11/2018 11:30:00 AM. This doesn't match the specified "startTime" because Binance doesn't have data before the returned date
var last = candles.Last().OpenTime; // 7/2/2018 6:00:00 PM. This doesn't match the specified "endTime" because the limit is 1000, which means it cuts the result when it reaches 1000.
// Test case 2
var candles = _client.GetKlines(symbol: "TRXUSDT", interval: KlineInterval.ThirtyMinutes, startTime: new DateTime(2020, 06, 06), endTime: new DateTime(2020, 06, 15), limit: 1000).Data.SkipLast(1).ToList();
var first = candles.First().OpenTime; // 6/6/2020 12:00:00 AM - fine
var last = candles.Last().OpenTime; // 6/8/2020 8:00:00 AM - That's the latest data, because the specified "endTime" is greater than the current date and time.
</code></pre>
<h3>Something very important:</h3>
<p>That loop's only responsibility is when there are more than 1000 candles between a given start date and end date. For example if the start date is <code>2018-01-01</code> and end date: <code>2020-01-01</code> (2 years), assuming the interval remains 30 minutes (<code>KlineInterval.ThirtyMinutes</code>), there are going to be way more than 1000 candles, which means a single call to <code>client.GetKlines(...)</code> won't make it. It will return the first 1000 candles but not all of them. If the period between start date and end date is very short, we might end up with less than 1000 candles returned by <code>client.GetKlines(...)</code>, which is fine. It might be better if I add a check to the loop (execute it only if the first call to <code>client.GetKlines(...)</code> returns 1000 candles; if less - do nothing).</p>
<h3>The actual question:</h3>
<p>I believe my code works fine and covers both test cases from above. Can you suggest me what to improve for better visual and performance look? A parallel loop would be a way to add multithreading in order to execute it faster.</p>
<pre><code>// Input data
DateTime StartDate = new DateTime(2018, 06, 04);
DateTime EndDate = new DateTime(2019, 01, 15);
// Logic that has to be improved
var interval2 = KlineInterval.OneDay;
var candles = _client.GetKlines(symbol, interval2, startTime: StartDate, endTime: EndDate, limit: 1000).Data.ToList();
var firstCandle = candles.First();
var lastCandle = candles.Last();
while (true)
{
var candles2 = _client.GetKlines(symbol, interval2, startTime: lastCandle.OpenTime, endTime: EndDate, limit: 1000).Data.ToList();
firstCandle = candles.First();
lastCandle = candles.Last();
// This check prevents re-adding already existent data
if (candles2.Last().OpenTime != lastCandle.OpenTime)
candles.AddRange(candles2);
if (EndDate == new DateTime(lastCandle.OpenTime.Year, lastCandle.OpenTime.Month, lastCandle.OpenTime.Day) || EndDate >= DateTime.Now)
break;
}
foreach (var candle in candles)
{
Console.WriteLine(candle.OpenTime);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T18:31:16.483",
"Id": "478192",
"Score": "0",
"body": "How many candles do you actually get (I would expect 255 (2018-06-04 to 2019-01)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T20:50:50.180",
"Id": "478212",
"Score": "0",
"body": "@JanDotNet, from `new DateTime(2018, 6, 4)` to `new DateTime(2019, 1, 15)` = 219 candles. That's because Binance has data from `6/11/2018`. So the start date is actually `new DateTime(2018, 6, 11)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T21:57:45.470",
"Id": "478218",
"Score": "0",
"body": "Ok, but 219 is less than the limit of 1000. Why do you have to load the candles in multiple steps?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T22:38:45.777",
"Id": "478219",
"Score": "0",
"body": "The limit is 1000. It cannot return more than 1000 candles but it can return less. The reason I do that in a loop is because if the candles between `start date` and `end date` exceed 1000, which is the limit, it won't collect them entirely but just the first 1000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T22:46:15.523",
"Id": "478220",
"Score": "0",
"body": "@JanDotNet, I hope you get the idea. If we look at the example above (`startTime: new DateTime(2018, 6, 4) ` and `endTime: new DateTime(2019, 1, 15)`), it doesn't have to go through the loop, because `client.GetKlines(...)` will return less than 1000 candles (219 - as we saw). It would probably be a better idea to add a check if `client.GetKlines(...)` returns `candles.Count = 1000` => do not process the loop, because that loop's only responsibility is when we have more than 1000 candles between `startTime` and `endTime`. 1000 is the maximum amount you can specify, if you look at their API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T10:37:50.983",
"Id": "478249",
"Score": "0",
"body": "Parallel processing helps with CPU-bound bottlenecks, like calculating a lot of cryptographically expensive hashes for example. Looks like the slow bit in your case is calling the API, which is IO-bound issue. Typically you'd solve that by using async calls, but it looks like you have to wait for each response before you can make the next request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T13:23:35.967",
"Id": "478261",
"Score": "0",
"body": "@StewartRitchie, yes https://github.com/JKorf/Binance.Net/blob/b1023bb46b8f35f699f0c1195cbc6b37070a31c0/Binance.Net/BinanceClient.cs#L521. Which makes no difference."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T09:12:38.970",
"Id": "243548",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Binance.Net getting historical data from start date to end date loop optimization"
}
|
243548
|
<p>I need suggestions on improving this code, the code is working fine ,but i'm gonna deploy this to production system, so before that would like to ask the community for any improvements/suggestions.</p>
<p>The script insert/update MySQL database using the data from PostgreSQL DB.</p>
<p>I have tested with some sample values and both insert and Updates are working fine.</p>
<p>Note: Using Python 3.5</p>
<pre><code>import psycopg2
import os
import time
import MySQLdb
import sys
from pprint import pprint
from datetime import datetime
from utils.config import Configuration as Config
from utils.postgres_helper import get_connection
from utils.utils import get_global_config
#ef db_connect():
# MySQLdb connection
try:
source_host = 'magento'
conf = get_global_config()
cnx_msql = MySQLdb.connect(host=conf.get(source_host, 'host'),
user=conf.get(source_host, 'user'),
passwd=conf.get(source_host, 'password'),
port=int(conf.get(source_host, 'port')),
db=conf.get(source_host, 'db'))
print('Magento MySQL DB Connected')
except mysql.connector.Error as e:
print ("MYSQL: Unable to connect!", e.msg)
sys.exit(1)
# Postgresql connection
try:
cnx_psql = get_connection(get_global_config(), 'pg_dwh')
print('DWH PostgreSQL DB Connected')
except psycopg2.Error as e:
print('PSQL: Unable to connect!\n{0}').format(e)
sys.exit(1)
# Cursors initializations
cur_msql = cnx_msql.cursor()
cur_msql_1 = cnx_msql.cursor()
cur_msql_2 = cnx_msql.cursor()
cur_psql = cnx_psql.cursor()
cur_psql_1 = cnx_psql.cursor()
now = time.strftime('%Y-%m-%d %H:%M:%S')
##################################################################################
update_sql_base="""select gr.email from unsubscribed gr
INNER JOIN nl_subscriber sn on sn.email=gr.email"""
msql_update_1="""UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'"""
msql_update_2="""UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';"""
cur_psql.execute(update_sql_base)
for row in cur_psql:
email=row[0]
cur_msql.execute(msql_update_1 %email)
cur_msql_2.execute(msql_update_2 %email)
cnx_msql.commit()
##################################################################################
insert_sql_base="""select gr.email,c.customer_id,'',3,'',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP),'','',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)
from unsubscribed gr
LEFT JOIN nl_subscriber sn on sn.email=gr.email
LEFT JOIN customers c on c.customer_email=gr.email
WHERE sn.email IS NULL"""
msql_insert_1="""INSERT INTO `nl_subscriber`(
`email`, `customer_id`, `options`, `status`, `confirm_code`, `timestamp`, `ip`, `store_id`,`confirmed_at`) SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s"""
cur_psql_1.execute(insert_sql_base)
for row in cur_psql_1:
print(msql_insert_1)
cur_msql_1.execute(msql_insert_1, row)
cnx_msql.commit()
## Closing cursors'
cur_msql.close()
cur_psql.close()
cur_psql_1.close()
cur_msql_1.close()
cur_msql_2.close()
## Committing
#cnx_psql.commit()
## Closing database connections
cnx_msql.close()
cnx_psql.close()
#if __name__ == '__main__':
#db_connect()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T20:01:04.730",
"Id": "478199",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>A couple thoughts.</p>\n\n<p>When opening database or other resources, try to use a <strong>context manager</strong> (the <code>with</code> statement). At the end of your code you are closing a bunch of connections/cursors:</p>\n\n<pre><code>## Closing cursors'\n## Closing cursors'\ncur_msql.close()\ncur_psql.close()\ncur_psql_1.close()\ncur_msql_1.close()\ncur_msql_2.close()\n\n## Closing database connections\ncnx_msql.close()\n</code></pre>\n\n<p>But your code could crash while processing, all it takes is a network error. There is no guarantee this code will be executed.</p>\n\n<p>One thing you can do is wrap the code in a <code>try/finally</code> block, and move those lines to the <code>finally</code> section. You don't have to have an <code>except</code> section. So I think it would be a good idea to use the <code>finally</code> for cleanup tasks.</p>\n\n<p>Some lines (the SQL statements) are way too long and require scrolling eg:</p>\n\n<pre><code>insert_sql_base=\"\"\"select gr.email,c.customer_id,'',3,'',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP),'','',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)\n from unsubscribed gr\n LEFT JOIN nl_subscriber sn on sn.email=gr.email\n LEFT JOIN customers c on c.customer_email=gr.email\n WHERE sn.email IS NULL\"\"\"\n</code></pre>\n\n<p>You can reflow the text like this for example:</p>\n\n<pre><code>insert_sql_base = \"\"\"SELECT gr.email,c.customer_id, '', 3, '',\nCAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP), '', '',\nCAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)\nFROM unsubscribed gr\nLEFT JOIN nl_subscriber sn ON sn.email = gr.email\nLEFT JOIN customers c ON c.customer_email = gr.email\nWHERE sn.email IS NULL\"\"\"\n</code></pre>\n\n<p>Added some more spacing too. Have a look at PEP guidelines, for instance <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n\n<p>Also, one thing I like to do is add aliases to the expressions in SQL queries. You have some blanks (<code>''</code>) or hardcoded values (<code>3</code>) but it's not immediately apparent what they represent.</p>\n\n<hr>\n\n<p>I think that you could reduce the number of variables. Too many similar-looking variables increases the risk of confusion.\nConsider this code:</p>\n\n<pre><code>msql_update_1=\"\"\"UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'\"\"\"\n\nmsql_update_2=\"\"\"UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';\"\"\"\n\ncur_psql.execute(update_sql_base)\n\nfor row in cur_psql:\n email=row[0]\n cur_msql.execute(msql_update_1 %email)\n cur_msql_2.execute(msql_update_2 %email)\ncnx_msql.commit()\n</code></pre>\n\n<p>You could have one cursor and reuse it eg:</p>\n\n<pre><code>for row in cur_psql:\n email=row[0]\n msql_update = \"\"\"UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'\"\"\"\n cur_msql.execute(msql_update %email)\n\n msql_update = \"\"\"UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';\"\"\"\n cur_msql.execute(msql_update %email)\ncnx_msql.commit()\n</code></pre>\n\n<p>Although I am not sure why you have two statements instead of just one. Again, use context managers whenever possible to limit scope as much as possible.</p>\n\n<hr>\n\n<p>There are very few <strong>comments</strong> in the code, and the flow is not that straightforward because there is <strong>overlap</strong>. For example:</p>\n\n<pre><code>update_sql_base=\"\"\"select gr.email from unsubscribed gr\n INNER JOIN nl_subscriber sn on sn.email=gr.email\"\"\"\n\nmsql_update_1=\"\"\"UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'\"\"\"\n\nmsql_update_2=\"\"\"UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';\"\"\"\n\ncur_psql.execute(update_sql_base)\n\nfor row in cur_psql:\n email=row[0]\n cur_msql.execute(msql_update_1 %email)\n cur_msql_2.execute(msql_update_2 %email)\ncnx_msql.commit()\n</code></pre>\n\n<p>Note that between the definition of <code>update_sql_base</code> and its execution, you define <code>msql_update_1</code>, <code>msql_update_2</code>. Move these two lines, try to keep related code together.</p>\n\n<p>A very modest change to better separate the two (includes proposed changes above):</p>\n\n<pre><code>update_sql_base = \"\"\"SELECT gr.email FROM unsubscribed gr\nINNER JOIN nl_subscriber sn ON sn.email = gr.email\"\"\"\ncur_psql.execute(update_sql_base)\n\n\nfor row in cur_psql:\n email=row[0]\n msql_update = \"\"\"UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'\"\"\"\n cur_msql.execute(msql_update %email)\n\n msql_update = \"\"\"UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';\"\"\"\n cur_msql.execute(msql_update %email)\ncnx_msql.commit()\n</code></pre>\n\n<p>But I find that the name <code>update_sql_base</code> is misleading. This is not an UPDATE statement but a SELECT statement. The names are not very helpful overall.</p>\n\n<hr>\n\n<p>You can declutter the code by moving blocks of code to small functions then call them in sequence eg:</p>\n\n<pre><code>open_mysql_db()\nopen_postgress_db()\nupdate_mysql_db()\nupdate_postgress_db()\nclose_postgress_db()\nclose_mysql_db()\n</code></pre>\n\n<p>That would make the whole more readable and easier to follow.</p>\n\n<p>Example:</p>\n\n<pre><code>def copy_subscribers(cnx_msql, cnx_psql):\n \"\"\"Copy subscribers from MySQL to Postgress\n \"\"\"\n\n try:\n cur_psql = cnx_psql.cursor()\n cur_msql = cnx_msql.cursor()\n\n # get subscriber list from MySQL\n insert_sql_base = \"\"\"SELECT gr.email,c.customer_id, '', 3, '',\n CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP), '', '',\n CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)\n FROM unsubscribed gr\n LEFT JOIN nl_subscriber sn ON sn.email = gr.email\n LEFT JOIN customers c ON c.customer_email = gr.email\n WHERE sn.email IS NULL\"\"\"\n cur_psql.execute(insert_sql_base)\n\n # insert susbcriber to Postgress\n msql_insert = \"\"\"INSERT INTO `nl_subscriber`(`email`, `customer_id`,\n `options`, `status`, `confirm_code`,\n `timestamp`, `ip`, `store_id`,`confirmed_at`)\n SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s\"\"\"\n for row in cur_psql:\n print(msql_insert)\n cur_msql.execute(msql_insert, row)\n\n finally:\n cnx_msql.commit()\n cur_psql.close()\n cur_msql.close()\n</code></pre>\n\n<p>I don't know if the function description is accurate but this is an idea. Note that I am passing connection instances <code>cnx_msql</code> and <code>cnx_psql</code> as arguments to the function (I prefer to avoid global variables). The idea is to better isolate the blocks, also avoid the proliferation of variables and at the same time limit their scope.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T19:53:18.340",
"Id": "478198",
"Score": "0",
"body": "Thanks a lot for this detailed explanation! I'm rather new to python, I have corrected fe things as you mentioned, But the function block, when i created it it was saying cursor was not defined, may be the scope is limited.And what i can do with the context manager here?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T20:59:03.043",
"Id": "243578",
"ParentId": "243552",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243578",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:26:52.890",
"Id": "243552",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Suggestions on Python code to update/insert data in PRODUCTION system"
}
|
243552
|
<p>From HackerRank's 10 Days of JavaScript, <a href="https://www.hackerrank.com/challenges/js10-loops/problem" rel="noreferrer">Day2: Loops</a>:</p>
<blockquote>
<p>Complete the vowelsAndConsonants function in the editor below. It has one parameter, a string,s, consisting of lowercase English alphabetic letters (i.e., a through z). The function must do the following:</p>
<p>First, print each vowel in s on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in s.
Second, print each consonant (i.e., non-vowel) in s on a new line in the same order as it appeared in s.</p>
</blockquote>
<p>The following code is in JavaScript. The code runs perfectly fine, just finding a way to make it better.</p>
<pre><code>function vowelsAndConsonants(s) {
let sp = s.split("");
let arr1 =[];
let arr2 =[];
for(let i=0;i<sp.length;i++)
{
if(sp[i]=='a'||sp[i]=='e'||sp[i]=='i'||sp[i]=='o'||sp[i]=='u'){
arr1.push(sp[i]);
}else{
arr2.push(sp[i]);
}
}
for(let i = 0;i<arr1.length;i++){
console.log(arr1[i]);
}
for(let i = 0;i<arr2.length;i++){
console.log(arr2[i]);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:06:23.827",
"Id": "478025",
"Score": "0",
"body": "Please clarify what your code is actually doing. Your description is very hard to decipher."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:13:53.073",
"Id": "478026",
"Score": "1",
"body": "Thanks for letting me know. I have edited the description so that it will be easier to decipher."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:34:43.110",
"Id": "478030",
"Score": "0",
"body": "Much better, thank you."
}
] |
[
{
"body": "<p>From a short review;</p>\n\n<ul>\n<li><code>arr1</code> and <code>arr2</code> are terrible names, we could call them <code>consonants</code> and <code>vowels</code></li>\n<li>accessing <code>sp[i]</code> so often is not efficient, I would store that value in a variable</li>\n<li>when dealing with lists, consider going functional (using <code>forEach</code>, <code>map</code>, <code>reduce</code>, <code>join</code> etc.)</li>\n<li><code>sp</code> is not a great name</li>\n<li>There is a nicer way to iterate over the characters of a string with <code>for( of )</code></li>\n</ul>\n\n<p>Finally, I wanted to provide the below as an example where I incorporate the above points;</p>\n\n<pre><code>function vowelsAndConsonants2(s) {\n const vowels = [],\n consonants = [];\n\n for(const c of s){\n if('aeiou'.includes(c)){\n vowels.push(c);\n }else{\n consonants.push(c);\n }\n }\n console.log(vowels.join(\"\\n\"));\n console.log(consonants.join(\"\\n\"));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T16:15:28.220",
"Id": "478082",
"Score": "1",
"body": "in the example code `c` becomes a global variable because it isn't declared with a scope keyword - I'd recommend `const`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T18:04:30.037",
"Id": "478086",
"Score": "1",
"body": "Good point, fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T11:28:42.277",
"Id": "243555",
"ParentId": "243553",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "243555",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T10:35:46.627",
"Id": "243553",
"Score": "7",
"Tags": [
"javascript",
"programming-challenge",
"node.js"
],
"Title": "Vowels and Consonants"
}
|
243553
|
<p>First of all, I am very new to programming and also this site.</p>
<p>This is a very simple "Rock, Paper, Scissors" game I made in C#. At first, it asks if I want to play the game. If my answer is yes, then I enter my name and the game starts. The program asks me to choose rock, paper or scissors, then the computer randomly picks one ,the program compares them and gives the outcome. If I win 5 rounds I win the game but if the computer wins 5 round it wins the game, and then the program asks if I want to play again.</p>
<p>My code is working but I think it could have been better, cleaner and shorter.</p>
<pre><code>using System;
using System.ComponentModel.Design;
namespace rockpaperscissors
{
class Player
{
public string playername;
private int playerscore;
public int Score
{
get { return playerscore; }
set { playerscore = value; }
}
}
class RockPaperScissors
{
public static string p_rps;
private static int c_rps;
private static int computerscore;
public static void Initialize(Player player)
{
player.Score = 0;
computerscore = 0;
}
public static void Board(Player player)
{
Console.WriteLine("\n\t\t{0}: {1}\n\n\t\tComputer: {2}\n", player.playername, player.Score, computerscore);
}
public static int ComputerRPS()
{
Random c = new Random();
c_rps = c.Next(1, 4);
return c_rps;
}
public static void Check(int c, Player player)
{
c = ComputerRPS();
switch(c)
{
case 1:
if (p_rps == "R")
{
Console.WriteLine("Tie");
}
else if (p_rps == "P")
{
Console.WriteLine("Computer chose rock.\nPaper beats rock. {0} wins this round.", player.playername);
player.Score++;
}
else if (p_rps == "S")
{
Console.WriteLine("Computer chose rock.\nRock beats scissors. Computer wins this round.");
computerscore++;
}
break;
case 2:
if (p_rps == "R")
{
Console.WriteLine("Computer chose paper.\nPaper beats rock. Computer wins this round.");
computerscore++;
}
else if (p_rps == "P")
{
Console.WriteLine("Tie");
}
else if (p_rps == "S")
{
Console.WriteLine("Computer chose paper.\nScissors beats rock. {0} wins this round.", player.playername);
player.Score++;
}
break;
case 3:
if (p_rps == "R")
{
Console.WriteLine("Computer chose scissors.\nRock beats scissors. {0} wins this round.", player.playername);
player.Score++;
}
else if (p_rps == "P")
{
Console.WriteLine("Computer chose scissors.\nScissors beats paper. Computer wins this round.");
computerscore++;
}
else if (p_rps == "S")
{
Console.WriteLine("Tie");
}
break;
}
}
public static bool WhoWins(Player player)
{
if (player.Score == 5)
{
Console.WriteLine("\n{0} wins the game.\n",player.playername);
return true;
}
if (computerscore == 5)
{
Console.WriteLine("\nComputer wins the game.\n");
return true;
}
return false;
}
}
class Program
{
public static bool play;
public static string startgame;
static void StartGameOrNot()
{
do
{
startgame = Console.ReadLine().ToUpper();
startgame.ToUpper();
if (startgame == "Y")
{
play = true;
}
else if (startgame == "N")
{
Console.WriteLine("\nOkay then, goodbye");
Environment.Exit(0);
}
else
{
Console.Write("\nInvalid. Do you want to start the game? [Y/N] --> ");
}
} while (startgame != "Y" && startgame != "N");
}
static void Main(string[] args)
{
Console.Write("Do you want to start the game? [Y/N] --> ");
StartGameOrNot();
Player player1 = new Player();
Console.Clear();
Console.Write("\n\n\tWhat is your name? --> ");
player1.playername = Console.ReadLine();
Console.Clear();
RockPaperScissors.Initialize(player1);
while (play)
{
RockPaperScissors.Board(player1);
do
{
Console.Write("Rock, paper, scissors? [R/P/S] --> ");
RockPaperScissors.p_rps = Console.ReadLine().ToUpper();
} while (RockPaperScissors.p_rps == "R" && RockPaperScissors.p_rps == "P" && RockPaperScissors.p_rps == "S");
int c = RockPaperScissors.ComputerRPS();
Console.Clear();
RockPaperScissors.Check(c, player1);
if(RockPaperScissors.WhoWins(player1))
{
Console.Write("Replay? --> ");
StartGameOrNot();
RockPaperScissors.Initialize(player1);
Console.Clear();
}
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Seperation of concerns, the rule engine should be separated from the \"AI\". Now you need a large rewrite if you want to support two players. </p>\n\n<p>Properly written there would be no difference if a AI player or a real player was playing and even two AI could play against each other.</p>\n\n<p>Also the rules can be defined with a 2 dimensional array instead of switch case / if-block</p>\n\n<p>Here is a working but not perfected example, I suspect that this is a school homework so do not want to give you everything ;)</p>\n\n<pre><code>class Program\n{\n private enum Type\n {\n Rock = 0, \n Paper = 1,\n Scissor = 2\n }\n\n private interface IPLayerInput\n {\n Type GetInput();\n }\n\n private class KeyboardPlayerInput : IPLayerInput\n {\n public Type GetInput()\n {\n return (Type)Enum.Parse(typeof(Type), Console.ReadLine() ?? string.Empty);\n }\n }\n\n private class AiPLayerInput : IPLayerInput\n {\n private readonly Type[] _values;\n private readonly Random _rand;\n\n public AiPLayerInput()\n {\n _values = Enum.GetValues(typeof(Type)).Cast<Type>().ToArray();\n _rand = new Random();\n }\n\n public Type GetInput()\n {\n return _values[_rand.Next(0, _values.Length)];\n }\n }\n\n private class Player\n {\n private readonly IPLayerInput _input;\n\n public Player(string name, IPLayerInput input)\n {\n _input = input;\n Name = name;\n }\n\n public int Score { get; set; }\n public string Name { get; }\n\n public void RequestNewHand()\n {\n CurrentHand = _input.GetInput();\n }\n\n public Type CurrentHand { get; private set; } \n }\n\n static void Main()\n {\n var rules = new Type?[,] { \n { null, Type.Paper, Type.Rock }, \n { Type.Paper, null, Type.Scissor }, \n { Type.Rock, Type.Scissor, null } };\n\n\n var players = new List<Player> {new Player(\"AI\", new AiPLayerInput()), new Player(\"Hooman\", new KeyboardPlayerInput())};\n\n Player winner = null;\n while (winner == null)\n {\n players.ForEach(p => p.RequestNewHand());\n foreach (var player in players)\n {\n var score = players.Count(p => p != player && rules[(int)player.CurrentHand, (int)p.CurrentHand] == player.CurrentHand);\n player.Score += score;\n }\n\n winner = players.SingleOrDefault(p => p.Score >= 3);\n }\n\n Console.WriteLine($\"Winner is {winner.Name}\");\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:34:52.910",
"Id": "243561",
"ParentId": "243556",
"Score": "3"
}
},
{
"body": "<p>The program compiles and runs on my machine, and I didn't notice any unexpected behavior or bug, so this is a good start.</p>\n\n<h1>Issues</h1>\n\n<h2>Naming conventions</h2>\n\n<p>In C# CamelCase is preferred for naming class properties. As such, names like <code>PlayerName</code>, <code>PlayerScore</code>, <code>ComputerScore</code> would be better.</p>\n\n<p>Same goes for namespaces, so <code>RockPaperScissors</code> would be better.</p>\n\n<p>Also, some names choices aren't quite meaningful. I feel like <code>ComputerMove</code> and <code>PlayerMove</code> would make more sense than <code>c_rps</code> and <code>p_rps</code>.</p>\n\n<h2>Unused <code>using</code></h2>\n\n<p>You don't use anything from <code>System.ComponentModel.Design</code>, so the line <code>using System.ComponentModel.Design;</code> should be removed.</p>\n\n<h2>Don't use global variables</h2>\n\n<p>While they technically are properties of the <code>Program</code> class, the <code>play</code> and <code>startgame</code> variables are scoped over the whole program, and there is no reason for this. Pass the variables as arguments if they should be used across multiple methods.</p>\n\n<h2>Use auto-properties</h2>\n\n<p>Considering this snippet:</p>\n\n<pre><code>private int playerscore;\n\npublic int Score\n{\n get { return playerscore; }\n set { playerscore = value; }\n}\n</code></pre>\n\n<p>C# has a shorthand for this kind of pattern, which would simply be:</p>\n\n<pre><code>public int PlayerScore { get; set; }\n</code></pre>\n\n<h2>Inconsistent types</h2>\n\n<p>A player move is stored as a <code>string</code>, while a computer move is store as an <code>int</code>. This is confusing, and makes it harder than necessary to compare the values. See your <code>Check()</code> method: there's got to be a way to make it simpler than listing all possible cases, right?</p>\n\n<p>Using <code>int</code>s for both would already makes it much easier. </p>\n\n<p>Another option is to create a class implementing the <code>IComparable</code> interface. It may be considered overkill in a simple case like this one, but has the advantage of being more generic and applicable to other, possibly more complex, cases.</p>\n\n<h2>Magic number</h2>\n\n<p>The game stops when a player's score reaches 5. That's fine, but it would better for this value to be a named constant. </p>\n\n<p>If you change your mind and decide that 3 is better, you'd have to change the value in 2 places in your code. That would be easy to miss. Also, if you were to use this value elsewhere (e.g. the start screen, so the player knows for how long he'll be playing), you'd have to remember what that value is, and remember to modify it if you decide to change the value. It also makes the code more readable.</p>\n\n<h2>Separation of concerns</h2>\n\n<p>I can tell you tried to separate concerns, with the core of the game being in its own class, and console display being (somewhat) in the <code>Program</code> class. However, you only achieve this goal partially. A lot of methods directly print stuff on the console, instead of returning the value, so display is mixed with logic. </p>\n\n<p>This is bad practice, the main reason being that it makes the code harder to reuse. Say you'd like to make a fancy-pants GUI to play the game, you'd have to rewrite most of the existing code because all your <code>Console.WriteLine</code>s would fail if you don't use a console.</p>\n\n<p>A good approach would be to have a class holding the game state, and a class in charge of displaying the game, fetching the required data from the game state object.</p>\n\n<h1>Possible game improvements</h1>\n\n<p>When you'll have a clean code for your basic game of rock, paper, scissors, implementing one of these improvements should be possible with minimum changes.</p>\n\n<h2>Set the length of the game</h2>\n\n<p>Let the player decide for how long he wants to play before starting the game. </p>\n\n<h2>PvP</h2>\n\n<p>Playing vs the computer is nice, but an option to play vs a human opponent would be even better. I would have a <code>ComputerPlayer</code> and a <code>HumanPlayer</code> class, which both inherit from a <code>Player</code> class. That way</p>\n\n<h2>Rock, paper, scissors, lizard, Spock</h2>\n\n<p>How would you go at changing the rules to include more moves? Any odd number of moves can make a balanced game. (see <a href=\"https://en.wikipedia.org/wiki/Rock_paper_scissors#Additional_weapons\" rel=\"noreferrer\">Wikipedia</a> if you're not familiar with that variant).</p>\n\n<p>This is where <code>Move</code> class would probably prove more readable than working with <code>int</code>s for moves.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:56:04.910",
"Id": "243564",
"ParentId": "243556",
"Score": "5"
}
},
{
"body": "<p>In case 2 you have \"Computer chose paper.\\nScissors beats rock.\"</p>\n\n<p>I don't think that is right. Should be \"Computer chose paper.\\nScissors beats paper.\"</p>\n\n<p>You have a static variable, c_rps, but it's not needed.</p>\n\n<p>What is \"using System.ComponentModel.Design;\" for? I doubt it is needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T19:00:20.227",
"Id": "478194",
"Score": "0",
"body": "You are right, I will edit my answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T15:03:17.963",
"Id": "243565",
"ParentId": "243556",
"Score": "3"
}
},
{
"body": "<p>You have "Computer chose paper.\\nScissors beats rock" in case 2.<br />\nYou have a static variable, <code>c_rps</code>, you don't need it<br />\n(1,4) is not right, should be Next(1,3), there are three choices in Rock, Paper and Scissors.<br />\nWhat is System. ComponentModel. Design use;?<br />\nI don't think you need that as well</p>\n<p>Hope that helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T17:06:55.250",
"Id": "478181",
"Score": "0",
"body": "For Random.Next the first value is inclusive and the second value is exclusive, so Next(1,4) would return an integer between 1 and 3 inclusively."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:15:59.300",
"Id": "243620",
"ParentId": "243556",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T13:13:44.280",
"Id": "243556",
"Score": "3",
"Tags": [
"c#",
"beginner",
"rock-paper-scissors"
],
"Title": "Rock, Paper, Scissors in C#"
}
|
243556
|
<p>I've recently finished my first ever C program. I implemented a Sudoku solver that uses backtracking.</p>
<p>Does my code look like a proper C-program? Are there any recommendations for improving my code?</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int valid(int[][9], int, int, int);
int solve(int[][9]);
int find_empty_cell(int[][9], int *, int *);
int main() {
int puzzle[9][9] = {{1, 7, 4, 0, 9, 0, 6, 0, 0},
{0, 0, 0, 0, 3, 8, 1, 5, 7},
{5, 3, 0, 7, 0, 1, 0, 0, 4},
{0, 0, 7, 3, 4, 9, 8, 0, 0},
{8, 4, 0, 5, 0, 0, 3, 6, 0},
{3, 0, 5, 0, 0, 6, 4, 7, 0},
{2, 8, 6, 9, 0, 0, 0, 0, 1},
{0, 0, 0, 6, 2, 7, 0, 3, 8},
{0, 5, 3, 0, 8, 0, 0, 9, 6}};
int row = 0;
int column = 0;
if (solve(puzzle)) {
printf("\n+-----+-----+-----+\n");
for (int x = 0; x < 9; ++x) {
for (int y = 0; y < 9; ++y) printf("|%d", puzzle[x][y]);
printf("|\n");
if (x % 3 == 2) printf("\n+-----+-----+-----+\n");
}
}
else {
printf("\n\nNO SOLUTION FOUND\n\n");
}
return 0;
}
int valid(int puzzle[][9], int row, int column, int guess) {
int corner_x = row / 3 * 3;
int corner_y = column / 3 * 3;
for (int x = 0; x < 9; ++x) {
if (puzzle[row][x] == guess) return 0;
if (puzzle[x][column] == guess) return 0;
if (puzzle[corner_x + (x % 3)][corner_y + (x / 3)] == guess) return 0;
}
return 1;
}
int find_empty_cell(int puzzle[][9], int *row, int *column) {
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
if (!puzzle[x][y]) {
*row = x;
*column = y;
return 1;
}
}
}
return 0;
}
int solve(int puzzle[][9]) {
int row;
int column;
if(!find_empty_cell(puzzle, &row, &column)) return 1;
for (int guess = 1; guess < 10; guess++) {
if (valid(puzzle, row, column, guess)) {
puzzle[row][column] = guess;
if(solve(puzzle)) return 1;
puzzle[row][column] = 0;
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall it looks fine for a beginner-level program, you keep the functions small and separate different parts of the logic between them, which is good.</p>\n\n<ul>\n<li><code>int valid(int[][9], int, int, int);</code> You should make a habit of naming your parameters even during function declaration. Ideally the function definition is a copy/paste of the declaration.</li>\n<li>(Minor remark) It would be clearer to write <code>int puzzle[9][9]</code> in the parameter list, even though it makes no practical difference. It gives self-documenting code, however.</li>\n<li>But you should entirely avoid \"magic numbers\" like <code>9</code> in your code. You should have <code>#define SUDOKU_SIZE 9</code> or such instead. This goes for all the divide by <code>3</code> statements too, it's not clear to the reader where the \"magic number\" 3 came from. This is where you would need to place a comment, since the code doesn't speak for itself.</li>\n<li><p>(Major issue) Your indention style is exotic and therefore wouldn't be tolerated in a professional setting. For example the line following an <code>if</code> or <code>for</code> etc should be placed on a line of its own, and also indented (2 or 4 spaces are ok):</p>\n\n<pre><code>for (int y = 0; y < 9; ++y)\n printf(\"|%d\", puzzle[x][y]);\n</code></pre>\n\n<p>For mission-critical programs, this style isn't tolerated either, but you need to always use <code>{ }</code> compound statements even if there is just a single line. </p></li>\n<li><p>(Minor remark) <code>int puzzle[9][9]</code> This could perhaps have been declared <code>const</code>, so you have one read-only table of the original data, and place the solution in a different matrix. You could then also have implemented <em>const correctness</em> for functions that do not modify this matrix. </p></li>\n<li><p>(Minor remark) Coding style preference - avoid using the <code>!</code> for operands that aren't boolean. Instead of <code>!puzzle[x][y]</code>, I'd write <code>puzzle[x][y]==0</code> since the purpose is to check if something is <code>0</code>, not <code>false</code>.</p></li>\n<li><p>Instead of returning <code>1</code>/<code>0</code> type <code>int</code>, you should be using <code>true</code>/<code>false</code> and <code>bool</code> from <code>stdbool.h</code>.</p></li>\n<li><p>(Minor remark) This <code>int main()</code> is obsolete style in C. You should be using <code>int main(void)</code> instead. (C and C++ are different here)</p></li>\n<li><p>(Minor remark) Your functions are pretty short so I'd say it is ok to <code>return</code> from multiple places inside them. For more complex functions, multiple returns from a function is sometimes frowned upon and it's preferred to only have a single return at the end. This is no black/white rule though. I say avoid multiple return statements <em>unless</em> it actually makes the code <em>more</em> readable. In your current program it's fine.</p></li>\n<li><p>The matrix print could be made a function of its own, to be called from main().</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T14:09:08.077",
"Id": "478151",
"Score": "1",
"body": "And for non-beginners: (Minor remark, advanced topic) As a micro-optimization, `int *row, int *column` could have been changed to `int * restrict row, int * restrict column` to clarify that these pointers won't alias and point at the same memory address. This might allow the compiler to produce ever so slightly faster code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T13:04:17.183",
"Id": "490610",
"Score": "0",
"body": "Feel free to add your comment as a separate section to the end of your answer. Comments come and go, only posts last forever ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T14:08:42.637",
"Id": "243609",
"ParentId": "243562",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "243609",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T14:37:32.803",
"Id": "243562",
"Score": "4",
"Tags": [
"c",
"sudoku",
"depth-first-search",
"backtracking"
],
"Title": "Sudoku solver using backtracting and depth-first-search"
}
|
243562
|
<p>I have a class called <code>IntMatrix</code> which has 2 fields:</p>
<pre><code>Dimensions dimensions;//To save height and width of my matrix
int *data;//For saving data
</code></pre>
<p>and I need to override the operators <code>>,>=,<,<=,==,!=</code> which take a scalar and compare each single value in my matrix with that scalar accordingly, and returns a new matrix with the same size that contains 1 if the comparison returned true and 0 else.</p>
<p><strong>For example:</strong></p>
<p>mat: {1,2,3;4,5,6}</p>
<p>mat_2 = mat > 3;//Should return {0,0,0;1,1,1}</p>
<p>So, you may notice that all my functions have the exact lines of code except whenever I wrote <code>!=</code> it should be <code>> or < or == or etc...</code>.</p>
<p>So, in order to remove duplication here's how I implemented them:</p>
<pre><code>IntMatrix IntMatrix::operator<(int num) const {
return filter(*this,Between(INT_MIN,num-1));
}
IntMatrix IntMatrix::operator>(int num) const {
return filter(*this,Between(num+1,INT_MAX));
}
IntMatrix IntMatrix::operator!=(int num) const {
return filter(*this,Between(num,num), true);
}
</code></pre>
<p>where <code>Between</code> is a functor (to replace a pointer to a function).</p>
<p>So, when I reviewed my code I strongly believe this is not the best solution to give to this kind of problem, since <code>filter()</code> won't be well understandable by other programmers.</p>
<p>From your experience is there anyway to improve this code?</p>
<p>(I know that macros would be perfect here but don't want to use them either since they are a bad practice)</p>
<p><strong>Note:</strong> I am working with <strong>C++11</strong> and want only to use standard libraries.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T22:22:14.397",
"Id": "478099",
"Score": "1",
"body": "Generally we like to see the whole class, both the header file and the C++ source file for the full context. It is very hard to provide a good review with only pieces of the code presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T05:14:40.243",
"Id": "478227",
"Score": "0",
"body": "Generally, you shouldn't make operators like `<` and `==` that return something else other than bool. It might cause issues on some level. In Matlab they have special bitwise operators but it will be hard to do in C++. Consider making functions instead of operators."
}
] |
[
{
"body": "<h1>Make use of the standard library</h1>\n\n<p>This looks like a job for <a href=\"https://en.cppreference.com/w/cpp/algorithm/transform\" rel=\"nofollow noreferrer\"><code>std::transform()</code></a>, which in many other languages would be the equivalent of the map function. It works on iterators, so it would help if your class provides <code>begin()</code> and <code>end()</code> functions, or if internally you store values in a <code>std::vector</code>. However, the <code>data</code> pointer can be used as well.</p>\n\n<p>Then, it's possible to write your operators like so:</p>\n\n<pre><code>#include <algorithm>\n\nIntMatrix IntMatrix::operator<(int num) const {\n IntMatrix result(width(), height()); // assuming this creates a matrix with the same dimensions\n const auto count = width() * height();\n std::transform(data, data + count, result.data,\n [num](int value){return value < num;});\n return result;\n}\n</code></pre>\n\n<p>With this, there is no need to write your own <code>filter()</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T00:22:12.023",
"Id": "478104",
"Score": "0",
"body": "Can't I fix this without using std::transform()? I am looking for personally written code, Anyway thanks for sharing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T05:57:24.520",
"Id": "478113",
"Score": "5",
"body": "@user225756 Why? Using the standard library is usually the preferred method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T20:50:44.157",
"Id": "478211",
"Score": "0",
"body": "It's like an assignment and I need to write my own code instead on using some libraries"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T20:55:33.027",
"Id": "478214",
"Score": "0",
"body": "In that case, consider creating a variant of `filter()` that takes a function as an argument, so that you can call it like so: `IntMatrix IntMatrix::operator<(int num) const { return filter(*this, [num](int value){return value < num;}); }`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T23:01:38.460",
"Id": "243580",
"ParentId": "243571",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T18:31:05.157",
"Id": "243571",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"c++11",
"functional-programming",
"overloading"
],
"Title": "C++ algorithm to implement multiple operators in one"
}
|
243571
|
<p>I want to share my raycasting source (the first engine:)</p>
<p>this program renders the game map (MAP array) and sprites (sprites_on_map array)</p>
<p>ask and criticize!</p>
<p>p.s I don't speak/write English very well (not my native language), but I tried to make the comments clear</p>
<p><a href="https://i.stack.imgur.com/Iq9G1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iq9G1.png" alt="enter image description here"></a> This is data/wall_1.bmp</p>
<p><a href="https://i.stack.imgur.com/2n17r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2n17r.png" alt="enter image description here"></a> This is data/sprite_1.bmp</p>
<pre><code>import pygame as p
import math as m
FOV, FOV_STEP, LENGHT_STEP, MAX_LENGHT = 1., .00375, .01, 50.
prespeed = .08 # explained in the wall_render method
rotate = .1
pspeed = .25
FPS = 30
WID, HEI = 320, 200
win = p.display.set_mode((WID, HEI), p.FULLSCREEN)
win.set_alpha(None)
p.event.set_allowed([])
dWID = 261 # game window width
dHEI = 161 # game window height
dWIDs = (WID - dWID) // 2 # game window start draw x
dHEIs = 10 # game window start draw y
mulHEI = 1.5 # wall size y
mulSPR_HEI = 1
sprite_max_size = 1000
FOV_STEP = FOV / (dWID + 1)
win.fill((50, 50, 50))
walls = {1 : 'data/wall_1.bmp'}
sprites = {1 : 'data/sprite_1.bmp'}
# if this is a multi-sided sprite : list of keys to image paths
# example:
# 1 : 'data/side1.bmp'
# 2 : 'data/side2.bmp'
# 3 : [1, 2]
# 3 is a multi-side sprite
animated_sprites = {} # key :
# [ frames ([sprite key1, sprite key2, ...]),
# loop (True/False),
# frame ( > 0, < len(frames)),
# speed (now_image = frames[int(frame + speed)])]
solid_sprites = [1]
### -------------------------------------------------------------------------------------- LEVEL
px, py, pa = 1.5, 2.5, 6.28 # player x + .5 , player y + .5 , player angle
sprites_on_map = {0 : [2.5, 2.5, 1]} # key : [x + .5, y + .5, key to sprite, if this is a multi-sided sprite : degree (radians)
MAP = [[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]] # keys from walls
roof_color, floor_color = (56, 56, 56), (112, 112, 112) # (R, G, B), (R, G, B)
### -------------------------------------------------------------------------------------- END LEVEL
redraw = True
p.mouse.set_visible(False)
p.mouse.set_pos((dWIDs + dWID // 2, dHEIs + dHEI // 2))
mouse_speed = .001
def moving(x, y, ang):
ystep = y + m.sin(ang) * pspeed
xstep = x + m.cos(ang) * pspeed
if MAP[int(ystep)][int(xstep)] == 0:
for i in sprites_on_map.keys():
sprite = sprites_on_map.get(i)
if sprite[2] in solid_sprites:
if int(sprite[0]) == int(xstep) and int(sprite[1]) == int(ystep):
return
return y + m.sin(ang) * pspeed, x + m.cos(ang) * pspeed
def wall_render(x, y, ang):
screen = [] # fow drawing
angle = ang - FOV / 2 # start of scan
while angle < pa + FOV / 2:
# the method of recalculating the beam (I've never heard of this, I thought of it myself :)
# the idea is that the beam goes at a speed of N and as soon as it collides
# with the wall goes 1 N back and continues to go at a speed of M (M < N) so you can get more quality
# so prespeed is N and LENGHT_STEP is M
Cang = m.cos(angle)
Sang = m.sin(angle)
rstep = prespeed # speed of ray (now N)
rfar = 0 # far of ray
obj = 0
while rfar < MAX_LENGHT:
rfar += rstep
rayy = y + Sang * rfar
rayx = x + Cang * rfar
obj = MAP[int(rayy)][int(rayx)]
if obj != 0: # if ray in wall then speed of ray is M
if rstep == prespeed:
rfar -= rstep
rstep = LENGHT_STEP
obj = 0
else:
break
if obj != 0:
xside = False
if MAP[int(rayy)][int(rayx - Cang * rstep)] ==\
MAP[int(rayy)][int(rayx + Cang * rstep)]:
# if the left side of the beam and the right side are the same wall, then this is the "x" side of the wall
xside = True
if xside:
# cut is the percentage for getting a slice of the wall (drawing a strip of wall)
if py > rayy : cut = 1 - rayx + int(rayx) # fix mirroring of the wall image
else : cut = rayx - int(rayx)
else:
if px < rayx : cut = 1 - rayy + int(rayy) # fix mirroring of the wall image
else : cut = rayy - int(rayy)
screen.append(['wall', rfar, angle - ang, obj, cut, xside]) # screen[0] is the type of object (2 types: wall/sprite)
# screen[1] is far to wall
# screen[2] is object (for draw) of wall
# screen[3] is cut
# screen[4] is side (for drawing the dark side of the wall)
angle += FOV_STEP
return screen
def sprite_render(sprites_on_map, drawed, x, y, ang):
screen = []
for i in sprites_on_map.keys():
sprite = sprites_on_map.get(i)
sprite_dist = m.sqrt((x - sprite[0]) * (x - sprite[0]) +
(y - sprite[1]) * (y - sprite[1])) # Pythagorean theorem
sprite_dir = m.atan2(sprite[1] - py, sprite[0] - px) - ang # you will need it to calculate the beginning of drawing by x
while sprite_dir < -3.14 : sprite_dir += 6.28
while sprite_dir > 3.14 : sprite_dir -= 6.28
sprite_size = min(sprite_max_size, dHEI / sprite_dist * mulHEI)
horizontal = (sprite_dir + FOV / 2) / FOV_STEP - sprite_size * dWID / dHEI / 2 + dWIDs # beginning of drawing by x
if horizontal + sprite_size * dWID / dHEI > dWIDs and horizontal < dWID + dWIDs:
start_scan = int(horizontal) - dWIDs if horizontal > dWIDs else 0 # sprite_draw_x_start
end_scan = int(horizontal + sprite_size * dWID / dHEI) - dWIDs if horizontal + sprite_size * dWID / dHEI < dWID + dWIDs else dWID # sprite_draw_x_end
# if the sprite is behind the wall, it is not visible, so you do not need to draw it, and this is calculated in the next "for"
can_add_sprite = False
for xx in drawed[start_scan:end_scan]:
if xx[0] == 'wall':
if xx[1] > sprite_dist: # if we can see this sprite : we draw it
can_add_sprite = True
break
if can_add_sprite:
vertical = dHEIs + (dHEI - sprite_size * mulSPR_HEI) / 2 # y position on screen of the sprite
obj = sprite[2]
if i in animated_sprites:
obj = animated_sprites.get(i)[0][int(animated_sprites.get(i)[2])]
if type(sprites.get(obj)) is list: # multi-sided sprites
degree = sprites_on_map.get(i)[3] - pa + .3925
while degree < 0 : degree += 6.28
while degree > 6.28 : degree -= 6.28
obj = sprites.get(obj)[int(degree / (6.28 / len(sprites.get(obj))))]
screen.append(['sprite', sprite_dist, horizontal, vertical, obj, sprite_size]) # screen[0] is the type of object (2 types: wall/sprite)
# screen[1] is the distantion to the sprite
# screen[2] is the x position on screen of the sprite
# screen[3] is the y position on screen of the sprite
# screen[4] is the size of the sprite
return screen
def rescreen(screen):
# (255, 0, 255) is the None color
win.set_alpha(None) # I've heard it makes the game faster)
old_path = None
for i in screen:
if i[0] == 'wall':
i.pop(0)
height = dHEI / (i[0] * m.cos(i[1])) * mulHEI
start_draw = 0 if height > dHEI else int(dHEI - height) // 2
start_cut = 0 if height < dHEI else (height - dHEI) / 2
end_cut = height if height < dHEI else dHEI
if old_path != walls.get(i[2]):
nimg = p.image.load(walls.get(i[2]))
old_path = walls.get(i[2])
img = p.transform.scale(nimg, (nimg.get_size()[0], int(height)))
if i[4]: # dark wall side
img.set_alpha(100)
p.draw.line(win,
(0, 0, 0),
(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, start_draw + dHEIs),
(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, start_draw + dHEIs + end_cut))
if start_draw != 0: # roof
p.draw.line(win,
roof_color,
(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, dHEIs),
(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, dHEIs + start_draw))
if end_cut != dHEI: # floor
p.draw.line(win,
floor_color,
(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, dHEIs + dHEI),
(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, dHEIs + end_cut + start_draw))
win.blit(img, # wall
img.get_rect(topleft=(int((i[1] + FOV / 2) / FOV_STEP) + dWIDs, start_draw + dHEIs)),
(nimg.get_size()[0] * i[3], start_cut, 1, end_cut + 1))
elif i[0] == 'sprite':
i.pop(0)
img = p.image.load(sprites.get(i[3]))
img.set_colorkey((255, 0, 255))
img = p.transform.scale(img, (int(i[4] * dWID / dHEI), int(i[4] * mulSPR_HEI)))
# all these calculations are necessary so that the sprite does not go beyond the screen
start_draw_x = dWIDs if i[1] < dWIDs else int(i[1])
start_draw_y = dHEIs if i[2] < dHEIs else int(i[2])
cut_xs = 0 if i[1] > dWIDs else dWIDs - i[1]
cut_ys = 0 if i[2] > dHEIs else dHEIs - i[2]
cut_xe = int(i[4] * dWID / dHEI) if start_draw_x + int(i[4] * dWID / dHEI) < dWID + dWIDs else dWIDs + dWID - start_draw_x + 1
cut_ye = int(i[4] * mulSPR_HEI) if start_draw_y + i[4] < dHEIs + dHEI else dHEIs + dHEI - start_draw_y
win.blit(img, # sprite draw
img.get_rect(topleft=(start_draw_x, start_draw_y)),
(cut_xs, cut_ys, cut_xe, cut_ye + 1))
p.display.update()
screen = wall_render(px, py, pa)
while True:
for e in p.event.get():
if e == p.QUIT:
break
p.time.delay(1000 // FPS) # wait
if p.key.get_pressed()[p.K_ESCAPE]:
break
if p.key.get_pressed()[p.K_LEFT]:
pa -= rotate
if pa < 3.14: pa = 9.42
redraw = True
if p.key.get_pressed()[p.K_RIGHT]:
pa += rotate
if pa > 9.42: pa = 3.14
redraw = True
if p.key.get_pressed()[p.K_UP] or p.key.get_pressed()[p.K_w]:
res = moving(px, py, pa)
if res is not None:
py, px = res
redraw = True
if p.key.get_pressed()[p.K_DOWN] or p.key.get_pressed()[p.K_s]:
res = moving(px, py, pa - 3.14)
if res is not None:
py, px = res
redraw = True
if p.key.get_pressed()[p.K_a]:
res = moving(px, py, pa - 1.57)
if res is not None:
py, px = res
redraw = True
if p.key.get_pressed()[p.K_d]:
res = moving(px, py, pa + 1.57)
if res is not None:
py, px = res
redraw = True
if p.mouse.get_pos() != (dWIDs + dWID // 2, dHEIs + dHEI // 2): # mouse looking
pa -= (dWIDs + dWID // 2 - p.mouse.get_pos()[0]) * mouse_speed
if pa < 3.14: pa = 9.42
if pa > 9.42: pa = 3.14
redraw = True
p.mouse.set_pos((dWIDs + dWID // 2, dHEIs + dHEI // 2))
if animated_sprites != {}:
fdel = [] # to delete an animation
for i in animated_sprites.keys():
sprite = animated_sprites.get(i)
sprite[2] += sprite[3]
if int(sprite[2]) >= len(sprite[0]):
if sprite[1]:
animated_sprites.get(i)[2] = 0
else:
sprite[2] -= sprite[3]
fdel.append(i)
else:
animated_sprites.get(i)[2] = sprite[2]
if not redraw:
# should we redraw everything?
if int(sprite[2] - sprite[3]) != int(sprite[2]) or sprite[2] == 0:
if sprite_render({i:sprites_on_map.get(i)},wall_render(px, py, pa),px,py,pa) != []:
# yes, hell, we should
redraw = True
for i in fdel: # delete animations
del animated_sprites[i]
if redraw:
redraw = False
screen = wall_render(px, py, pa) # wall rendering
screen += sprite_render(sprites_on_map, screen, px, py, pa) # sprite rendering
# the painter's algorithm
screen.sort(key=lambda x: x[1])
screen = screen[::-1]
rescreen(screen) # redraw
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T19:08:52.097",
"Id": "478091",
"Score": "2",
"body": "Hey Koliqa, whilst I appreciate the effort that went into the comments, could you please [edit] your question to add a short description on what you're raycasting. For example is it a cube or another basic shape, or is it more complex like a scene or a game? Once you've added this information please ping me and I'll help clean up your description :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T12:43:53.920",
"Id": "478255",
"Score": "0",
"body": "@Peilonrayz , I've re-released everything and made changes to the code (mostly in terms of comments), I'm still open to questions and criticism:) P.S I forgot to clarify: this is a rendering of the game"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T18:33:36.503",
"Id": "243572",
"Score": "2",
"Tags": [
"python",
"pygame",
"raycasting"
],
"Title": "Raycasting python (pyagame)"
}
|
243572
|
<p>Task: Rowset of all reachable(in any direction) nodes from any node in a graph. In other words I need to extract all nodes of a particular graph from a table in the database where graph specified by an id of any one graph node. The final goal is a map in the app.</p>
<p>Table structure of <code>DocumentDependency</code> is simple as:</p>
<pre><code>descendant_id | predecessor_id
-------------------------------
2857 | 2856
2858 | 2856
2859 | 2856
2859 | 2857
2860 | 2859
2861 | 2859
</code></pre>
<p>Finally I came up with CTE:</p>
<pre><code>WITH RECURSIVE DocumentGraph AS
(
SELECT
CASE WHEN predecessor_id = 2858 THEN descendant_id ELSE predecessor_id END AS anchor_id,
ARRAY[ROW(predecessor_id, descendant_id)] path,
1 depth
FROM
DocumentDependency
WHERE
2858 in (descendant_id, predecessor_id)
UNION ALL
SELECT
CASE WHEN DocumentDependency.predecessor_id = DocumentGraph.anchor_id THEN DocumentDependency.descendant_id ELSE DocumentDependency.predecessor_id END,
path || ROW(DocumentDependency.predecessor_id, DocumentDependency.descendant_id) path,
depth + 1
FROM
DocumentGraph
JOIN DocumentDependency ON
DocumentGraph.anchor_id in (DocumentDependency.predecessor_id, DocumentDependency.descendant_id)
AND
ROW(DocumentDependency.predecessor_id, DocumentDependency.descendant_id) <> ALL(path)
)
</code></pre>
<p>There are a lot discussions about directed graphs and this is sort of a compilation from stack* and one useful book<sup>1</sup>, but I'm experiencing an overdose and what I need is criticism.</p>
<ol>
<li>Maybe this is generally an inappropriate approach? =)</li>
<li>Lightweight? (What if DocumentDependency will have 500k rows?)</li>
<li>Portability? (for now I'm using PostgreSQL12)</li>
<li>Simplicity? (I'm under custom ORM and need to extend for ROWS/ARRAYS/CTE support but probably there is a way to avoid using arrays?)</li>
</ol>
<hr>
<p><sup>1</sup><sub>Joe Celko's Trees and Hierarchies in SQL For Smarties (highly recommended, btw ;)</sub></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:53:34.313",
"Id": "478177",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>I am not well qualified to answer this, as I know nothing of PostgreSQL or the RECURSIVE extension you are using, so unfortunately I cannot very well comment on your solution.</p>\n\n<p>However perhaps it can be tackled with (relatively!) standard SQL. Let's define a temporary table </p>\n\n<pre><code>CREATE TABLE #Temp ( id int, status int )\n</code></pre>\n\n<p>A status of 1 will indicate the node is reachable, but it has not yet been processed, a status of 2 indicates the node is reachable, and all immediate descendants have been added. We initialise by inserting the starting node ( I think in your example it is 2858 ).</p>\n\n<pre><code>INSERT INTO #temp ( id, status ) VALUES ( 2858, 1 )\n</code></pre>\n\n<p>Now we can set up a loop to insert all the reachable nodes:</p>\n\n<pre><code>DECLARE @x int \nWHILE 1 = 1\nBEGIN\n SELECT @x = -1 -- Some value that is not a valid node id\n SELECT @x = id FROM #Temp WHERE Status = 1\n IF @x = -1 BREAK -- All reachable nodes processed.\n\n INSERT INTO #temp( id, status ) \n SELECT descendant_id, 1 \n FROM DocumentDependency WHERE predecessor_id = @x\n AND descendant_id NOT in ( SELECT id FROM #Temp )\n\n UPDATE #temp SET status = 2 WHERE id = @x\nEND\n</code></pre>\n\n<p>When the loop terminates, #Temp should contain all the reachable node ids. Provided suitable indexes are defined, I think this should be reasonably efficient. As a variation, you could perhaps process multiple nodes with status 1 on each iteration of the loop, I will leave that as an exercise ( you may need an extra status value to differentiate between nodes that have just been added and nodes that are being processed ). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T12:25:39.953",
"Id": "243601",
"ParentId": "243574",
"Score": "3"
}
},
{
"body": "<p>Based on the nearly the same idea from Celko's book I came up with another version without arrays&rows but still using common table expression.</p>\n\n<pre><code>WITH RECURSIVE DocumentGraph AS\n(\n SELECT DISTINCT\n document1_id document2_id,\n 0 depth,\n '/2856' path\n\n FROM DocumentCyclicDependency\n\n WHERE\n document1_id = 2856\n\n UNION ALL\n\n SELECT\n document_dependency.document2_id,\n document_graph.depth + 1,\n document_graph.path || '/' || document_dependency.document2_id\n\n FROM\n DocumentCyclicDependency AS document_dependency,\n DocumentGraph AS document_graph\n\n WHERE\n document_graph.document2_id = document_dependency.document1_id\n AND\n document_graph.path NOT LIKE '%' || document_dependency.document2_id || '%'\n)\n\nSELECT document2_id, depth, path\nFROM DocumentGraph\n</code></pre>\n\n<p>DocumentCyclicDependency is actually a tricky view: </p>\n\n<pre><code>CREATE VIEW DocumentCyclicDependency(document1_id, document2_id) AS\n\n SELECT descendant_id, predecessor_id FROM DocumentDependency\n\n UNION ALL\n\n SELECT predecessor_id, descendant_id FROM DocumentDependency;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T17:45:39.850",
"Id": "243626",
"ParentId": "243574",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T19:41:41.670",
"Id": "243574",
"Score": "3",
"Tags": [
"sql",
"graph",
"postgresql"
],
"Title": "Fetching all nodes of a directed graph by an id of any node"
}
|
243574
|
<h1>Intro</h1>
<p>I've been working to implement a modified version of the <code>achemso.bst</code> file from the American Chemical Society's<a href="https://ctan.org/pkg/achemso?lang=en" rel="nofollow noreferrer"><code>achemso</code> package</a> that properly implements patents as defined by the ACS Style Guide.</p>
<p>This is the first time that I've worked in a meaningful way with BibTeX Style files and while I am presently happy with the result - I really want to have someone take a look over the final code and jsut check for glaring or stupid mistakes.</p>
<h1>Main Control Function</h1>
<p>In general, the changes that I would like to have reviewed are best shown by the following definition.</p>
<pre><code>FUNCTION { patent } {
begin.bibitem
format.authors
format.assignees
format.title
format.type.number.patent
format.date
format.CAS
format.note
end.bibitem
}
</code></pre>
<p>That is, the BST file adds a definition for handling patents. To do this, I have added the functions format.assignees, format.date, format.type.number.patent and format.CAS. All other format. functions are as defined in the orignal <code>achemso.bst</code> file.</p>
<p>Additionally, the <code>begin.bibitem</code> and <code>end.bibitem</code> have been modified to wrap the entire entry in an <code>\href{}{}</code> wrapper if a url is present.</p>
<h1>Added/Modified Functions</h1>
<p><strong>All of the added/modified functions, in order of my uncertainty in the implementation of them.</strong></p>
<h2>format.CAS function</h2>
<p>This function constructs the Chemcial Abstract reference line at the end of the bibtex entry. It checks if both the <code>CAS_CAN</code> and <code>CAS_AN</code> exists. It then constructs the output string by adding the appropriate elements from left to right.</p>
<pre><code>FUNCTION { format.CAS } {
CAS_CAN duplicate$ empty$ not
{
CAS_AN duplicate$ empty$ not
{
"Chem. Abstr. " emph swap$
"AN " "" find.replace
#1 #4 substring$
add.comma bold
*
swap$
"CAN " "" find.replace
":" ",} " find.replace
"\emph{" swap$ *
*
output
}
{ pop$ }
if$
}
{ pop$ }
if$
}
</code></pre>
<h2>Modifed <code>begin.bibitem</code> and <code>end.bibitem</code> functions</h2>
<p>This section modifies the <code>begin.bibitem</code> and <code>end.bibitem</code> definitions to include a <code>\href{}{}</code> wrapper.</p>
<pre><code>INTEGERS { href.present.bool }
FUNCTION { begin.bibitem } {
newline$
"\bibitem" write$
label
calculate.full.names
duplicate$
short.names =
{ pop$ }
{ * }
if$
"[" swap$ * "]" * write$
"{" cite$ * "}" * write$
newline$
url empty$ not
'href.present.bool :=
href.present.bool
{"\href{" url * "}{" * write$}
{ }
if$
""
next.punct.comma 'next.punct.int :=
}
FUNCTION { end.bibitem } {
would.add.period
{
href.present.bool
{ "}" * }
{ }
if$
"\relax" * write$
newline$
"\mciteBstWouldAddEndPuncttrue" write$
newline$
"\mciteSetBstMidEndSepPunct{\mcitedefaultmidpunct}" write$
newline$
"{\mcitedefaultendpunct}{\mcitedefaultseppunct}\relax"
}
{
href.present.bool
{ "}" * }
{ }
if$
"\relax" * write$
newline$
"\mciteBstWouldAddEndPunctfalse" write$
newline$
"\mciteSetBstMidEndSepPunct{\mcitedefaultmidpunct}" write$
newline$
"{}{\mcitedefaultseppunct}\relax"
}
if$
write$
newline$
"\EndOfBibitem" write$
}
</code></pre>
<h2>format.assignees function</h2>
<p>This function pushes the assignee value to the stack, checks if is empty, then if not, formats it and outputs. Formatting includes changing <code> AND</code> to <code>;</code>, and ensureing that the value is wrapped in parens.</p>
<pre><code>FUNCTION { format.assignees } {
assignee duplicate$ empty$
{ pop$ }
{ " AND" ";" find.replace.upper
duplicate$
duplicate$
#-1 #1 substring$
")" =
#1 #1 substring$
"(" =
and
{ paren }
{ }
if$
output
next.punct.period 'next.punct.int :=
}
if$
}
</code></pre>
<h2>format.type.number.patent function</h2>
<p>This function, and its helper function format the patent type and number, and output them.</p>
<pre><code>FUNCTION { format.type.patent } {
type empty$
{ "Patent" }{ type }
if$ output
}
FUNCTION { format.type.number.patent } {
number empty$
{ }
{
format.type.patent " " number * * output
next.punct.comma 'next.punct.int :=
}
if$
}
</code></pre>
<h2>Helper Functions</h2>
<p>These are helper functions that are necesary for some of the above function to work correctly. I think that they are sufficent for this use case as is, but any improvements are appreciated.</p>
<pre><code>% From : https://tex.stackexchange.com/a/28104
% Originally from: http://ctan.org/pkg/tamethebeast
INTEGERS{ l }
FUNCTION{ string.length }
{ #1 'l :=
{ duplicate$ duplicate$ #1 l substring$ = not }
{ l #1 + 'l := }
while$
pop$ l
}
STRINGS{replace find text}
INTEGERS{find_length}
FUNCTION{find.replace}
{ 'replace :=
'find :=
'text :=
find string.length 'find_length :=
""
{ text empty$ not }
{ text #1 find_length substring$ find =
{ replace *
text #1 find_length + global.max$ substring$ 'text :=
}
{ text #1 #1 substring$ *
text #2 global.max$ substring$ 'text :=
}
if$
}
while$
}
% new code
FUNCTION{find.replace.upper}
{ 'replace :=
'find :=
'text :=
find string.length 'find_length :=
""
{ text empty$ not }
{ text #1 find_length substring$ "u" change.case$ find =
{ replace *
text #1 find_length + global.max$ substring$ 'text :=
}
{ text #1 #1 substring$ *
text #2 global.max$ substring$ 'text :=
}
if$
}
while$
}
FUNCTION{find.replace.ignorecase}
{ swap$
"u" change.case$
swap$
find.replace.upper
}
</code></pre>
<hr />
<h1>Full BibTeX Style Definition</h1>
<p>All of the above code are held in a single BST file, as</p>
<pre><code>% Notes: this is an editied version of the ``achemso.bst'' file, used to develop the patent entry type based off of the specification of the ACS Style Guide (3rd ed. pp 310-311)
ENTRY
{
abstract
address
assignee
author
booktitle
CODEN
CAS_AN
CAS_CAN
chapter
ctrl-article-title
ctrl-chapter-title
ctrl-doi
ctrl-etal-firstonly
ctrl-etal-number
ctrl-use-title
date
day
doi
edition
editor
howpublished
institution
journal
key
maintitle
month
note
number
organization
pages
publisher
school
series
title
type
url
version
volume
year
}
{ }
{
label
short.names
}
% Generic logic functions, from the core BibTeX styles
FUNCTION { and } {
{ }
{
pop$
#0
}
if$
}
FUNCTION { not } {
{ #0 }
{ #1 }
if$
}
FUNCTION { or } {
{
pop$
#1
}
{ }
if$
}
FUNCTION { xor } {
{ not }
{ }
if$
}
% Generic functions for basic manipulations: many of these
% come from the core BibTeX styles or 'Tame the BeaST'
FUNCTION { chr.to.value.error } {
#48 +
int.to.chr$
"'" swap$ *
"'" *
" is not a number: treated as zero." *
warning$
#0
}
FUNCTION { chr.to.value } {
chr.to.int$ #48 -
duplicate$
#0 <
{ chr.to.value.error }
{
duplicate$
#9 >
{ chr.to.value.error }
{ }
if$
}
if$
}
STRINGS {
extract.input.str
extract.output.str
}
FUNCTION { is.a.digit } {
duplicate$
"" =
{
pop$
#0
}
{
chr.to.int$
#48 -
duplicate$
#0 < swap$ #9 > or not
}
if$
}
FUNCTION{ is.a.number } {
{
duplicate$
#1 #1 substring$
is.a.digit
}
{ #2 global.max$ substring$ }
while$
"" =
}
FUNCTION { extract.number } {
duplicate$
'extract.input.str :=
"" 'extract.output.str :=
{ extract.input.str empty$ not }
{
extract.input.str #1 #1 substring$
extract.input.str #2 global.max$ substring$ 'extract.input.str :=
duplicate$
is.a.number
{ extract.output.str swap$ * 'extract.output.str := }
{
pop$
"" 'extract.input.str :=
}
if$
}
while$
extract.output.str empty$
{ }
{
pop$
extract.output.str
}
if$
}
FUNCTION { field.or.null } {
duplicate$
empty$
{
pop$
""
}
{ }
if$
}
INTEGERS {
multiply.a.int
multiply.b.int
}
FUNCTION { multiply } {
'multiply.a.int :=
'multiply.b.int :=
multiply.b.int #0 <
{
#-1
#0 multiply.b.int - 'multiply.b.int :=
}
{ #1 }
if$
#0
{ multiply.b.int #0 > }
{
multiply.a.int +
multiply.b.int #1 - 'multiply.b.int :=
}
while$
swap$
{ }
{ #0 swap$ - }
if$
}
INTEGERS { str.conversion.int }
FUNCTION { str.to.int.aux.ii } {
{
duplicate$
empty$ not
}
{
swap$
#10 multiply 'str.conversion.int :=
duplicate$
#1 #1 substring$
chr.to.value
str.conversion.int +
swap$
#2 global.max$ substring$
}
while$
pop$
}
FUNCTION { str.to.int.aux.i } {
duplicate$
#1 #1 substring$
"-" =
{
#1 swap$
#2 global.max$ substring$
}
{
#0 swap$
}
if$
#0
swap$
str.to.int.aux.ii
swap$
{ #0 swap$ - }
{ }
if$
}
FUNCTION { str.to.int } {
duplicate$
empty$
{
pop$
#0
}
{ str.to.int.aux.i }
if$
}
FUNCTION { tie.or.space.connect } {
duplicate$
text.length$ #3 <
{ "~" }
{ " " }
if$
swap$ * *
}
FUNCTION { yes.no.to.bool } {
duplicate$
empty$
{
pop$
#0
}
{
"l" change.case$
"yes" =
{ #1 }
{ #0 }
if$
}
if$
}
% Functions of formatting
FUNCTION { bold } {
duplicate$
empty$
{
pop$
""
}
{ "\textbf{" swap$ * "}" * }
if$
}
FUNCTION { emph } {
duplicate$
empty$
{
pop$
""
}
{ "\emph{" swap$ * "}" * }
if$
}
FUNCTION { paren } {
duplicate$
empty$
{
pop$
""
}
{ "(" swap$ * ")" * }
if$
}
% Functions for punctuation
FUNCTION { add.comma } { ", " * }
FUNCTION { add.colon } { ": " * }
FUNCTION { add.period } { add.period$ " " * }
FUNCTION { add.semicolon } { "; " * }
FUNCTION { add.space } { " " * }
% Bibliography strings: fixed values collected into functions
FUNCTION { bbl.and } { "and" }
FUNCTION { bbl.chapter } { "Chapter" }
FUNCTION { bbl.doi } { "DOI:" }
FUNCTION { bbl.editor } { "Ed." }
FUNCTION { bbl.editors } { "Eds." }
FUNCTION { bbl.edition } { "ed." }
FUNCTION { bbl.etal } { "\latin{et~al.}" }
FUNCTION { bbl.in } { "In" }
FUNCTION { bbl.inpress } { "in press" }
FUNCTION { bbl.msc } { "M.Sc.\ thesis" }
FUNCTION { bbl.page } { "p" }
FUNCTION { bbl.pages } { "pp" }
FUNCTION { bbl.phd } { "Ph.D.\ thesis" }
FUNCTION { bbl.version } { "version" }
FUNCTION { bbl.volume } { "Vol." }
% Functions for number formatting
STRINGS { pages.str }
FUNCTION { hyphen.to.dash } {
'pages.str :=
""
{ pages.str empty$ not }
{
pages.str #1 #1 substring$
"-" =
{
"--" *
{
pages.str #1 #1 substring$
"-" =
}
{ pages.str #2 global.max$ substring$ 'pages.str := }
while$
}
{
pages.str #1 #1 substring$
*
pages.str #2 global.max$ substring$ 'pages.str :=
}
if$
}
while$
}
INTEGERS { multiresult.bool }
FUNCTION { multi.page.check } {
'pages.str :=
#0 'multiresult.bool :=
{
multiresult.bool not
pages.str empty$ not
and
}
{
pages.str #1 #1 substring$
duplicate$
"-" = swap$ duplicate$
"," = swap$
"+" =
or or
{ #1 'multiresult.bool := }
{ pages.str #2 global.max$ substring$ 'pages.str := }
if$
}
while$
multiresult.bool
}
% Functions for calculating the label data needed by natbib
INTEGERS {
current.name.int
names.separate.comma
names.separate.semicolon
names.separate.comma.bool
remaining.names.int
total.names.int
}
STRINGS {
current.name.str
names.str
}
FUNCTION { full.format.names } {
'names.str :=
#1 'current.name.int :=
names.str num.names$ 'remaining.names.int :=
{ remaining.names.int #0 > }
{
names.str current.name.int "{vv~}{ll}" format.name$
current.name.int #1 >
{
swap$ add.comma swap$
remaining.names.int #1 >
{ }
{
duplicate$
"others" =
{ bbl.etal }
{ bbl.and }
if$
add.space swap$ *
}
if$
*
}
{ }
if$
remaining.names.int #1 - 'remaining.names.int :=
current.name.int #1 + 'current.name.int :=
}
while$
}
FUNCTION { full.author } {
author empty$
{ "" }
{ author full.format.names }
if$
}
FUNCTION { full.author.editor } {
author empty$
{
editor empty$
{ "" }
{ editor full.format.names }
if$
}
{ author full.format.names }
if$
}
FUNCTION { full.editor } {
editor empty$
{ "" }
{ editor full.format.names }
if$
}
FUNCTION { short.format.names } {
'names.str :=
names.str #1 "{vv~}{ll}" format.name$
names.str num.names$
duplicate$
#2 >
{
pop$
add.space bbl.etal *
}
{
#2 <
{ }
{
names.str #2 "{ff }{vv }{ll}{ jj}" format.name$
"others" =
{ add.space bbl.etal * }
{
add.space
bbl.and add.space
*
names.str #2 "{vv~}{ll}" format.name$
*
}
if$
}
if$
}
if$
}
FUNCTION { short.author.key } {
author empty$
{
key empty$
{ cite$ #1 #3 substring$ }
{ key }
if$
}
{ author short.format.names }
if$
}
FUNCTION { short.author.editor.key } {
author empty$
{
editor empty$
{
key empty$
{ cite$ #1 #3 substring$ }
{ key }
if$
}
{ editor short.format.names }
if$
}
{ author short.format.names }
if$
}
FUNCTION { short.author.key.organization } {
author empty$
{
key empty$
{
organization empty$
{ cite$ #1 #3 substring$ }
{
organization #1 #4 substring$
"The " =
{ organization }
{ organization #5 global.max$ substring$ }
if$
#3 text.prefix$
}
if$
}
{ key }
if$
}
{ author short.format.names }
if$
}
FUNCTION { short.editor.key.organization } {
editor empty$
{
key empty$
{
organization empty$
{ cite$ #1 #3 substring$ }
{
organization #1 #4 substring$
"The " =
{ organization }
{ organization #5 global.max$ substring$ }
if$
#3 text.prefix$
}
if$
}
{ key }
if$
}
{ editor short.format.names }
if$
}
FUNCTION { calculate.full.names } {
type$ "book" =
type$ "inbook" =
or
{ full.author.editor }
{
type$ "proceedings" =
{ full.editor }
{ full.author }
if$
}
if$
}
FUNCTION { calculate.short.names } {
type$ "book" =
type$ "inbook" =
or
{ short.author.editor.key }
{
type$ "proceedings" =
{ short.editor.key.organization }
{
type$ "manual" =
{ short.author.key.organization }
{ short.author.key }
if$
}
if$
}
if$
'short.names :=
}
FUNCTION { calculate.names } {
calculate.short.names
short.names
year empty$
{ "()" }
{ "(" year * ")" * }
if$
*
'label :=
}
% Counting up the number of entries
INTEGERS { entries.int }
FUNCTION { initialize.count.entries } {
#0 'entries.int :=
}
FUNCTION { count.entries } {
entries.int #1 + 'entries.int :=
}
% Start and end of bibliography functions
FUNCTION { begin.bib } {
"achemso 2019-02-14 v3.12a" top$
preamble$ empty$
{ }
{
preamble$ write$
newline$
}
if$
"\providecommand{\latin}[1]{#1}" write$
newline$
"\makeatletter" write$
newline$
"\providecommand{\doi}" write$
newline$
" {\begingroup\let\do\@makeother\dospecials" write$
newline$
" \catcode`\{=1 \catcode`\}=2 \doi@aux}" write$
newline$
"\providecommand{\doi@aux}[1]{\endgroup\texttt{#1}}" write$
newline$
"\makeatother" write$
newline$
"\providecommand*\mcitethebibliography{\thebibliography}" write$
newline$
"\csname @ifundefined\endcsname{endmcitethebibliography}" write$
" {\let\endmcitethebibliography\endthebibliography}{}" write$
newline$
"\begin{mcitethebibliography}{"
entries.int int.to.str$ * "}" * write$
newline$
"\providecommand*\natexlab[1]{#1}" write$
newline$
"\providecommand*\mciteSetBstSublistMode[1]{}" write$
newline$
"\providecommand*\mciteSetBstMaxWidthForm[2]{}" write$
newline$
"\providecommand*\mciteBstWouldAddEndPuncttrue" write$
newline$
" {\def\EndOfBibitem{\unskip.}}" write$
newline$
"\providecommand*\mciteBstWouldAddEndPunctfalse" write$
newline$
" {\let\EndOfBibitem\relax}" write$
newline$
"\providecommand*\mciteSetBstMidEndSepPunct[3]{}" write$
newline$
"\providecommand*\mciteSetBstSublistLabelBeginEnd[3]{}" write$
newline$
"\providecommand*\EndOfBibitem{}" write$
newline$
"\mciteSetBstSublistMode{f}" write$
newline$
"\mciteSetBstMaxWidthForm{subitem}{(\alph{mcitesubitemcount})}" write$
newline$
"\mciteSetBstSublistLabelBeginEnd" write$
newline$
" {\mcitemaxwidthsubitemform\space}" write$
newline$
" {\relax}" write$
newline$
" {\relax}" write$
newline$
}
FUNCTION { end.bib } {
newline$
"\end{mcitethebibliography}" write$
newline$
}
% Functions used for the special "control" entry type, to pass data
% from LaTeX to BibTeX
INTEGERS {
ctrl.article.title.bool
ctrl.chapter.title.bool
ctrl.doi.bool
ctrl.etal.firstonly.bool
ctrl.etal.number.int
}
FUNCTION { initialize.control.values } {
#1 'ctrl.article.title.bool :=
#0 'ctrl.chapter.title.bool :=
#0 'ctrl.doi.bool :=
#1 'ctrl.etal.firstonly.bool :=
#15 'ctrl.etal.number.int :=
}
FUNCTION { control } {
ctrl-article-title yes.no.to.bool 'ctrl.article.title.bool :=
ctrl-chapter-title yes.no.to.bool 'ctrl.chapter.title.bool :=
ctrl-doi yes.no.to.bool 'ctrl.doi.bool :=
ctrl-etal-firstonly yes.no.to.bool 'ctrl.etal.firstonly.bool :=
ctrl-etal-number str.to.int 'ctrl.etal.number.int :=
ctrl-use-title empty$
'skip$
{ ctrl-use-title yes.no.to.bool 'ctrl.article.title.bool := }
if$
}
% Functions of each bibitem: tracking punctuation and transferring
% items to the .bbl file
INTEGERS {
next.punct.comma
next.punct.period
next.punct.semicolon
next.punct.space
}
FUNCTION { initialize.tracker } {
#0 'next.punct.comma :=
#1 'next.punct.period :=
#2 'next.punct.semicolon :=
#3 'next.punct.space :=
}
INTEGERS { next.punct.int }
FUNCTION { output } {
swap$
duplicate$ empty$
{ pop$ }
{
next.punct.int next.punct.space =
{ add.space }
{
next.punct.int next.punct.comma =
{ add.comma }
{
next.punct.int next.punct.semicolon =
{ add.semicolon }
{ add.period }
if$
}
if$
}
if$
write$
}
if$
next.punct.comma 'next.punct.int :=
}
%<Edited>
INTEGERS { href.present.bool }
% Functions for each bibliography entry: start and finish
FUNCTION { begin.bibitem } {
newline$
"\bibitem" write$
label
calculate.full.names
duplicate$
short.names =
{ pop$ }
{ * }
if$
"[" swap$ * "]" * write$
"{" cite$ * "}" * write$
newline$
url empty$ not
'href.present.bool :=
href.present.bool
{"\href{" url * "}{" * write$}
{ }
if$
""
next.punct.comma 'next.punct.int :=
}
INTEGERS { add.period.length.int }
FUNCTION { would.add.period } {
duplicate$
add.period$
text.length$ 'add.period.length.int :=
duplicate$
text.length$
add.period.length.int =
{ #0 }
{ #1 }
if$
}
FUNCTION { end.bibitem } {
would.add.period
{
href.present.bool
{ "}" * }
{ }
if$
"\relax" * write$
newline$
"\mciteBstWouldAddEndPuncttrue" write$
newline$
"\mciteSetBstMidEndSepPunct{\mcitedefaultmidpunct}" write$
newline$
"{\mcitedefaultendpunct}{\mcitedefaultseppunct}\relax"
}
{
href.present.bool
{ "}" * }
{ }
if$
"\relax" * write$
newline$
"\mciteBstWouldAddEndPunctfalse" write$
newline$
"\mciteSetBstMidEndSepPunct{\mcitedefaultmidpunct}" write$
newline$
"{}{\mcitedefaultseppunct}\relax"
}
if$
write$
newline$
"\EndOfBibitem" write$
}
%<!Edited>
% Formatting names: authors and editors are not quite the same,
% and there is the question of how to handle 'et al.'
FUNCTION { initialize.name.separator } {
#1 'names.separate.comma :=
#0 'names.separate.semicolon :=
}
FUNCTION { format.names.loop } {
{ remaining.names.int #0 > }
{
names.str current.name.int "{vv~}{ll,}{~f.}{,~jj}" format.name$
duplicate$
'current.name.str :=
current.name.int #1 >
{
duplicate$
"others," =
{
pop$
*
bbl.etal
add.space
remaining.names.int #1 - 'remaining.names.int :=
}
{
swap$
names.separate.comma.bool
{ add.comma }
{ add.semicolon }
if$
%<*bio>
% remaining.names.int #1 >
% { }
% { bbl.and add.space * }
% if$
%</bio>s
swap$
*
}
if$
}
{ }
if$
remaining.names.int #1 - 'remaining.names.int :=
current.name.int #1 + 'current.name.int :=
}
while$
}
FUNCTION { format.names.all } {
total.names.int 'remaining.names.int :=
format.names.loop
}
FUNCTION { format.names.etal } {
ctrl.etal.firstonly.bool
{ #1 'remaining.names.int := }
{ ctrl.etal.number.int 'remaining.names.int := }
if$
format.names.loop
current.name.str "others," =
{ }
{
add.space
bbl.etal
add.space
*
}
if$
}
FUNCTION { format.names } {
'names.separate.comma.bool :=
'names.str :=
#1 'current.name.int :=
names.str num.names$ 'total.names.int :=
total.names.int ctrl.etal.number.int >
{
ctrl.etal.number.int #0 =
{ format.names.all }
{ format.names.etal }
if$
}
{ format.names.all }
if$
}
%<Added>
% From : https://tex.stackexchange.com/a/28104
% Originally from: http://ctan.org/pkg/tamethebeast
INTEGERS{ l }
FUNCTION{ string.length }
{
#1 'l :=
{duplicate$ duplicate$ #1 l substring$ = not}
{l #1 + 'l :=}
while$
pop$ l
}
STRINGS{replace find text}
INTEGERS{find_length}
FUNCTION{find.replace}
{ 'replace :=
'find :=
'text :=
find string.length 'find_length :=
""
{ text empty$ not }
{ text #1 find_length substring$ find =
{
replace *
text #1 find_length + global.max$ substring$ 'text :=
}
{ text #1 #1 substring$ *
text #2 global.max$ substring$ 'text :=
}
if$
}
while$
}
% new code
FUNCTION{find.replace.upper}
{ 'replace :=
'find :=
'text :=
find string.length 'find_length :=
""
{ text empty$ not }
{ text #1 find_length substring$ "u" change.case$ find =
{
replace *
text #1 find_length + global.max$ substring$ 'text :=
}
{ text #1 #1 substring$ *
text #2 global.max$ substring$ 'text :=
}
if$
}
while$
}
FUNCTION{find.replace.ignorecase}
{ swap$
"u" change.case$
swap$
find.replace.upper
}
% if assignee is not empty then check replace and w/ `;`. then check if it is parened. if not paren
FUNCTION { format.assignees } {
assignee duplicate$ empty$
{ pop$ }
{ " AND" ";" find.replace.upper
duplicate$
duplicate$
#-1 #1 substring$
")" =
#1 #1 substring$
"(" =
and
{ paren }
{ }
if$
output
next.punct.period 'next.punct.int :=
}
if$
}
FUNCTION { format.CAS } {
CAS_CAN duplicate$ empty$ not
{
CAS_AN duplicate$ empty$ not
{
"Chem. Abstr. " emph swap$
"AN " "" find.replace
#1 #4 substring$
add.comma bold
*
swap$
"CAN " "" find.replace
":" ",} " find.replace
"\emph{" swap$ *
*
output
}
{ pop$ }
if$
}
{ pop$ }
if$
}
%</Added>
% Converting editions into their fixed representations
FUNCTION { bbl.first } { "1st" }
FUNCTION { bbl.second } { "2nd" }
FUNCTION { bbl.third } { "3rd" }
FUNCTION { bbl.fourth } { "4th" }
FUNCTION { bbl.fifth } { "5th" }
FUNCTION { bbl.st } { "st" }
FUNCTION { bbl.nd } { "nd" }
FUNCTION { bbl.rd } { "rd" }
FUNCTION { bbl.th } { "th" }
STRINGS {
ord.input.str
ord.output.str
}
FUNCTION { make.ordinal } {
duplicate$
"1" swap$
*
#-2 #1 substring$
"1" =
{
bbl.th *
}
{
duplicate$
#-1 #1 substring$
duplicate$
"1" =
{
pop$
bbl.st *
}
{
duplicate$
"2" =
{
pop$
bbl.nd *
}
{
"3" =
{ bbl.rd * }
{ bbl.th * }
if$
}
if$
}
if$
}
if$
}
FUNCTION { convert.to.ordinal } {
extract.number
"l" change.case$ 'ord.input.str :=
ord.input.str "first" = ord.input.str "1" = or
{ bbl.first 'ord.output.str := }
{
ord.input.str "second" = ord.input.str "2" = or
{ bbl.second 'ord.output.str := }
{
ord.input.str "third" = ord.input.str "3" = or
{ bbl.third 'ord.output.str := }
{
ord.input.str "fourth" = ord.input.str "4" = or
{ bbl.fourth 'ord.output.str := }
{
ord.input.str "fifth" = ord.input.str "5" = or
{ bbl.fifth 'ord.output.str := }
{
ord.input.str #1 #1 substring$
is.a.number
{ ord.input.str make.ordinal }
{ ord.input.str }
if$
'ord.output.str :=
}
if$
}
if$
}
if$
}
if$
}
if$
ord.output.str
}
% Functions for each type of entry
FUNCTION { format.address } {
address empty$
{ }
{
address
output
}
if$
}
FUNCTION { format.authors } {
author empty$
{ }
{
%<*bio>
% author names.separate.comma format.names
%</bio>
%<*!bio>
author names.separate.semicolon format.names
%</!bio>
output
next.punct.space 'next.punct.int :=
}
if$
}
FUNCTION { format.editors } {
editor empty$
{ }
{
editor names.separate.comma format.names
add.comma
editor num.names$ #1 >
{ bbl.editors }
{ bbl.editor }
if$
*
output
next.punct.semicolon 'next.punct.int :=
}
if$
}
FUNCTION { format.authors.or.editors } {
author empty$
{ format.editors }
{ format.authors }
if$
next.punct.space 'next.punct.int :=
}
FUNCTION { format.chapter } {
chapter empty$
{ }
{
bbl.chapter add.space
chapter
*
output
}
if$
}
FUNCTION { format.doi } {
doi empty$
'skip$
{
bbl.doi add.space
"\doi{" * doi * "}" *
output
}
if$
}
FUNCTION { format.edition } {
edition empty$
{ }
{
edition convert.to.ordinal
add.space bbl.edition *
output
}
if$
next.punct.semicolon 'next.punct.int :=
}
FUNCTION { format.group.address } {
duplicate$
empty$
{ pop$ }
{
address empty$
{ }
{
add.colon
address
*
}
if$
output
}
if$
}
FUNCTION { format.howpublished } {
howpublished empty$
{ }
{
howpublished
output
}
if$
}
FUNCTION { format.journal } {
journal emph
output
next.punct.space 'next.punct.int :=
}
FUNCTION { format.journal.unpub } { journal emph output }
FUNCTION { format.note } { note empty$ { }{ note output } if$ }
FUNCTION { format.number.series } {
series empty$
{ }
{
series
number empty$
{ }
{
add.space
number *
}
if$
output
next.punct.semicolon 'next.punct.int :=
}
if$
}
FUNCTION { format.organization } {
organization empty$
{ }
{
organization paren
output
next.punct.period 'next.punct.int :=
}
if$
}
FUNCTION { format.organization.address } { organization format.group.address }
FUNCTION { format.pages } {
pages empty$
{ }
{
pages multi.page.check
{
bbl.pages
pages hyphen.to.dash
}
{ bbl.page pages }
if$
tie.or.space.connect
output
}
if$
ctrl.doi.bool
{ format.doi }
'skip$
if$
}
FUNCTION { format.pages.article } {
pages empty$
{ }
{
pages hyphen.to.dash
output
}
if$
ctrl.doi.bool
{ format.doi }
'skip$
if$
}
FUNCTION { format.publisher.address } {
publisher format.group.address
}
FUNCTION { format.school.address } {
school
duplicate$
empty$
{ pop$ }
{
address empty$
{ }
{
add.comma
address
*
}
if$
output
}
if$
}
FUNCTION { format.title } {
title empty$
{ }
{
title
output
next.punct.period 'next.punct.int :=
}
if$
}
FUNCTION { format.title.article } {
ctrl.article.title.bool
{
title empty$
{ }
{
title
output
next.punct.period 'next.punct.int :=
}
if$
}
{ }
if$
}
FUNCTION { format.title.techreport } {
title empty$
{ }
{
title emph
output
next.punct.semicolon 'next.punct.int :=
}
if$
}
FUNCTION { format.title.booktitle } {
title empty$
{ }
{
title
output
next.punct.period 'next.punct.int :=
}
if$
booktitle empty$
{ }
{
booktitle
output
next.punct.period 'next.punct.int :=
}
if$
}
STRINGS {
book.title
chapter.title
}
FUNCTION { format.title.booktitle.book } {
"" 'chapter.title :=
booktitle empty$
{
"" 'chapter.title :=
title 'book.title :=
}
{
ctrl.chapter.title.bool
{
title empty$
'skip$
{ title 'chapter.title := }
if$
}
'skip$
if$
maintitle empty$
{ booktitle 'book.title := }
{ maintitle add.period booktitle * 'book.title := }
if$
}
if$
chapter.title empty$
{ }
{
chapter.title
output
next.punct.period 'next.punct.int :=
}
if$
book.title emph
chapter.title empty$
{
author empty$
{ }
{
editor empty$
{ }
{ bbl.in add.space swap$ * }
if$
}
if$
}
{ bbl.in add.space swap$ * }
if$
output
}
FUNCTION { format.type } {
type empty$
{ }
{
pop$
type
}
if$
output
}
FUNCTION { format.type.number } {
type empty$
{ }
{
number empty$
{ }
{
type
number tie.or.space.connect
*
output
}
if$
}
if$
}
FUNCTION { format.type.patent } {
type empty$
{ "Patent" }{ type }
if$ output
}
FUNCTION { format.type.number.patent } {
number empty$
{ }{
format.type.patent " " number * * output
next.punct.comma 'next.punct.int :=
}
if$
}
FUNCTION { format.url } {
url empty$
{ }
{
"\url{" url * "}" *
output
}
if$
}
FUNCTION { format.year } {
year empty$
{ }
{
year
output
next.punct.semicolon 'next.punct.int :=
}
if$
}
STRINGS { sYear sMonth sDay d}
INTEGERS { iYear iMonth iDay }
FUNCTION { format.date } {
"" 'sYear :=
"" 'sMonth :=
"" 'sDay :=
date empty$ not
{ % if the date is note empty, then
% split the date into year month and day
date #1 #4 substring$ 'sYear :=
date #6 #2 substring$ 'sMonth :=
date #9 #2 substring$ 'sDay :=
% remove leading zero from sMonth and sDay iff leading zeros exist
sMonth #1 #1 substring$ "0" = { sMonth #2 #1 substring$ 'sMonth := }{ } if$
sDay #1 #1 substring$ "0" = { sDay #2 #1 substring$ 'sDay := }{ } if$
}{ % else, gather values from appropriate fields
year empty$ not {year }{""}if$ 'sYear :=
month empty$ not {month}{""}if$ 'sMonth :=
day empty$ not {day }{""}if$ 'sDay :=
} if$
% Convert sMonth from number string to abbreviated month
sMonth "1" = sMonth "01" = or { "Jan" 'sMonth := }{ } if$
sMonth "2" = sMonth "02" = or { "Feb" 'sMonth := }{ } if$
sMonth "3" = sMonth "03" = or { "March" 'sMonth := }{ } if$
sMonth "4" = sMonth "04" = or { "April" 'sMonth := }{ } if$
sMonth "5" = sMonth "05" = or { "May" 'sMonth := }{ } if$
sMonth "6" = sMonth "06" = or { "June" 'sMonth := }{ } if$
sMonth "7" = sMonth "07" = or { "July" 'sMonth := }{ } if$
sMonth "8" = sMonth "08" = or { "Aug" 'sMonth := }{ } if$
sMonth "9" = sMonth "09" = or { "Sept" 'sMonth := }{ } if$
sMonth "10" = { "Oct" 'sMonth := }{ } if$
sMonth "11" = { "Nov" 'sMonth := }{ } if$
sMonth "12" = { "Dec" 'sMonth := }{ } if$
sYear empty$ not {
sMonth empty$ not {
sMonth sDay empty$ not {" " sDay *}{ "" }if$ ", " * *
}{ "" }if$
sYear * output
}{}if$
next.punct.semicolon 'next.punct.int :=
}
FUNCTION { format.year.article } {
year empty$
{ }
{
%<*bio>
% year paren
% output
% next.punct.space 'next.punct.int :=
%</bio>
%<*!bio>
year bold
output
%</!bio>
}
if$
}
FUNCTION { format.version } {
version empty$
{ }
{
bbl.version add.space
version
*
output
}
if$
}
FUNCTION { format.volume.article } {
volume emph
output
}
FUNCTION { format.volume } {
volume empty$
{ }
{
bbl.volume
volume
tie.or.space.connect
output
next.punct.semicolon 'next.punct.int :=
}
if$
}
% The functions to deal with each entry type
FUNCTION { article } {
begin.bibitem
format.authors
%<*bio>
% format.year.article
%</bio>
format.title.article
format.journal
%<*!bio>
format.year.article
%</!bio>
format.volume.article
format.pages.article
format.note
end.bibitem
}
FUNCTION { book } {
begin.bibitem
format.authors.or.editors
format.title.booktitle.book
format.edition
author empty$
{ }
{ format.editors }
if$
format.number.series
format.publisher.address
format.year
format.volume
format.chapter
format.pages
format.note
end.bibitem
}
FUNCTION { inbook } { book }
FUNCTION { booklet } {
begin.bibitem
format.authors
format.title
format.howpublished
format.address
format.year
format.note
end.bibitem
}
FUNCTION { collection } { book }
FUNCTION { incollection } { book }
FUNCTION { inpress } {
begin.bibitem
format.authors
%<*bio>
% format.year.article
%</bio>
format.journal.unpub
doi empty$
{
bbl.inpress
output
}
{
%<*!bio>
format.year.article
%</!bio>
next.punct.comma 'next.punct.int :=
format.doi
}
if$
format.note
end.bibitem
}
FUNCTION { inproceedings } {
begin.bibitem
format.authors
format.title.booktitle
format.address
format.year
format.pages
format.note
end.bibitem
}
FUNCTION { manual } {
begin.bibitem
format.authors
format.title
format.version
format.organization.address
format.year
format.note
end.bibitem
}
FUNCTION { mastersthesis } {
begin.bibitem
format.authors
format.title
bbl.msc format.type
format.school.address
format.year
format.note
end.bibitem
}
FUNCTION { misc } {
begin.bibitem
format.authors
format.title
format.howpublished
format.year
format.url
format.note
end.bibitem
}
FUNCTION { patent } {
begin.bibitem
format.authors
format.assignees
format.title
format.type.number.patent
format.date
format.CAS
format.note
end.bibitem
}
FUNCTION { phdthesis } {
begin.bibitem
format.authors
format.title
bbl.phd format.type
format.school.address
format.year
format.note
end.bibitem
}
FUNCTION { proceeding } {
begin.bibitem
format.title
format.address
format.year
format.pages
format.note
end.bibitem
}
FUNCTION { techreport } {
begin.bibitem
format.authors.or.editors
format.title.techreport
format.type.number
format.organization.address
format.year
format.volume
format.pages
format.note
end.bibitem
}
FUNCTION { unpublished } {
begin.bibitem
format.authors
format.journal.unpub
doi empty$
{ format.howpublished }
{
format.year
next.punct.comma 'next.punct.int :=
format.doi
}
if$
format.note
end.bibitem
}
FUNCTION { default.type } { misc }
% Macros containing pre-defined short cuts
% patent macros per the biblatex documentaion
% See page 283 of http://mirrors.ibiblio.org/CTAN/macros/latex/contrib/biblatex/doc/biblatex.pdf
MACRO { patent } { "Patent" }
MACRO { patentau } { "Au. Patent" }
MACRO { patentuk } { "Br. Patent" }
MACRO { patenteu } { "Eur. Patent" }
MACRO { patentfr } { "Fr. Patent" }
MACRO { patentde } { "Ger. Offen." } % seen in acs reference - maybe short for "offensichtlich"; a possible translation of patent
MACRO { patentus } { "U.S. Patent" }
% patent requests
MACRO { patapp } { "Patent Appl." }
MACRO { patappau } { "Au. Pat. Appl." }
MACRO { patappuk } { "Br. Pat. Appl." }
MACRO { patappeu } { "Eur. Pat. Appl." }
MACRO { patappfr } { "Fr. Pat. Appl." }
MACRO { patappde } { "Ger. Pat. Appl." }
MACRO { patappjp } { "kōkai tokkyo kōhō" }
MACRO { patappus } { "U.S. Pat. Appl." }
% alias using biblatex style abbreviations
MACRO { patreq } { "Patent Appl." }
MACRO { patreqde } { "Ger. Pat. Appl." }
MACRO { patreqeu } { "Eur. Pat. Appl." }
MACRO { patreqfr } { "Fr. Pat. Appl." }
MACRO { patrequk } { "Br. Pat. Appl." }
MACRO { patrequs } { "U.S. Pat. Appl." }
% Corrected in accordance with ACS Style guide, 3rd ed, pp. 161
MACRO { jan } { "Jan" }
MACRO { feb } { "Feb" }
MACRO { mar } { "March" }
MACRO { apr } { "April" }
MACRO { may } { "May" }
MACRO { jun } { "June" }
MACRO { jul } { "July" }
MACRO { aug } { "Aug" }
MACRO { sep } { "Sept" }
MACRO { oct } { "Oct" }
MACRO { nov } { "Nov" }
MACRO { dec } { "Dec" }
MACRO { acbcct } { "ACS Chem.\ Biol." }
MACRO { achre4 } { "Acc.\ Chem.\ Res." }
MACRO { acncdm } { "ACS Chem.\ Neurosci." }
MACRO { ancac3 } { "ACS Nano" }
MACRO { ancham } { "Anal.\ Chem." }
MACRO { bichaw } { "Biochemistry" }
MACRO { bcches } { "Bioconjugate Chem." }
MACRO { bomaf6 } { "Biomacromolecules" }
MACRO { bipret } { "Biotechnol.\ Prog." }
MACRO { crtoec } { "Chem.\ Res.\ Toxicol." }
MACRO { chreay } { "Chem.\ Rev." }
MACRO { cmatex } { "Chem.\ Mater." }
MACRO { cgdefu } { "Cryst.\ Growth Des." }
MACRO { enfuem } { "Energy Fuels" }
MACRO { esthag } { "Environ.\ Sci.\ Technol." }
MACRO { iechad } { "Ind.\ Eng.\ Chem.\ Res." }
MACRO { inoraj } { "Inorg.\ Chem." }
MACRO { jafcau } { "J.~Agric.\ Food Chem." }
MACRO { jceaax } { "J.~Chem.\ Eng.\ Data" }
MACRO { jceda8 } { "J.~Chem.\ Ed." }
MACRO { jcisd8 } { "J.~Chem.\ Inf.\ Model." }
MACRO { jctcce } { "J.~Chem.\ Theory Comput." }
MACRO { jcchff } { "J. Comb. Chem." }
MACRO { jmcmar } { "J. Med. Chem." }
MACRO { jnprdf } { "J. Nat. Prod." }
MACRO { joceah } { "J.~Org.\ Chem." }
MACRO { jpcafh } { "J.~Phys.\ Chem.~A" }
MACRO { jpcbfk } { "J.~Phys.\ Chem.~B" }
MACRO { jpccck } { "J.~Phys.\ Chem.~C" }
MACRO { jpclcd } { "J.~Phys.\ Chem.\ Lett." }
MACRO { jprobs } { "J.~Proteome Res." }
MACRO { jacsat } { "J.~Am.\ Chem.\ Soc." }
MACRO { langd5 } { "Langmuir" }
MACRO { mamobx } { "Macromolecules" }
MACRO { mpohbp } { "Mol.\ Pharm." }
MACRO { nalefd } { "Nano Lett." }
MACRO { orlef7 } { "Org.\ Lett." }
MACRO { oprdfk } { "Org.\ Proc.\ Res.\ Dev." }
MACRO { orgnd7 } { "Organometallics" }
% Construction of bibliography: reading of data, construction of
% labels, output of formatted bibliography
READ
EXECUTE { initialize.control.values }
EXECUTE { initialize.count.entries }
EXECUTE { initialize.name.separator }
EXECUTE { initialize.tracker }
ITERATE { calculate.names }
ITERATE { count.entries }
EXECUTE { begin.bib }
ITERATE { call.type$ }
EXECUTE { end.bib }
%</bst>
</code></pre>
<hr />
<h2>Python Conversion Tool</h2>
<p>This short program takes in a file containing one or more SciFinder References in the <code>Tagged Format (.txt)</code> format, and converts it into a BibTeX entry compatable with the bibtex style above.</p>
<pre class="lang-py prettyprint-override"><code>r"""Simple sctipt to convert Scifinder refernces for patents into bibtex entries for my customized acspat.bst bibtex style.
note: acspat.bst complies with the ACS format as outlined by The ACS Style Guide, 3rd Edition
usage
python "c:\...\cas2bibtex.py" "c:\...\ref.txt" > "c:\...\ref.bib"
"""
import sys
import re
import inspect
import httplib2
import pycountry
from datetime import datetime
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from pylatexenc import latexencode
# method to convert patents to bibtex
def convert_Patent(fields):
"""Convert the passed dictionary from SciFinder `Tagged Format (*.txt)` to Custom @Patent bibtex entry
Args:
fields (dict): dictionary verions of Scifinder CAS reference sheet
"""
assert isinstance(fields, dict)
assert fields["Document Type"]=="Patent"
# ACS spec uses the application date, not publishing date
# pub_date = datetime.strptime(fields["Publication Date"],"%Y%m%d")
app_date = datetime.strptime(fields["Patent Application Date"],"%Y%m%d")
print()
# print(pycountry.countries.get(name=str(fields["Patent Assignee"]).replace(r"\(.*\)","").title()))
# construct a google patent url from the text file data
google_pat_url =("https://patents.google.com/patent/" +
fields["Patent Country"].strip() +
fields["Patent Number"].strip() +
fields["Patent Kind Code"].strip())
# check if the url is valid, if not, ditch it. store result as url
url = google_pat_url if int(httplib2.Http().request(google_pat_url, "HEAD")[0]["status"])<400 else ''
bib_str = inspect.cleandoc(
# Key, abstract and keywords - stuf to make finding the right doc easier when writing
r"""@Patent{{{citation_key},
abstract = {{{abstract}}},
keywords = {{{keywords}}},
"""
# Basic Publication Info
r"""author = {{{author}}},
assignee = {{{assignee}}},
title = {{{title}}},
date = {{{date}}},
year = {{{year}}},
month = {{{month}}},
day = {{{day}}},
"""
# Document info
r"""pages = {{{pages}}},
language = {{{language}}},
"""
# patent-specific info
r"""type = {{{patent_type}}},
number = {{{patent_number}}},
"""
# Search-related info
r"""CODEN = {{{CODEN}}},
CAS_AN = {{{accession_number}}},
CAS_CAN = {{{chemical_abstracts_number}}},
url = {{{url}}}
}}""".format(
citation_key = fields["Inventor Name"].split(maxsplit=1)[0].replace(',','') +
app_date.strftime("%Y"),
abstract = latexencode.unicode_to_latex(fields["Abstract"].strip()),
# abstract = fields["Abstract"],
keywords = fields["Index Terms"],
author = fields["Inventor Name"].replace('; '," and "),
assignee = fields["Patent Assignee"] if
pycountry.countries.get(name=fields["Patent Assignee"].strip('()'))==None
else '',
title = latexencode.unicode_to_latex(fields["Title"]).title(),
date = app_date.strftime("%Y-%m-%d"),
year = app_date.strftime("%Y"),
month = app_date.strftime("%m"),
day = app_date.strftime("%d"),
pages = fields["Page"],
language = fields["Language"],
patent_type = fields["Journal Title"]+'.', # this holds the abbreviation for patent type
# period added as this an abbreviation; this is an exception
patent_number = fields["Patent Number"],
CODEN = fields["CODEN"],
accession_number = fields["Accession Number"],
chemical_abstracts_number = fields["Chemical Abstracts Number(CAN)"],
url = fields["URL"] if fields["URL"] != '' else url # use the cas specified url, if it exists, else use the url selected above
))
return(bib_str)
# Main method - runs at execution-time
def main():
""" Check if any command-line arguments for what files to look at are passed,
if not, prompt user for what files to use
Assert that the file is of the appropriate scifinder format
extract records, and one by one, convert those records to the bibtex entries
using `convert_Patent()`
"""
if len(sys.argv)<2:
tk = Tk()
tk.withdraw()
tk.call('wm', 'attributes', '.', '-topmost', True)
files = askopenfilename(title="Choose File(s) to Convert",multiple=True)
else:
files = sys.argv[1:]
# Define patterns to seek out the records
rec_pattern = r"""START_RECORD\n # Begins with start record
(?P<Fields>.+?) # Capture as few lines as possible between
END_RECORD""" # Ends with End Record
fld_pattern = r"""FIELD\s # Begins with
(?P<Key>.+?)\: # Capture the key (everything before the `:` - newlines excluded)
(?P<Def>.+?)?\.? # Capture the definition (everything after the `:` - trailing periods excluded)
\n""" # Ends with a non-optional newline
# Compile the patterns into regex objects
rec_regex = re.compile(rec_pattern, re.VERBOSE | re.MULTILINE | re.DOTALL)
fld_regex = re.compile(fld_pattern, re.VERBOSE | re.MULTILINE)
# iter over all passed files
for filePath in files:
# open and read the file into memory
file = open(filePath)
fileTxt = file.read()
file.close()
# find records using regexp and iter over them
for record in rec_regex.findall(fileTxt):
# convert the records into dicts
fields = dict(fld_regex.findall(record))
# decision tree for converting based off of doc type
# print result with intention that this can be used
# at the shell and piped into a file
if fields["Document Type"]=="Patent":
print(convert_Patent(fields))
else:
print("Attempted to covert file: {}\nHowever, document type <{}> is yet not supported".format(
filePath, fields["Document Type"]))
# Force auto-run of main
if __name__ == "__main__": main()
</code></pre>
<p><a href="https://pastebin.com/1FapdFE4" rel="nofollow noreferrer">Sample Input</a></p>
<p><a href="https://pastebin.com/J3xtkzzK" rel="nofollow noreferrer">Sample Output</a></p>
<h1>Output</h1>
<p><strong>Expected Output</strong></p>
<p>From The ACS Style Guide 3rd Ed., 310-311, patents are expected to presented as</p>
<p><strong>Recommended Format:</strong></p>
<p>Patent Owner 1; Patent Owner 2; etc. Title of Patent. Patent Number, Date.</p>
<p><strong>Examples:</strong></p>
<ol>
<li><p>Sheem, S. K. Low-Cost Fiber Optic Pressure Sensor. U.S. Patent 9,738,537, May 18, 2004.</p>
</li>
<li><p>Lenssen, K. C.; Jantscheff, P.; Kiedrowski, G.; Massing, U. Cationic Lipids With Serine Backbone for Transfecting Biological Molecules.Eu. Pat. Appl. 1457483, 2004.</p>
</li>
<li><p>Langhals, H.; Wetzel, F.; Perylene Pigments with Metallic Effects. Ger. Offen. DE 10357978.8, Dec 11, 2013; <em>Chem. Abstr.</em> <strong>2005,</strong> <em>143,</em> 134834.</p>
</li>
<li><p>Shimizu, Y.; Kajiyama, H. (Kanebo, Ltd., Japan; Kanebo Synthetic Fibers, Ltd.). Jpn. Kokai Tokkyo Koho JP 2004176197 A2 20040624, 2004.</p>
</li>
</ol>
<p><strong>Actual Output</strong></p>
<p>Using the code above in latex, and data from Scifinder converted to BibTeX using the Python Script, below, the same patents (excluding the 3rd, which was not present in the SciFinder Database), produce the following citations</p>
<p><a href="https://i.stack.imgur.com/g1XyY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g1XyY.png" alt="Actual Output" /></a></p>
<p><a href="https://www.overleaf.com/read/xrvsfwykxbrz" rel="nofollow noreferrer">Take a look at the MWE that generated this on Overleaf</a></p>
<hr />
<h1>Discussion</h1>
<p>It would seem that there are a fair number of inconsistencies with the data available from the SciFinder database, when compared to the expeced values.</p>
<p>Most Concerningly - the date which is cited according to the style guide is inconsistent. For <a href="https://patents.google.com/patent/EP1457483A1" rel="nofollow noreferrer">Examples 2</a> and <a href="https://patents.google.com/patent/JP2004176197A" rel="nofollow noreferrer">5</a> In the guide, the publication date is cited, for <a href="https://patents.google.com/patent/BR9904502A" rel="nofollow noreferrer">3</a> and <a href="https://patents.google.com/patent/DE10357978A1" rel="nofollow noreferrer">4</a> the application date is used. <a href="https://patents.google.com/patent/US6597820B1" rel="nofollow noreferrer">Example 1</a> appears to use a completely unrelated date.</p>
<p>As a result of this I decided to use the publication date for all of my citations, but if anyone can provide me with guidance as to why the dates are varying and how I might programmatically address this, I would be very appreciative of this.</p>
<p><em>Other Concerns</em></p>
<p>In the BibTeX Style File, the Definitions for <code>format.assignees</code> and <code>format.CAS</code> both use the <code>find.replace</code> function or a variant of this. This function ends up adding quite a few steps onto each citation generation, and I am concerned that this my significantly negatively affect proformence with large bibliographies. How might this be improved?</p>
<p>In the Python script below, the <code>latexencode.unicode_to_latex(...)</code> function sometimes incorrectly converts inputs - for instance the character gamma (<span class="math-container">\$\gamma\$</span>) is not properly handled to the expected <code>\gamma</code> - is there a better alternative for converting unicode to latex?</p>
<p>Are there any resources that you woudl suggest for working with BST files (asside from <a href="http://tug.ctan.org/info/bibtex/tamethebeast/ttb_en.pdf" rel="nofollow noreferrer">Tame the BeaST</a>)? Documentation on the format is quite scarce.</p>
<p>Are there any other general improvements that you might suggest?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:57:57.287",
"Id": "478523",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<p>A good first step is always to look at the BibTeX output and trying to resolve all the errors that appear. In your case, I get</p>\n<blockquote>\n<pre><code>This is BibTeX, Version 0.99d (TeX Live 2020)\nThe top-level auxiliary file: main.aux\nThe style file: acspat.bst\nDatabase file #1: ref.bib\nachemso 2019-02-14 v3.12a\n1 is an integer literal, not a string, for entry Sheem1997\nwhile executing---line 1932 of file acspat.bst\nYou can't pop an empty literal stack for entry Sheem1997\nwhile executing---line 1932 of file acspat.bst\n1 is an integer literal, not a string, for entry Lenssen2003\nwhile executing---line 1932 of file acspat.bst\nYou can't pop an empty literal stack for entry Lenssen2003\nwhile executing---line 1932 of file acspat.bst\nYou can't pop an empty literal stack for entry Langhals2003\nwhile executing---line 1932 of file acspat.bst\n1 is an integer literal, not a string, for entry Shimizu2002\nwhile executing---line 1932 of file acspat.bst\nYou can't pop an empty literal stack for entry Shimizu2002\nwhile executing---line 1932 of file acspat.bst\n(There were 7 error messages)\n</code></pre>\n</blockquote>\n<p>That's a lot of repetition, but basically BibTeX reports two issues for every entry:</p>\n<pre><code>1 is an integer literal, not a string, for entry Sheem1997\nwhile executing---line 1932 of file acspat.bst\nYou can't pop an empty literal stack for entry Sheem1997\nwhile executing---line 1932 of file acspat.bst\n</code></pre>\n<p>Where are these coming from? The <code>1 is an integer literal</code> is caused by</p>\n<pre><code>FUNCTION { format.assignees } {\n assignee duplicate$ empty$\n { pop$ }\n { " AND" ";" find.replace.upper\n duplicate$\n duplicate$\n #-1 #1 substring$\n ")" = % <--------- After this comparison, a `1` (which represents "true" is at the top of the stack\n % not the string you duplicated earlier\n #1 #1 substring$\n "(" =\n and\n { paren }\n { }\n if$\n output\n next.punct.period 'next.punct.int := \n }\n if$ \n}\n</code></pre>\n<p>To fix this, add a <code>swap$</code> between <code>")" =</code> and <code>#1 #1 substring$</code> to get the string above the number (aka boolean) again.</p>\n<p>This leaves the "You can't pop an empty literal stack". Look at</p>\n<pre><code>FUNCTION { format.type.patent } {\n type empty$\n { "Patent" }{ type }\n if$ output\n}\n\nFUNCTION { format.type.number.patent } {\n number empty$\n { }\n {\n format.type.patent " " number * * output\n next.punct.comma 'next.punct.int :=\n }\n if$\n}\n</code></pre>\n<p>Especially the line</p>\n<pre><code>format.type.patent " " number * * output\n</code></pre>\n<p>This tries to concatenate " " and number to the string left on the stack by <code>format.type.patent</code>, but because <code>format.type.patent</code> ends with <code>output</code>, the string is no longer on the stack but already printed.</p>\n<p>To fix this, change <code>format.type.patent</code> to</p>\n<pre><code>FUNCTION { format.type.patent } {\n type empty$\n { "Patent" }{ type }\n if$\n}\n</code></pre>\n<p>to avoid the premature output. (You might want to rename the function name because it no longer behaves like the other <code>format.</code> functions)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:31:44.703",
"Id": "478511",
"Score": "0",
"body": "Absolutely fantastic - I had been developing this on Overleaf and was completely unaware that there even was a BibTeX output file. I've implemented both of the changes you have suggested. Thank you :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:33:03.183",
"Id": "478527",
"Score": "0",
"body": "Just as a note on this answer, in implenting the change to `format.assignees` the code segment `and { paren } { } if$` should be changed to `and { } { paren } if$` because I had my logic backwards"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:08:01.183",
"Id": "243775",
"ParentId": "243576",
"Score": "5"
}
},
{
"body": "<h2>Fix for Latex Encoding</h2>\n<p>Thank you to <a href=\"https://chat.stackexchange.com/users/31162/david-carlisle\">David Carlisle</a> for helping me figure out this one.</p>\n<p>The problems encoding <span class=\"math-container\">\\$\\gamma\\$</span> and similar unicode characters arrives not from the <code>latexencode.unicode_to_latex(...)</code> function, but rather from reading in the files incorrectly. Rather than using <code>open(filePath)</code>, <code>open(filePath,encoding="utf-8")</code> should be used to ensure that the unicode characters are read in properly.</p>\n<p>Additionally, this unicode conversion should be applied to the <code>keywords</code> field as this may also contain unicode characters, as shown by the Langhals Example.</p>\n<p>When implemented, this renders a python file, <code>cas2bibtex.py</code> of the form</p>\n \n<pre class=\"lang-py prettyprint-override\"><code>r"""Simple sctipt to convert Scifinder refernces for patents into bibtex entries for my customized acspat.bst bibtex style. \n\n note: acspat.bst complies with the ACS format as outlined by The ACS Style Guide, 3rd Edition\n\n usage \n python "c:\\...\\cas2bibtex.py" "c:\\...\\ref.txt" > "c:\\...\\ref.bib"\n"""\n\nimport sys\nimport re\nimport inspect\nimport httplib2\nimport pycountry \nfrom datetime import datetime\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\nfrom pylatexenc import latexencode\n\n# method to convert patents to bibtex\ndef convert_Patent(fields):\n """Convert the passed dictionary from SciFinder `Tagged Format (*.txt)` to Custom @Patent bibtex entry\n\n Args:\n fields (dict): dictionary verions of Scifinder CAS reference sheet\n """\n\n assert isinstance(fields, dict)\n assert fields["Document Type"]=="Patent"\n\n # ACS spec uses application and publication date interchangably. I am not sure which to use, so the code for both is provided below.\n pub_date = datetime.strptime(fields["Publication Date"],"%Y%m%d")\n app_date = datetime.strptime(fields["Patent Application Date"],"%Y%m%d")\n\n # construct a google patent url from the text file data\n google_pat_url =("https://patents.google.com/patent/" + \n fields["Patent Country"].strip() + \n fields["Patent Number"].strip() + \n fields["Patent Kind Code"].strip())\n\n # check if the url is valid, if not, ditch it. store result as url\n url = google_pat_url if int(httplib2.Http().request(google_pat_url, "HEAD")[0]["status"])<400 else ''\n\n bib_str = inspect.cleandoc(\n # Key, abstract and keywords - stuf to make finding the right doc easier when writing\n r"""@Patent{{{citation_key},\n abstract = {{{abstract}}},\n keywords = {{{keywords}}},\n """\n # Basic Publication Info \n r"""author = {{{author}}},\n assignee = {{{assignee}}},\n title = {{{title}}},\n date = {{{date}}},\n year = {{{year}}},\n month = {{{month}}},\n day = {{{day}}},\n """\n # Document info\n r"""pages = {{{pages}}},\n language = {{{language}}},\n """\n # patent-specific info\n r"""type = {{{patent_type}}},\n number = {{{patent_number}}}, \n """\n # Search-related info\n r"""CODEN = {{{CODEN}}},\n CAS_AN = {{{accession_number}}},\n CAS_CAN = {{{chemical_abstracts_number}}}, \n url = {{{url}}}\n }}""".format(\n citation_key = fields["Inventor Name"].split(maxsplit=1)[0].replace(',','') +\n app_date.strftime("%Y"), \n abstract = latexencode.unicode_to_latex(fields["Abstract"].strip()),\n keywords = latexencode.unicode_to_latex(fields["Index Terms"]),\n author = fields["Inventor Name"].replace('; '," and "),\n assignee = fields["Patent Assignee"] if \n pycountry.countries.get(name=fields["Patent Assignee"].strip('()'))==None\n else '',\n title = latexencode.unicode_to_latex(fields["Title"]).title(),\n\n date = app_date.strftime("%Y-%m-%d"),\n year = app_date.strftime("%Y"),\n month = app_date.strftime("%m"),\n day = app_date.strftime("%d"), \n \n pages = fields["Page"],\n language = fields["Language"],\n\n patent_type = fields["Journal Title"] # this holds the abbreviation for patent type\n + '.' if str(fields["Journal Title"]).find('.') > 0 else '',\n # period added if the entry is a period - subject to change\n patent_number = fields["Patent Number"],\n \n CODEN = fields["CODEN"],\n accession_number = fields["Accession Number"],\n chemical_abstracts_number = fields["Chemical Abstracts Number(CAN)"],\n\n url = fields["URL"] if fields["URL"] != '' else url # use the cas specified url, if it exists, else use the url selected above\n ))\n\n return(bib_str)\n\n# Main method - runs at execution-time\ndef main():\n """ Check if any command-line arguments for what files to look at are passed, \n if not, prompt user for what files to use\n\n Assert that the file is of the appropriate scifinder format\n\n extract records, and one by one, convert those records to the bibtex entries \n using `convert_Patent()`\n """\n\n if len(sys.argv)<2:\n tk = Tk()\n tk.withdraw()\n tk.call('wm', 'attributes', '.', '-topmost', True)\n files = askopenfilename(title="Choose File(s) to Convert",multiple=True)\n else:\n files = sys.argv[1:]\n\n # Define patterns to seek out the records\n rec_pattern = r"""START_RECORD\\n # Begins with start record\n (?P<Fields>.+?) # Capture as few lines as possible between \n END_RECORD""" # Ends with End Record\n fld_pattern = r"""FIELD\\s # Begins with \n (?P<Key>.+?)\\: # Capture the key (everything before the `:` - newlines excluded)\n (?P<Def>.+?)?\\.? # Capture the definition (everything after the `:` - trailing periods excluded)\n \\n""" # Ends with a non-optional newline\n\n # Compile the patterns into regex objects\n rec_regex = re.compile(rec_pattern, re.VERBOSE | re.MULTILINE | re.DOTALL)\n fld_regex = re.compile(fld_pattern, re.VERBOSE | re.MULTILINE)\n\n # iter over all passed files\n for filePath in files:\n\n # open and read the file into memory\n file = open(filePath,encoding="utf-8")\n fileTxt = file.read()\n file.close()\n \n # find records using regexp and iter over them \n for record in rec_regex.findall(fileTxt):\n # convert the records into dicts\n fields = dict(fld_regex.findall(record))\n \n # decision tree for converting based off of doc type\n # print result with intention that this can be used \n # at the shell and piped into a file\n if fields["Document Type"]=="Patent":\n print(convert_Patent(fields))\n else:\n print("Attempted to covert file: {}\\nHowever, document type <{}> is yet not supported".format(\n filePath, fields["Document Type"]))\n\n# Force auto-run of main\nif __name__ == "__main__": main()\n</code></pre>\n<p><a href=\"https://pastebin.com/Z81JKAyT\" rel=\"nofollow noreferrer\">Updated Sample Output</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T17:18:02.800",
"Id": "243784",
"ParentId": "243576",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T20:09:23.457",
"Id": "243576",
"Score": "6",
"Tags": [
"python",
"latex"
],
"Title": "Custom BibTeX Style File to Implement Patents in the ACS Style"
}
|
243576
|
<p>I've created a code based upon a dice roll where the number of rolls is decided by user input. I am new to this, so any and all feedback will be appreciated as I feel the code is quite clunky at best.</p>
<pre><code>number_of_times = int(input("How many times do you want to roll the dice?: "))
print(number_of_times)
def dice_roll(x):
import random
for r in range(x):
roll = random.randint(1,20)
print(roll)
dice_roll(number_of_times)
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>You should have imports at the top of your code. Having them in the middle of code makes it needlessly confusing with no benefit.</li>\n<li>You code doesn't account for the possibility of a user not entering an integer as input. You can utilize a <code>while</code>, <code>try</code> and <code>except ValueError</code> to allow a user to attempt to re-enter a value.</li>\n<li>You should keep code out of the global scope. Wrapping your code in a <code>main</code> function will help prevent future mishaps.</li>\n<li>You should really use a better name than <code>x</code>, <code>amount</code> is descriptive.</li>\n<li>Rather than <code>r</code> you can use <code>_</code> or <code>__</code> to denote that you are throwing away the value. This is no different that what you have done now, but it is a custom to help others understand your code quickly.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n\ndef roll_dice(amount):\n for _ in range(amount):\n print(random.randint(1, 20))\n\n\ndef main():\n while True:\n try:\n amount = int(input(\"How many times do you want to roll the dice? \"))\n break\n except ValueError:\n print(\"That is not a valid whole number.\")\n print(amount)\n roll_dice(amount)\n\n\nmain()\n</code></pre>\n\n<p>There are some more advanced things you can do too.</p>\n\n<ol start=\"6\">\n<li>You can use an <code>if __name__ == \"__main__\":</code> guard to help prevent your <code>main</code> code from running accidentally. If it is imported by accident from another script.</li>\n<li>It would be better for you to return the values of the dice rather than <code>print</code>. This allows you to reuse the function later if you need to use the results of the thrown dice.</li>\n<li>You can use <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a> to select <code>k</code> amount of values.</li>\n<li>Print is slow. You may want to change to use <code>\"\\n\".join</code> to reduce the overhead from calling <code>print</code> multiple times. However you need to convert all the values to strings.</li>\n<li><p>To easily convert each value in a list to a string you can use a for loop, building a new list.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>output = []\nfor item in roll_dice(amount):\n output.append(str(item))\n</code></pre>\n\n<p>This contains a lot of noise, so we can use a list comprehension to simplify this.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>output = [str(die) for die in roll_dice(amount)]\n</code></pre></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n\ndef roll_dice(amount):\n return random.choices(range(1, 21), k=amount)\n\n\ndef main():\n while True:\n try:\n amount = int(input(\"How many times do you want to roll the dice? \"))\n break\n except ValueError:\n print(\"That is not a valid whole number.\")\n print(amount)\n print(\"\\n\".join([str(die) for die in roll_dice(amount)]))\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p><strong>Note</strong>: Personally I don't think using the list comprehension and <code>str.join</code> to be as nice as a for loop when it comes to non-performance critical code. This is to show you how you can improve future code with the code you have today.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T01:21:57.133",
"Id": "243584",
"ParentId": "243582",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T00:35:15.073",
"Id": "243582",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Looking for improvements on basic dice roll code (Python 3)"
}
|
243582
|
<p>I have a large log file in the following format. Do note that this is already sorted alphabetically. I wish to split it into smaller pieces, and with file names reflecting the content of the file (first three char of the row).</p>
<p>I wish for the code to be efficient. Speed and simplicity is the key. The log file is in 10s of GB in size, and there are 1000s of such logs. </p>
<p>Secondly, for large output files (only if the output file is greater than 4 lines), the script should sub-split the file into smaller pieces, using the next alphabet. I am aware this can be done by 2 separate awk commands, but that would not be efficient. Can you pls help me update the existing code?</p>
<p><strong>Input file:</strong></p>
<pre><code>Jon1,details
Jon2,details
Jon4,details
Ron1,detailsaa
Ron1,detailsbb
Ron1,detailscc
Ron1,detailsdd
Ron1,detailsee
Ron2,detailsff
</code></pre>
<p><strong>Output I wish for:</strong></p>
<pre><code>cat Jon
Jon1,details
Jon2,details
Jon4,details
cat Ron1
Ron1,detailsaa
Ron1,detailsbb
Ron1,detailscc
Ron1,detailsdd
Ron1,detailsee
cat Ron2
Ron2,detailsff
</code></pre>
<p><strong>Current code</strong></p>
<pre><code>awk '
fname != $1{
close(fname)
fname=$1
}
{print $0 > fname}' FS="[[:digit:]]+" ./hugeFile
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T13:03:59.600",
"Id": "478137",
"Score": "2",
"body": "Welcome to the Code Review website, where we review code you have written that is working as expected and provide suggestions on how to improve the code. Code that is not working as expected or not written yet is considered off-topic and the question may be closed by the community. Please see our guidelines in the [help center](https://codereview.stackexchange.com/help/asking)."
}
] |
[
{
"body": "<p>Since you are concerned about execution speed, you should write this program in some other programming languages as well and compare their performance. I'd take Java, C++, Go, Perl, Python and Rust. Traditionally, AWK gets the job done but is not optimized for processing huge amounts of data.</p>\n\n<p>Instead of setting <code>FS</code> on the command line, it should be in a <code>BEGIN</code> clause since it is an essential part of the program:</p>\n\n<pre><code>BEGIN {\n FS = /[[:digit:]]+/;\n}\n</code></pre>\n\n<p>Asking for code that is not yet implemented is off-topic on this site, so I won't comment much on that. The code will become much larger by that requirement though and will require more thought. Be prepared to have a collection of small sample files to test the edge cases automatically.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T05:19:44.350",
"Id": "243587",
"ParentId": "243585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T02:27:14.463",
"Id": "243585",
"Score": "0",
"Tags": [
"bash",
"linux",
"awk"
],
"Title": "Split large log file like a dictionary"
}
|
243585
|
<p>Following the method suggested <a href="https://math.stackexchange.com/questions/3710402/generate-random-points-on-perimeter-of-ellipse">here</a>, I've written a Python script that generates random points along the perimeter of an ellipse. I wanted to compare a "naive" method (which fails to produce an even distribution) with the correct method, which works like this:</p>
<ol>
<li>Numerically compute <em>P,</em> the perimeter of the ellipse.</li>
<li>Pick a random number <em>s</em> on [0,<em>P</em>].</li>
<li>Determine the angle <em>t</em> associated with that arc length <em>s.</em></li>
<li>Compute the <em>x</em>- and <em>y</em>-coordinates associated with <em>t</em> from the parametric form of the ellipse. </li>
</ol>
<p>Here is the code I am hoping to receive feedback on. I ran it through <code>flake8</code> already. </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def ellipse_arc(a, b, theta, n):
"""Cumulative arc length of ellipse with given dimensions"""
# Divide the interval [0 , theta] into n steps at regular angles
t = np.linspace(0, theta, n)
# Using parametric form of ellipse, compute ellipse coord for each t
x, y = np.array([a * np.cos(t), b * np.sin(t)])
# Compute vector distance between each successive point
x_diffs, y_diffs = x[1:] - x[:-1], y[1:] - y[:-1]
cumulative_distance = [0]
c = 0
# Iterate over the vector distances, cumulating the full arc
for xd, yd in zip(x_diffs, y_diffs):
c += np.sqrt(xd**2 + yd**2)
cumulative_distance.append(c)
cumulative_distance = np.array(cumulative_distance)
# Return theta-values, distance cumulated at each theta,
# and total arc length for convenience
return t, cumulative_distance, c
def theta_from_arc_length_constructor(a, b, theta=2*np.pi, n=100):
"""
Inverse arc length function: constructs a function that returns the
angle associated with a given cumulative arc length for given ellipse."""
# Get arc length data for this ellipse
t, cumulative_distance, total_distance = ellipse_arc(a, b, theta, n)
# Construct the function
def f(s):
assert np.all(s <= total_distance), "s out of range"
# Can invert through interpolation since monotonic increasing
return np.interp(s, cumulative_distance, t)
# return f and its domain
return f, total_distance
def rand_ellipse(a=2, b=0.5, size=50, precision=100):
"""
Returns uniformly distributed random points from perimeter of ellipse.
"""
theta_from_arc_length, domain = theta_from_arc_length_constructor(a, b, theta=2*np.pi, n=precision)
s = np.random.rand(size) * domain
t = theta_from_arc_length(s)
x, y = np.array([a * np.cos(t), b * np.sin(t)])
return x, y
def rand_ellipse_bad(a, b, n):
"""
Incorrect method of generating points evenly spaced along ellipse perimeter.
Points cluster around major axis.
"""
t = np.random.rand(n) * 2 * np.pi
return np.array([a * np.cos(t), b * np.sin(t)])
</code></pre>
<p>And some test visualizations:</p>
<pre><code>np.random.seed(4987)
x1, y1 = rand_ellipse_bad(2, .5, 1000)
x2, y2 = rand_ellipse(2, .5, 1000, 1000)
fig, ax = plt.subplots(2, 1, figsize=(13, 7), sharex=True, sharey=True)
fig.suptitle('Generating random points on perimeter of ellipse', size=18)
ax[0].set_aspect('equal')
ax[1].set_aspect('equal')
ax[0].scatter(x1, y1, marker="+", alpha=0.5, color="crimson")
ax[1].scatter(x2, y2, marker="+", alpha=0.5, color="forestgreen")
ax[0].set_title("Bad method: Points clustered along major axis")
ax[1].set_title("Correct method: Evenly distributed points")
</code></pre>
<p><a href="https://i.stack.imgur.com/vodwc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vodwc.png" alt="comparison of methods"></a></p>
<pre><code># Plot arc length as function of theta
theta_from_arc_length, domain = theta_from_arc_length_constructor(2, .5, theta=2*np.pi, n=100)
s_plot = np.linspace(0, domain, 100)
t_plot = theta_from_arc_length(s_plot)
fig, ax = plt.subplots(figsize=(7,7), sharex=True, sharey=True)
ax.plot(t_plot, s_plot)
ax.set_xlabel(r'$\theta$')
ax.set_ylabel(r'cumulative arc length')
</code></pre>
<p><a href="https://i.stack.imgur.com/CRXUQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CRXUQ.png" alt="ellipse arc length fn"></a></p>
<p>I would appreciate a general review, but I also have a few specific questions:</p>
<ol>
<li><strong>How are my comments?</strong> In my code, I know many of my comments are explaining "how" rather than "why," and my inclination is simply to remove them, since I think I have made my variable and function names clear. But I would appreciate an example of how a comment like <code># Compute vector distance between each successive point</code> could be rewritten in "why" terms.</li>
<li><strong>Have I computed the arc length in the most efficient way possible?</strong> I started by generating the points in two lists of <em>x</em>- and <em>y</em>-coordinates, then iterated over these lists to get the distance made at each step, cumulating those distances as I went around. </li>
<li><strong>Is it there anything unconventional or inefficient about using <code>theta_from_arc_length_constructor</code> to create the inverse arc-length function?</strong> My thinking was that I need to evaluate the inverse of the arc-length function for every <em>s,</em> so I should go ahead and "prepare" this function rather than recalculate the total arc length each time. But doesn't <code>return np.interp(s, cumulative_distance, t)</code> mean that numpy has to do the interpolation every time I call <em>f</em> ? Or does it get "automatically" vectorized because I feed it <em>s</em> as an array later on when creating the graphs?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T06:45:30.330",
"Id": "478763",
"Score": "0",
"body": "Consider `mpmath.quad` for integration (example [here](https://codegolf.stackexchange.com/a/195398))"
}
] |
[
{
"body": "<p>Some small speed improvement. Instead of having a Python <code>for</code> loop in order to compute the total and cumulative sum, use the respective <code>numpy</code> functions. Same for the differences:</p>\n\n<pre><code>x_diffs, y_diffs = np.diff(x), np.diff(y)\ndelta_r = np.sqrt(x_diffs**2 + y_diffs**2)\ncumulative_distance = delta_r.cumsum()\nc = delta_r.sum()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T23:13:40.927",
"Id": "478223",
"Score": "0",
"body": "Thank you! I was able to consolidate it a little more by using `np.linalg.norm` to get the deltas, like so: `coords = np.array([a * np.cos(t), b * np.sin(t)])`\n`coords_diffs = np.diff(coords)` \n`cumulative_distance = np.cumsum(np.linalg.norm(coords_diffs, axis=0))`. Also, I had to `np.concatenate` a 0 back onto the `cumsum` at the end so that it matches the size of `t`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T10:23:34.137",
"Id": "243597",
"ParentId": "243590",
"Score": "1"
}
},
{
"body": "<p>The intro you provided for this question is a good start on a module level comment or docstring that describes <strong>why</strong> the module is coded the way it is.</p>\n<pre><code>"""\nThis module generates random points on the perimeter of a ellipse.\n\nThe naive approach of picking a random angle and computing the\ncorresponding points on the ellipse results in points that are not\nuniformly distributed along the perimeter.\n\nThis module generates points that are uniformly distributed\non the perimeter by:\n\n 1. Compute P, the perimeter of the ellipse. There isn't a simple\n formula for the perimeter so it is calculated numerically.\n 2. Pick a random number s on [0,P].\n 3. Determine the angle t associated with the arc [0,s].\n 4. Compute the x- and y-coordinates associated with t from the\n parametric equation of the ellipse.\n"""\n</code></pre>\n<p>To respond to your comment, put the plotting code at the end of the file in a <code>if __name__ == "__main__":</code> guard (<a href=\"https://docs.python.org/3/library/__main__.html#module-__main__\" rel=\"nofollow noreferrer\">see docs</a>). If you run the file as a script or using <code>python -m</code> it will run the plotting code. If the file is imported then this code is not included.</p>\n<pre><code>if __name__ == "__main__":\n\n import matplotlib.pyplot as plt\n\n np.random.seed(4987)\n \n x1, y1 = rand_ellipse_bad(2, .5, 1000)\n x2, y2 = rand_ellipse(2, .5, 1000, 1000)\n \n fig, ax = plt.subplots(2, 1, figsize=(13, 7), sharex=True, sharey=True)\n fig.suptitle('Generating random points on perimeter of ellipse', size=18)\n ax[0].set_aspect('equal')\n ax[1].set_aspect('equal')\n ax[0].scatter(x1, y1, marker="+", alpha=0.5, color="crimson")\n ax[1].scatter(x2, y2, marker="+", alpha=0.5, color="forestgreen")\n ax[0].set_title("Bad method: Points clustered along major axis")\n ax[1].set_title("Correct method: Evenly distributed points")\n\n # Plot arc length as function of theta\n theta_from_arc_length, domain = theta_from_arc_length_constructor(2, .5, theta=2*np.pi, n=100)\n s_plot = np.linspace(0, domain, 100)\n t_plot = theta_from_arc_length(s_plot)\n \n fig, ax = plt.subplots(figsize=(7,7), sharex=True, sharey=True)\n ax.plot(t_plot, s_plot)\n ax.set_xlabel(r'$\\theta$')\n ax.set_ylabel(r'cumulative arc length')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T03:04:38.117",
"Id": "478319",
"Score": "0",
"body": "Thank you. Where would this comment go in the file? Would I just put it at the top (before the imports)? And if I wanted to include my visualizations as a \"usage example,\" is there a way to incorporate them into the same .py file? I have been doing everything in Jupyter notebook, so I'm used to having my separate markdown cells and this style of documentation is new to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T03:24:29.847",
"Id": "478321",
"Score": "0",
"body": "Pep 8 says `import` statement come after module level comments; put it before the imports. I don't know of a generic portable way to include images in a python source file. But I think you can include them in Sphynx documentation, or put a URL in a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T03:57:47.530",
"Id": "478322",
"Score": "0",
"body": "I don't want to put the images themselves in, just the code used to generate them as a sort of \"usage example.\" But perhaps I should come up with an example that doesn't involve matplotlib at all, since the main functions don't depend on it anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T04:51:23.977",
"Id": "478326",
"Score": "0",
"body": "@Max you could always put the plotting code in a `if __name__ == \"__main__\":` guard. See revised answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T02:24:24.857",
"Id": "243697",
"ParentId": "243590",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T07:11:42.140",
"Id": "243590",
"Score": "6",
"Tags": [
"python"
],
"Title": "Generate random points on perimeter of ellipse"
}
|
243590
|
<p>I wrote this code for finding, substituting and executing values in dictionary, much like <code>$()</code> bash operator works.</p>
<p>I used nested functions for this, forming hierarchy and encapsulating their names.
But now I'm concern, that this may be an overhead in reading ease and unit testing now
sucks, because I can't write test for concrete nested function in other file.</p>
<p>Should I make this functions global, or this approach is acceptable?</p>
<pre class="lang-py prettyprint-override"><code>def execute_steps(config):
def search_for_expand(var_name, stage_name):
if var_name in config.typedef.evaluators:
return config.typedef.evaluators[var_name]
if var_name in config.typedef.stages[stage_name]:
return config.typedef.stages[stage_name][var_name]
for stage in config.typedef.stages:
if var_name in config.typedef.stages[stage]:
return config.typedef.stages[stage][var_name]
return var_name
def execute_abstract(stage_name):
def substitute_macroses(var_name):
def is_expandable(value):
return DEF.EXECUTOR in value
def expand(var_value):
for match in DEF.EXECUTOR_RE.finditer(var_value):
value_to_expand = match.group(1)
var_value = var_value.replace(match.group(0),
search_for_expand(value_to_expand,
stage_name))
return var_value
var_value = stage[var_name]
if is_expandable(var_value):
stage[var_name] = expand(var_value)
stage = config.typedef.stages[stage_name]
for k in stage:
substitute_macroses(k)
def execute_build(stage):
execute_abstract(DEF.BUILD)
out = subprocess.run(stage[config.build_process.result],
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return out
def execute_static(stage, build_out):
execute_abstract(DEF.STATIC)
out = subprocess.run(stage[config.static_process.result],
shell=True,
input=build_out.stdout,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return out
def execute_dynamic(stage, static_out):
execute_abstract(DEF.DYNAMIC)
out = subprocess.run(stage[config.dynamic_process.result],
shell=True,
input=static_out.stdout,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return out
build_out = execute_build(config.typedef.stages[DEF.BUILD])
static_out = execute_static(config.typedef.stages[DEF.STATIC], build_out)
dynamic_out = execute_dynamic(config.typedef.stages[DEF.DYNAMIC], static_out)
return (build_out, static_out, dynamic_out)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T07:30:31.100",
"Id": "243591",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"closure"
],
"Title": "Finding, substituting and executing values in dictionaries"
}
|
243591
|
<p>I am fairly new to Golang and I was creating an API to fetch commits from any Github repository using their API. I was then creating a frequency count, based on the date and then sending it to the frontend. </p>
<p>Added a Gist for a better view:
<a href="https://gist.github.com/karansinghgit/256a3f69698004cab4024c39767a0be1" rel="nofollow noreferrer">https://gist.github.com/karansinghgit/256a3f69698004cab4024c39767a0be1</a></p>
<p>Currently, I only work in one main.go and I am not very aware of the programming pracices in Golang. I am using the Mux router to work with http.</p>
<p>I have 2 routes.<br>
The '/' route is handled by <code>getHome</code> and '/updateRepository' is handled by <code>updateRepository</code> handler.</p>
<p>I maintain a <code>currentRepository</code> variable globally.<br>
In both handler methods, I first get the timestamps of all the commits for that repository using Github's API using <code>getCommitTimeStamps</code>. </p>
<p>Then I parse the timestamps using <code>parseTimeStamps</code>, which first converts the RFC3339 date format to <code>YYYY-MM-DD</code> format and then basically create a map to store the frequency for each date.</p>
<p>The only extra method which <code>updateRepository</code> handler uses, is <code>parseURL</code> which basically extracts the Github Owner Name and Repository name from any Github URL.
I plan to update this using an input text element on my Frontend.</p>
<p><code>init</code> initialises a new Client for enabling access to Github's API. </p>
<p>I have split everything into functions, what else can I do? What are the things I can clean?</p>
<pre><code>package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/google/go-github/v31/github"
"github.com/gorilla/mux"
"golang.org/x/oauth2"
)
var client *github.Client
var ctx context.Context
type Repository struct {
Owner string `json:"owner"`
Name string `json:"name"`
}
type Frequency struct {
Date string `json:"date"`
Count int `json:"count"`
}
var currentRepository = Repository{
Owner: "karansinghgit",
Name: "foobar",
}
const GITHUB_AUTH_TOKEN string = "MY_AUTH_TOKEN"
func init() {
ctx = context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: GITHUB_AUTH_TOKEN},
)
tc := oauth2.NewClient(ctx, ts)
client = github.NewClient(tc)
}
func parseURL(repoURL *string) Repository {
res := currentRepository
if *repoURL != "" {
index := strings.Index(*repoURL, "github.com")
repo := *repoURL
repo = repo[index+11:]
var base []string
base = strings.Split(repo, "/")
var ans []string
for _, e := range base {
if e != "" {
ans = append(ans, e)
}
}
res = Repository{
Owner: ans[0],
Name: ans[1],
}
}
return res
}
func getCommitTimeStamps(repo Repository) []time.Time {
var commitTimeStamps []time.Time
opt := &github.CommitsListOptions{
ListOptions: github.ListOptions{PerPage: 50},
}
var allRepositoryCommits []*github.RepositoryCommit
for {
repositoryCommits, resp, err := client.Repositories.ListCommits(ctx, repo.Owner, repo.Name, opt)
if err != nil {
fmt.Println(err)
}
allRepositoryCommits = append(allRepositoryCommits, repositoryCommits...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
for _, e := range allRepositoryCommits {
commitTimeStamps = append(commitTimeStamps, *e.GetCommit().Author.Date)
}
return commitTimeStamps
}
func parseTimeStamps(commitTimeStamps []time.Time) []Frequency {
const RFC3339FullDate = "2006-08-06"
timeSeries := make([]string, len(commitTimeStamps))
for i, t := range commitTimeStamps {
timeSeries[i] = fmt.Sprintf("%d-%02d-%02d", t.Year(), t.Month(), t.Day())
}
m := make(map[string]int)
for _, t := range timeSeries {
m[t]++
}
var f []Frequency
for k, v := range m {
f = append(f, Frequency{
Date: k,
Count: v,
})
}
return f
}
func getHome(w http.ResponseWriter, r *http.Request) {
commitTimeStamps := getCommitTimeStamps(currentRepository)
commitTimeObjects := parseTimeStamps(commitTimeStamps)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
_ = json.NewEncoder(w).Encode(commitTimeObjects)
}
func updateRepository(w http.ResponseWriter, r *http.Request) {
var url struct {
URL string `json:"url"`
}
_ = json.NewDecoder(r.Body).Decode(&url)
currentRepository = parseURL(&url.URL)
fmt.Println(currentRepository)
// currentRepository looks like {bradtraversy reactcharts}
commitTimeStamps := getCommitTimeStamps(currentRepository)
commitTimeObjects := parseTimeStamps(commitTimeStamps)
// commitTimeObjects looks like [{2016-04-21 2} {2016-04-23 5} {2016-04-25 1}]
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "PUT")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
fmt.Println(currentRepository)
_ = json.NewEncoder(w).Encode(commitTimeObjects)
}
func main() {
router := mux.NewRouter()
router.Use(mux.CORSMethodMiddleware(router))
router.HandleFunc("/", getHome).Methods("GET", "OPTIONS")
router.HandleFunc("/updateRepository", updateRepository).Methods("PUT", "OPTIONS")
http.ListenAndServe(":8000", router)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T07:55:55.143",
"Id": "478119",
"Score": "0",
"body": "I don't understand why I was downvoted. I posted this in compliance with the rules of the community. Please add a comment to help me improve as to why this was downvoted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T08:10:07.197",
"Id": "478124",
"Score": "0",
"body": "@KaranSingh Also edit your question body and add a detailed description what your code is supposed to do please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T08:26:40.970",
"Id": "478125",
"Score": "0",
"body": "@πάνταῥεῖ updated with the required explanation"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T07:51:17.030",
"Id": "243592",
"Score": "2",
"Tags": [
"beginner",
"go"
],
"Title": "Creating an API in Go to work with Github"
}
|
243592
|
<p>I'm new to web development, and currently learning the basics of HTML and CSS. Many web pages follow the structural pattern of header, main, and footer; so I figured it'd be a good idea to try and implement this structure to see how things are carved.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
display: flex;
flex-direction: column;
font-family: sans-serif;
margin: 0;
min-height: 100vh;
}
header,
footer {
background-color: dodgerblue;
color: white;
text-align: center;
}
main {
background-color: snow;
flex: 1;
padding: 1rem;
}
footer {
margin-top: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<link rel="stylesheet" href="main.css">
<meta charset="UTF-8">
</head>
<body>
<header>
<h1>Header</h1>
</header>
<main>
<h2>Main content</h2>
</main>
<footer>
<h3>Footer</h3>
</footer>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I'm looking for all kinds of feedback, from style, to anti-patterns, ways to do things more concisely, and whatever other observation you can find useful. I do have some specific questions:</p>
<ol>
<li>Are the semantic HTML elements used correctly? There's no need for an article element inside the main element, right?</li>
<li>In the CSS I selected both header and footer for stuff that they have in common, is this good practice? Or should I keep a single header and a single footer selectors, separately? Could be more maintainable that way?</li>
<li>Is this normally handled using Flexbox? Or is Grid display a better tool for this?</li>
<li>What things would you do differently?</li>
</ol>
|
[] |
[
{
"body": "<p>I myself am also a beginner in the world of web development (So any comments about my answer are more than welcome!)\nBut maybe my tips can still be useful in one way or another. ;-}</p>\n<p>The first thing that came to mind is your header and footer element question about grouping them together that way in CSS because they have things in common...My short answer is no, I would change my HTML element for these, or better said, add a class or id attribute, and group it together this way.</p>\n<p>Example:</p>\n<pre><code> <header class = "topAndBottom">.....</header>\n <footer class = "topAndBottom">.....</footer>\n</code></pre>\n<p>CSS example:</p>\n<pre><code> .header, topAndBottom {\n.......\n}\n</code></pre>\n<p>I personally prefer the class attribute over the id, because you can use it more often in your HTML, the id attribute is once or maybe twice acceptable in your HTML(Not my rules)</p>\n<p>Or you can only style your <code><h1></code> inside your header and the <code><h3></code> inside your footer, I would recommend this if it is mainly text that you want to style.</p>\n<p>And one tiny comment about the order in your CSS, and this is purely personal, but maintain the order from your HTML in your CSS for better reading, especially when your code will be more advanced and complex.</p>\n<p>Good luck with your learning for web development! I started also not long ago and I am addicted!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:35:39.117",
"Id": "244046",
"ParentId": "243593",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244046",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T08:17:09.213",
"Id": "243593",
"Score": "1",
"Tags": [
"beginner",
"html",
"css",
"html5"
],
"Title": "Semantic implementation of the structure of a web page with header, main, and footer"
}
|
243593
|
<p><strong>Motivation</strong></p>
<p>The most common model for a random graph is the <a href="https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model" rel="nofollow noreferrer">Erdős–Rényi model</a>. However, it does not guarantee the connectedness of the graph. Instead, let's consider the following algorithm (in python-style pseudocode) for generating a random connected graph with <span class="math-container">\$n\$</span> nodes:</p>
<pre><code>g = empty graph
g.add_nodes_from(range(n))
while not g.is_connected:
i, j = random combination of two (distinct) nodes in range(n)
if {i, j} not in g.edges:
g.add_edge(i, j)
return g
</code></pre>
<p>The graph generated this way is guaranteed to be connected. Now, my intuition tells me that its expected number of edges is of the order <span class="math-container">\$ O(n \log n) \$</span>, and I want to test my hypothesis in Python. I don't intend to do a rigorous mathematical proof or a comprehensive statistical inference, just some basic graph plotting.</p>
<p><strong>The Codes</strong></p>
<p>In order to know whether a graph is connected, we need a partition structure (i.e. union-find). I first wrote a <code>Partition</code> class in the module <code>partition.py</code>. It uses path compression and union by weights:</p>
<pre><code># partition.py
class Partition:
"""Implement a partition of a set of items to disjoint subsets (groups) as
a forest of trees, in which each tree represents a separate group.
Two trees represent the same group if and only if they have the same root.
Support union operation of two groups.
"""
def __init__(self, items):
items = list(items)
# parents of every node in the forest
self._parents = {item: item for item in items}
# the sizes of the subtrees
self._weights = {item: 1 for item in items}
def __len__(self):
return len(self._parents)
def __contains__(self, item):
return item in self._parents
def __iter__(self):
yield from self._parents
def find(self, item):
"""Return the root of the group containing the given item.
Also reset the parents of all nodes along the path to the root.
"""
if self._parents[item] == item:
return item
else:
# find the root and recursively set all parents to it
root = self.find(self._parents[item])
self._parents[item] = root
return root
def union(self, item1, item2):
"""Merge the two groups (if they are disjoint) containing
the two given items.
"""
root1 = self.find(item1)
root2 = self.find(item2)
if root1 != root2:
if self._weights[root1] < self._weights[root2]:
# swap two roots so that root1 becomes heavier
root1, root2 = root2, root1
# root1 is heavier, reset parent of root2 to root1
# also update the weight of the tree at root1
self._parents[root2] = root1
self._weights[root1] += self._weights[root2]
@property
def is_single_group(self):
"""Return true if all items are contained in a single group."""
# we just need one item, any item is ok
item = next(iter(self))
# group size is the weight of the root
group_size = self._weights[self.find(item)]
return group_size == len(self)
</code></pre>
<p>Next, since we are only interested in the number of edges, we don't actually need to explicitly construct any graph object. The following function implicitly generates a random connected graph and return its number of edges:</p>
<pre><code>import random
from partition import Partition
def connected_edge_count(n):
"""Implicitly generate a random connected graph and return its number of edges."""
edges = set()
forest = Partition(range(n))
# each time we join two nodes we merge the two groups containing them
# the graph is connected iff the forest of nodes form a single group
while not forest.is_single_group:
start = random.randrange(n)
end = random.randrange(n)
# we don't bother to check whether the edge already exists
if start != end:
forest.union(start, end)
edge = frozenset({start, end})
edges.add(edge)
return len(edges)
</code></pre>
<p>We then estimate the expected number of edges for a given <span class="math-container">\$n\$</span>:</p>
<pre><code>def mean_edge_count(n, sample_size):
"""Compute the sample mean of numbers of edges in a sample of
random connected graphs with n nodes.
"""
total = sum(connected_edge_count(n) for _ in range(sample_size))
return total / sample_size
</code></pre>
<p>Now, we can plot the expected numbers of edges against <span class="math-container">\$ n \log n \$</span> for different values of <span class="math-container">\$n\$</span>:</p>
<pre><code>from math import log
import matplotlib.pyplot as plt
def plt_mean_vs_nlogn(nlist, sample_size):
"""Plot the expected numbers of edges against n * log(n) for
a given list of values of n, where n is the number of nodes.
"""
x_values = [n * log(n) for n in nlist]
y_values = [mean_edge_count(n, sample_size) for n in nlist]
plt.plot(x_values, y_values, '.')
</code></pre>
<p>Finally, when we called <code>plt_mean_vs_nlogn(range(10, 1001, 10), sample_size=100)</code>, we got:</p>
<p><a href="https://i.stack.imgur.com/3BGew.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3BGew.png" alt="enter image description here"></a></p>
<p>The plot seems very close to a straight line, supporting my hypothesis.</p>
<p><strong>Questions and ideas for future work</strong></p>
<ol>
<li>My program is slow! It took me 90 seconds to run <code>plt_mean_vs_nlogn(range(10, 1001, 10), sample_size=100)</code>. How can I improve the performance?</li>
<li>What other improvement can I make on my codes?</li>
<li>An idea for future work: do a linear regression on the data. A high coefficient of determination would support my hypothesis. Also find out the coefficient of <span class="math-container">\$ n \log n \$</span>.</li>
<li>Any other idea for testing my hypothesis programmatically?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T11:53:04.340",
"Id": "478128",
"Score": "1",
"body": "did you try [line_profiler](https://pypi.org/project/line-profiler/) to see which lines were slowing you down? To use it, first install and then add `@profile` to the function you want to profile. Then in terminal `kernprof -lv finename.py`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T11:55:32.887",
"Id": "478129",
"Score": "0",
"body": "Oh, I didn't know such thing exists. Thank you for your advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T11:56:35.890",
"Id": "478130",
"Score": "0",
"body": "You can add `@profile` to multiple functions. You may add the profiler results to the question."
}
] |
[
{
"body": "<p><strong>"My program is slow!"</strong></p>\n<p>You want an estimate for <span class=\"math-container\">\\$P\\$</span> different graph-sizes, each of which is the average of <span class=\"math-container\">\\$S\\$</span> samples of <code>connected_edge_count</code>. We assume <code>connected_edge_count</code> will run through it's <code>while</code> loop <span class=\"math-container\">\\$n\\log n\\$</span> times (approximately). What's the asymptotic complexity of <code>Partition.find()</code>? I'll wildly guess it's <span class=\"math-container\">\\$\\log n\\$</span>. So taking <span class=\"math-container\">\\$N\\$</span> as the maximum requested <span class=\"math-container\">\\$n\\$</span>, your <em>overall program</em> is <span class=\"math-container\">\\$O(P S N (\\log N)^2)\\$</span>.</p>\n<p>So broadly speaking, there's just a lot of work to do. Local improvements to the <em>implementation details</em> can help, but I think your biggest problem (at least until you start increasing <span class=\"math-container\">\\$n\\$</span>) is <span class=\"math-container\">\\$S\\$</span>. 100 is way too big. Playing around with some values, 15 seems to give somewhat stable results, although possibly you'll want more as you deal with larger <span class=\"math-container\">\\$n\\$</span> values.</p>\n<p>On the other hand, how often are you planning on running this? Ninety seconds isn't really that long. It feels like a long time when you're trying to iterate on the program. So one thing you might want to work on is the way the functions are nested. Rather than having each function in the stack call the next, let them take the prior result as an argument. This way you'll have better access to intermediate results, and won't have to re-run everything every time.</p>\n<p>I spent some time squishing around parts of the code to make sure I understood it, and then because I couldn't get the details out of my head. I haven't checked if it's faster or now, mostly it's just denser. For an academic POC, it goes up to 10K without any problems. (My <code>main</code> takes about three minutes to run. I still can't get <code>connected_edge_count(10 * 1000 * 1000)</code> to work; it crashes after a few minutes.) I'll post my version below in case there are any differences in it you find useful.</p>\n<p><strong>"What other improvement can I make on my codes?"</strong><br />\nAll the usual stuff. Better variable names, less mutation of state and variables, type-hints. Once I got a sense of what your code did I quite liked it; the tree system is clever. (But is it <em>accurate</em>? How do you <em>know</em>? If you're hoping to publish results, adding a few unit tests isn't going to be good enough.)</p>\n<p>In your comments you talked about not needing to build an explicit graph; you claimed to do it virtually. But notice that you <em>do</em> need to keep track of all the edges so that you can count them.</p>\n<p>Because performance is an issue, and we want to be able to handle large numbers of items, I made some optimizations that may make the code harder to read. For example, for the task at hand a <code>List[int]</code> (array) can serve the purpose of a <code>Dict[int, int]</code> with a lot less machine overhead. But it ties you representing your nodes as <code>int</code>s.</p>\n<p><strong>As for further research steps, it depends on your goals. My intuition is that this kind of sampling may be an easy way of checking if your hypothesis is viable, and you've done that. If you want to <em>prove</em> it, then you need to actually prove it. Maybe a programmatic proof system like agda or coq can help, maybe not; I haven't learned them yet!</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib\nmatplotlib.use('TkAgg')\n\nfrom itertools import count, dropwhile, takewhile\nimport random\nfrom math import exp, log\nimport matplotlib.pyplot as plt\nfrom scipy.special import lambertw\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Set, Tuple\n\nfrom time import sleep\n\n\nclass Partition(NamedTuple):\n parents: List[int]\n weights: List[int]\n edges: Set[Tuple[int, int]] # The tuple members must be storted! frozensets would be harder to screw up, and maybe slightly faster, but they take more ram, which I think is the bottleneck.\n\n @staticmethod\n def atomic(node_count: int):\n return Partition(\n parents=list(range(node_count)),\n weights=[1 for node in range(node_count)],\n edges=set()\n )\n\n def _node_to_str(self, node: int) -> str:\n if not node < len(self.parents):\n raise Exception(f"{node} is not in the range 0 - {len(self.parents)}.")\n return "{n}: <{c}>".format(\n n=node,\n c=", ".join(self._node_to_str(n) for (n, p) in enumerate(self.parents) if p == node and n != node)\n )\n\n def display(self) -> str:\n if 100 < len(self.parents):\n raise NotImplementedError("Refusing to pretty-print a large forest.")\n return "\\n".join(self._node_to_str(n) for (n, p) in enumerate(self.parents) if p == n)\n\n def find_root(self, item: int) -> int:\n parent = self.parents[item]\n if parent == item:\n return item\n else: # find the root and recursively set all parents to it\n root = self.find_root(parent)\n self.parents[item] = root\n return root\n\n def add_edge(self, item1: int, item2: int) -> int:\n """returns the number of edges added to the graph (1, or 0 if the edge was already there)"""\n edge = (item1, item2) if item1 < item2 else (item2, item1)\n if edge in self.edges:\n return 0\n else:\n self.edges.add(edge)\n root1 = self.find_root(item1)\n root2 = self.find_root(item2)\n if root1 != root2:\n weight1 = self.weights[root1]\n weight2 = self.weights[root2]\n heavier, lighter, lesser_weight = (root2, root1, weight1) if weight1 < weight2 else (root1, root2, weight2)\n self.parents[lighter] = heavier # reset parent of lighter to heavier\n self.weights[heavier] += lesser_weight # also update the weight of the tree the heavier node\n return 1\n\n def is_single_group(self) -> bool:\n # we can start with any node for the task at hand\n return len(self.parents) == self.weights[self.find_root(self.parents[0])]\n\n\ndef connected_edge_count(n: int) -> int:\n forest = Partition.atomic(n)\n nodes = range(n) # not the _real_ nodes, just an external thing to sample from.\n while not forest.is_single_group():\n edge = random.sample(nodes, 2)\n forest.add_edge(*edge)\n return len(forest.edges)\n\n\ndef mean_of(trial: Callable[..., int], *trial_args, sample_size: int, **trial_kwargs) -> float:\n return sum(trial(*trial_args, **trial_kwargs) for _ in range(sample_size)) / sample_size\n\n\ndef nlogn(x):\n return x * log(x)\n\n\ndef inverse(x):\n return abs(x / lambertw(x))\n\n\ndef plt_vs_nlogn(*samples: Tuple[int, float]):\n x_values = [nlogn(n) for (n, v) in samples]\n plt.xlabel("n⋅log(n)")\n y_values = [v for (n, v) in samples]\n plt.ylabel("mean edges to connect n-graph")\n plt.plot(x_values, y_values, '.')\n\n\ndef nlogn_range(start: int, stop: int, starting_step: float = 100) -> Iterable[int]:\n """This is rediculious overkill."""\n return [\n int(inverse(x))\n for x\n in takewhile(lambda _x: inverse(_x) < stop,\n dropwhile(lambda _x: inverse(_x) < start,\n count(1, nlogn(starting_step))))\n ]\n\n\ndef main():\n ns = list(nlogn_range(10, 10 * 1000, 500))\n results = {\n n: mean_of(\n connected_edge_count,\n n,\n sample_size=int(5 * log(n))\n )\n for n in ns\n }\n plt_vs_nlogn(*results.items())\n\n\ndef agrees_with_original(i: int) -> bool:\n import cr_243594_original\n mine = mean_of(connected_edge_count, i, sample_size=i)\n theirs = cr_243594_original.mean_edge_count(i, i)\n print(mine)\n print(theirs)\n return abs(mine - theirs) < (i/10) # this is totally made up and prone to failure because of the randomness.\n\ndef verbose_random_add(tree: Partition) -> None:\n edge = random.sample(range(len(tree.parents)), 2)\n print(sorted(edge))\n print(sorted(tree.edges))\n print(tree.add_edge(*edge))\n print(tree.display())\n print(tree.is_single_group())\n print(sorted(tree.edges))\n assert all(((a,b) not in tree.edges) or (tree.find_root(a) == tree.find_root(b))\n for a in range(len(tree.parents))\n for b in range(a+1, len(tree.parents)))\n print("===========================================")\n\n\nassert agrees_with_original(40)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/weewe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/weewe.png\" alt=\"output of my program\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T01:47:00.420",
"Id": "244086",
"ParentId": "243594",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244086",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T09:37:46.097",
"Id": "243594",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"random",
"graph"
],
"Title": "Test the hypothesis that the expected number of edges of a random connected graph is \\$ O(n \\log n) \\$"
}
|
243594
|
<p>I wanted to build a scaping-API for the website <a href="http://1001tracklists.com" rel="nofollow noreferrer">1001tracklists.com</a> by writing classes for Tracklist and Track objects and some helpful functions:</p>
<p><strong>Here's the full code (<a href="https://github.com/leandertolksdorf/1001-tracklists-api" rel="nofollow noreferrer">GitHub</a>):</strong></p>
<pre class="lang-py prettyprint-override"><code>import requests
import re
from fake_headers import Headers
from bs4 import BeautifulSoup
SOURCES = {
"1": "beatport",
"2": "apple",
"4": "traxsource",
"10": "soundcloud",
"13": "video",
"36": "spotify",
}
class Tracklist:
"""An object representing a tracklist on 1001tracklists.com
Keyword arguments:
url -- The url of the tracklist page.
Class variables:
url
title -- Title of the Tracklist
tracks -- List of Track Objects
Run tracklist_name.fetch() to get data.
"""
def __init__(self, url=""):
self.url = url
if not url:
with open("test.html") as f:
self.soup = BeautifulSoup(f, "html.parser")
else:
self.url = url
self.title = ""
self.tracks = []
self.soup = None
def __repr__(self):
url = f"<Tracklist> {self.url}\n"
title = f"<Title> {self.title}\n"
tracks = ""
for track in self.tracks:
tracks += f" <Track> {track.title}\n"
return url + title + tracks
def get_soup(self, url):
""""Retrtieve html and return a bs4-object."""
response = requests.get(url, headers=Headers().generate())
return BeautifulSoup(response.text, "html.parser")
def fetch(self):
"""Fetch title and tracks from 1001.tl"""
self.soup = self.get_soup(self.url)
self.title = self.soup.title.text
self.tracks = self.fetch_tracks()
def fetch_tracks(self):
"""Fetches metadata, url, and external ids for all tracks.
Result is saved as Track()-Objects to tracklist.tracks."""
result = []
# Find track containers.
track_table = self.soup.find_all("tr", class_="tlpItem")
for track in track_table:
# Find all hyperlinks for each track container
links = track.find_all("a")
for link in links:
# If track url found -> Save
if "/track/" in link["href"]:
track_url = link["href"]
break;
# Find span-elements with class="trackValue", which contain the track id.
info = track.find_all("td")[2]
track_id = info.find("span", class_="trackValue").get("id")[3:]
# Generate a new Track object using gathered data.
new = Track(
url = "",#track_url,
track_id = track_id,
title = info.find("meta", itemprop="name").get("content")
)
# Get external ids for new track.
new.fetch_external_ids()
result.append(new)
return result
def get_tracks(self):
for track in self.tracks:
print(track)
return self.tracks
class Track(Tracklist):
"""An object representing a track on 1001tracklists.com
Keyword arguments:
url -- The url of the tracklist page.
track_id -- Internal 1001.tl-track id
title -- Title
external_ids -- List of available streaming ids
Run track_name.fetch() to get data.
"""
def __init__(self, url="", track_id=0, title="", external_ids={}):
self.url = url
self.track_id = track_id
self.title = title
self.external_ids = external_ids
self.soup = None
def __repr__(self):
title = f"<Title> {self.title}\n"
track_id = f"<ID> {self.track_id}\n"
external = f"<External> {[x for x in self.external_ids]}\n"
url = f"<URL> {self.url}...\n"
return url + title + track_id + external
def fetch(self):
"""Fetch title, track_id and external ids."""
if not self.soup:
self.soup = self.get_soup(self.url)
self.title = self.soup.find("h1", id="pageTitle").text.strip()
# Extract track id from <li title="add media links for this track">-element.
track_id_source = self.soup.find("li", title="add media links for this track")
try:
# Extract content of "onclick" attribute, which is a js-function.
track_id_source = track_id_source.get("onclick")
# Extract track id (after idItem-parameter) using regex.
self.track_id = re.search("(?<=idItem:\\s).[0-9]+", track_id_source).group(0)
except AttributeError:
print(track_id_source)
# Fetch external ids
self.fetch_external_ids()
def get_external(self, *services):
"""Returns external ids of passed streaming services.
Arguments:
services -- One or more streaming service names.
* for all.
Services:
spotify, video, apple, traxsource, soundcloud, beatport
"""
if services[0] == "*":
return self.external_ids
result = {}
for service in services:
try:
result[service] = self.external_ids[service]
except KeyError:
print(f"ERROR: No id found for {service}")
return result
def fetch_external_ids(self):
"""Fetch external ids."""
result = {}
URL = f"https://www.1001tracklists.com/ajax/get_medialink.php?idObject=5&idItem={self.track_id}&viewSource=1"
# Request all medialinks from 1001tl-API.
response = requests.get(URL).json()
# Add external ids to external_ids.
if response["success"]:
data = response["data"]
for elem in data:
try:
result[SOURCES[elem["source"]]] = elem["playerId"]
except KeyError:
print("Source: ", elem["source"], "not defined.")
self.external_ids = result
else:
print("Request failed:", response)
</code></pre>
<p>I think it'd be really helpful to get some thoughts of you guys!</p>
<p>I got two specific questions:</p>
<ul>
<li>Where to put constant configurations like SOURCES? Inside the class or outside the class?</li>
<li>Should I outsource the scraping stuff to an own class (Scraper) and let Track and Tracklist inherit scraping functions from that?</li>
</ul>
<p>Have a great day!</p>
|
[] |
[
{
"body": "<p>As a suggestion it is good to always maintain configuration outside the project and import it in the code and use it. And separating the similar functionality into individual files is also a good practice for a cleaner project structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T13:05:12.657",
"Id": "478138",
"Score": "0",
"body": "Thanks! So you're saying it would be better to make e.g. a Scraper-class in a separate file for all scraping-functionalities and just import that to the main file? What about the two separate classes \"Track\" and \"Tracklist\"? Tracklist depends on Track, as it stores Track-objects in a class variable. So the two should stay in the same file, am I right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T13:07:15.507",
"Id": "478139",
"Score": "0",
"body": "Yes that's correct. Similar functionality always keep them together. And any reusable functionality across the project should be separated under one module"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T12:02:31.557",
"Id": "243599",
"ParentId": "243598",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T10:41:17.280",
"Id": "243598",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Unofficial API for 1001tracklists.com"
}
|
243598
|
<p>I tried my hands on Rock-Paper-Scissors. But the twist is that the game has a brain that aims to learns your behaviour.</p>
<p>The brain is a simple counter that updates the player's current choice based on players previous choices. The <code>level</code> determines the number of previous choices cpu will remember. In any event the player tracks its own inputs and makes calculated choices to defeat the CPU, I have added a <a href="https://stackoverflow.com/a/15533404/8363478"><em>timed input</em></a> function i.e. if you don't provide input within 5 secs, you lose.</p>
<p>The game works perfectly, however I am unhappy with the <code>main</code> function. There are too many try-except blocks. My questions are</p>
<ul>
<li>What are possible improvements ?</li>
<li>How do I improve the <code>print_cpu_data</code> function in the way it shows the information ?</li>
<li>If I wish to make a GUI for the game (e.g tkinter, Pygame, etc), what part of the code should be made into functions and how to do so efficiently ?</li>
</ul>
<p>As I am not a beginner (somewhat less than intermediate) , I appreciate some advanced ideas and concepts.</p>
<pre class="lang-py prettyprint-override"><code>"""
Rock-Paper-Scissor with CPU
"""
from itertools import product
import select
import sys
SCORE_TABLE = [[1, 0, 2],
[2, 1, 0],
[0, 2, 1]]
SCORE_STR = ['LOSE', 'DRAW', 'WIN']
ROCK = 0
PAPER = 1
SCISSOR = 2
CHOICE_STR = ['ROCK', 'PAPER', 'SCISSOR']
WIN_MOVE = [PAPER, SCISSOR, ROCK]
class GameCpu:
"""Class to create game CPU"""
def __init__(self, level=1):
self.level = level
self.probs = {}
for t in product([ROCK, PAPER, SCISSOR], repeat=level):
self.probs[t] = [0, 0, 0]
self.prev = [0]*level
def get_cpu_choice(self):
"""Return CPU choice"""
tmp = self.probs[tuple(self.prev)]
pred = tmp.index(max(tmp))
return WIN_MOVE[pred]
def train_cpu(self, choice_player):
"""Train CPU with current player choice"""
self.probs[tuple(self.prev)][choice_player] += 1
self.prev.pop(0)
self.prev.append(choice_player)
def print_cpu_data(self):
"""Print CPU data"""
print('\nPattern', '\t'*self.level, 'Choice count\n')
for key, val in self.probs.items():
print(*[f'{CHOICE_STR[k]}' for k in key], sep=', ', end='\t\t')
print(*[f'{CHOICE_STR[i]}:{v}' for i, v in enumerate(val)])
def input_with_timeout(prompt, timeout):
"""Timed input"""
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.readline().rstrip('\n')
raise Exception
def main():
"""main function"""
while True:
try:
level = int(input('Enter CPU level (Level 1,2,3): '))
assert 1 <= level <= 3
break
except:
print('Invalid.')
print('\nPress Q to quit game\
\nRemember you have got only 5secs to give input.\
\nThe choices are ROCK:1 PAPER:2 SCISSOR:3\n')
cpu = GameCpu(level)
scores = [0, 0, 0]
timeout = 5
while True:
choice_player = None
try:
choice_player = input_with_timeout('Enter choice: ', timeout)
except:
print('Times up')
if not choice_player:
break
if choice_player.lower() == 'q':
break
try:
choice_player = int(choice_player)-1
assert 0 <= choice_player <= 2
except:
print('Invalid. ', end='\n')
continue
choice_cpu = cpu.get_cpu_choice()
s = SCORE_TABLE[choice_player][choice_cpu]
scores[s] += 1
print(f'{SCORE_STR[s]}')
cpu.train_cpu(choice_player)
total = max(1, sum(scores))
percent = [100*s/total for s in scores]
print('\nSTATS: \n')
print(f'Total games played: {total}')
print(*[f'{SCORE_STR[i]}:{p:.2f}% ' for i, p in enumerate(percent)])
cpu.print_cpu_data()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T19:10:46.550",
"Id": "478195",
"Score": "0",
"body": "When I executed your code it didn't allow me to intoduce any input, only the level of the CPU"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T06:04:19.253",
"Id": "478228",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<h3>How do I improve the print_cpu_data function in the way it shows the information ?</h3>\n\n<p>Well, nowadays the most common architectural pattern (design scheme) for many projects is the MVC its principle is to separate the classes and code constructs in your project into 3 packages (model-view-controller)</p>\n\n<ul>\n<li>In the model goes <em>all the code which constitutes your application logic</em> for example your class <code>GameCpu</code></li>\n<li>In the view goes <em>the code which displays the information that the user is supposed to see</em> in exmaple a class which uses <code>tkinter, Pygame</code> etc.</li>\n<li>In the controller goes the code which allows communication between model and view.</li>\n</ul>\n\n<p>You need to be aware that Desktop apps and Web apps have a different approach for the MVC due its nature.</p>\n\n<h3>If I wish to make a GUI for the game (e.g tkinter, Pygame, etc), what part of the code should be made into functions and how to do so efficiently ?</h3>\n\n<p>As I said, you could use an MVC pattern which is basically 3 packages named model, view, controller and import classes accordingly.</p>\n\n<p>I believe your question is more likely to be answered with <strong>modularization</strong> and <strong>refactoring</strong></p>\n\n<p>Modularization is to split independent code blocs into functions, and refactoring is to simplify the code you have written.</p>\n\n<p>Well, I hope it helped you, maybe you need a couple of youtube videos to understand how MVC works. I know, it seems more work, but when you are debugging medium to semi-large <em>personal projects</em> it is worthy, in great scale projects its indispensable. (not just MVC, to use an architectural pattern with an enterprise architecture [the names makes it sound complex but actually it isn't]).</p>\n\n<p>Note: You may ask why did i not answered your first question, well, the code does not work when I execute it, so I can't make suggestions in the air, plus if I recommend a new form to solve this problem, many mods request answers to be bassed on the poster's code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T19:29:47.537",
"Id": "243632",
"ParentId": "243602",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T12:41:26.470",
"Id": "243602",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissor with a CPU (console)"
}
|
243602
|
<p>Is there a way I could simplify this with Sass or JS? It works, but it's not what I'd call 'DRY' code. An alternate form I've tried is a Sass <code>for</code> loop but can't get it to work.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
margin-top: 10px;
opacity: 1;
color: black;
font-size: 55px;
-webkit-background-clip: text;
text-shadow: 1px 1px 5px rgb(167, 167, 167);
animation: fill 1s;
}
@keyframes fill {
0% {
-webkit-text-fill-color: rgba(0, 0, 0, 0);
}
2.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.025);
}
5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.05);
}
7.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.075);
}
10% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.1);
}
12.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.125);
}
15% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.15);
}
17.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.175);
}
20% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.2);
}
22.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.225);
}
25% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.25);
}
27.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.275);
}
30% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.3);
}
32.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.325);
}
35% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.35);
}
37.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.375);
}
40% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.4);
}
42.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.425);
}
45% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.45);
}
47.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.475);
}
50% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.5);
}
52.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.525);
}
55% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.55);
}
57.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.575);
}
60% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.6);
}
62.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.625);
}
65% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.65);
}
67.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.675);
}
70% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.7);
}
72.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.725);
}
75% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.75);
}
77.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.775);
}
80% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.8);
}
82.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.825);
}
85% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.85);
}
87.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.875);
}
90% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.9);
}
92.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.925);
}
95% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.95);
}
97.5% {
-webkit-text-fill-color: rgba(0, 0, 0, 0.975);
}
100% {
-webkit-text-fill-color: rgba(0, 0, 0, 1);
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>This Is A Test</h1></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>I think, I would make a special class for the style instead of having it as a style for all <code>h1</code>'s.</p>\n<p>You can IMO simplify the <code>keyframes</code> quite a bit in the following way:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.fade-in {\n margin-top: 10px;\n opacity: 1;\n color: rgba(0, 0, 0, 1);\n font-size: 55px;\n -webkit-background-clip: text;\n text-shadow: 1px 1px 5px rgb(167, 167, 167);\n animation-timing-function: steps(50, end);\n animation: fill 2s;\n}\n\n@keyframes fill {\n 0% {\n color: rgba(0, 0, 0, 0.1);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><h1 class=\"fade-in\">This Is A Test</h1></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>When I test it on my computer it seems to be the same effect.</p>\n<p><code>-webkit-text-fill-color</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-text-fill-color\" rel=\"nofollow noreferrer\">isn't standard</a>, so I wouldn't rely on using it at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:45:55.287",
"Id": "478450",
"Score": "1",
"body": "Good thinking. I knew there was a better way!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T18:51:47.247",
"Id": "243677",
"ParentId": "243603",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "243677",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T12:53:43.937",
"Id": "243603",
"Score": "4",
"Tags": [
"javascript",
"html",
"css",
"sass"
],
"Title": "Keyframes animation"
}
|
243603
|
<p>I want to implement in openMP a loop that terminates when a certain condition holds. In serial code the function body would simply be</p>
<pre><code>for(; begin < end; ++begin)
if(pred(begin))
return true;
return false;
</code></pre>
<p>The openMP version may differ in two respects: (1) concurrent function calls to <code>pred()</code> are not truncated and (2) the order of calls to <code>pred()</code> may be anything. However, it must not be assumed that calls to <code>pred()</code> are all equally expensive.</p>
<pre><code>/// loop until pred(i) returns true;
/// \return whether loop was terminated
template<typename index, typename predicate>
bool loop_until(index begin, index end, predicate const&pred)
{
const index chunk_size = std::max(index(1), index((begin-end)/(8*omp_get_num_threads())));
std::atomic<bool> stop{false};
std::atomic<index> next_chunk{begin};
# pragma omp parallel
{
for(index beg_chunk = next_chunk.fetch_add(chunk_size);
beg_chunk < end && !stop;
beg_chunk = next_chunk.fetch_add(chunk_size))
for(index end_chunk = std::min(beg_chunk+chunk_size,end);
beg_chunk < end_chunk && !stop;
++beg_chunk)
if(pred(beg_chunk))
stop = true;
}
return stop;
}
</code></pre>
<p>I'm a bit rusty on openMP hence my questions:</p>
<ul>
<li>Is the code correct?</li>
<li>Is there a more openMPish or better way to code this?</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T12:53:58.493",
"Id": "243604",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"openmp"
],
"Title": "openMP implementation of loop until predicate met"
}
|
243604
|
<p>I'm trying to implement a SQL transaction management in Node.js, that would append queries to an existing transaction if available, or create a new one if none exists yet, thanks to an optional
<code>connection</code> parameters. I'm using the <a href="https://www.npmjs.com/package/mysql" rel="nofollow noreferrer"><code>mysql</code></a> NPM package, and after having had a look to their (rather small) <a href="https://www.npmjs.com/package/mysql#transactions" rel="nofollow noreferrer">section about transactions</a>, I came up with the following:</p>
<pre class="lang-js prettyprint-override"><code>import mysql from "mysql";
const pool = mysql.createPool({
...
});
const _getConnection = () => new Promise((resolve, reject) => {
pool.getConnection((error, connection) => {
if (error) {
reject(error);
} else {
resolve(connection);
}
});
});
const _beginTransaction = (connection) => new Promise((resolve, reject) => {
connection.beginTransaction((error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
const _commitTransaction = (connection) => new Promise((resolve, reject) => {
connection.commit((error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
const _rollbackTransaction = (connection) => new Promise((resolve) => {
connection.rollback(resolve);
});
const _transactional = async (run, retry = true) => {
const connection = await _getConnection();
await _beginTransaction(connection);
try {
const result = await run(connection);
await _commitTransaction(connection);
return result;
} catch (error) {
await _rollbackTransaction(connection);
const errorCode = error && error.code;
if ("ER_LOCK_DEADLOCK" === errorCode && retry) {
return _transactional(run, false);
} else {
throw error;
}
} finally {
connection.release();
}
};
export const transactional = (run) => async (...args) => {
if (args.length) {
const lastArg = args[args.length - 1];
if (lastArg && "PoolConnection" === lastArg.constructor.name) {
return run(...args);
}
}
return _transactional(async (connection) => run(...[...args].concat(connection)));
};
export const query = (sql, values, connection) => new Promise((resolve, reject) => {
connection.query(sql, values, (error, results) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
</code></pre>
<p>Now, in some other file:</p>
<pre class="lang-js prettyprint-override"><code>import { transactional, query } from "./..."
export const fn1 = transactional(async (x, y, z, connection) => {
const result = await query("...", [x, y], connection);
return query("...", [result.id, z], connection);
});
export const fn2 = transactional(async (x, y, z, connection) => {
// passing the connection instance to fn1,
// so that it does not create a new transaction,
// but rather use the one created by fn2
// (where this connection instance comes from):
await fn1(x, y, z, connection);
return query("...", [], connection);
});
</code></pre>
<p>Finally, in some other file again:</p>
<pre class="lang-js prettyprint-override"><code>// fn1 will create its own transaction since none is passed:
await fn1(x, y, z);
// fn2 will create its own transaction since none is passed,
// but when it calls fn1, that same transaction will be used:
await fn2(x, y, z);
</code></pre>
<hr>
<p>This seems to do the job quite nicely so far, but we aren't really under heavy load yet, more in a kind of "beta-live" state at the moment.</p>
<p>So the question is, will it scale? Do you see any issue with this implementation? I don't like reinventing square wheels, but I couldn't find such implementation already.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T14:22:56.387",
"Id": "478153",
"Score": "0",
"body": "Your using pool connections, that is one of the ways to avoid the pitfalls of what I was saying in SO, didn't notice in SO you was using a Pool. I personally use a single connection and handle concurrency inside node. But the only thing I would say about the code above, I personally would use a separate `try finally` for your `_getConnection` because if `_beginTransaction` fails for any reason you will leak connections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T14:42:53.160",
"Id": "478154",
"Score": "0",
"body": "@Keith, interesting! So with a single `connection`, you can't really use SQL transactions though, can you? You'll face contention and locking issues as soon as concurrency occurs otherwise I guess? Would you mind providing a small overview of how this single-connection approach would look like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T15:27:14.910",
"Id": "478159",
"Score": "0",
"body": "Yes, you just have to serialise access to the connection, I just use a global promise for this. You can also mix this with pooling too. To be honest not sure if this gives any more performance gains or not. The reason I use this approach is because I can use with other DB's too, like SQLite where I've found transaction handling to be a bit harsh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T15:42:59.547",
"Id": "478162",
"Score": "0",
"body": "@Keith Oh ok, fair enough :) But good point about the `finally`, I'll move the call to `_beginTransaction` inside the `try` block (not sure why I didn't do it in the first place to be honest)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T13:35:17.933",
"Id": "243607",
"Score": "1",
"Tags": [
"mysql",
"node.js",
"transactions"
],
"Title": "SQL transaction management in Node.js with MySQL: use the existing transaction or create a new one if none exists"
}
|
243607
|
<p>I wrote a simple transpiler (that may be a bit of a stretch) in perl to cut down on some boiler plate code.
I'm very new to perl, this being maybe my third ever project in it. My main question would be to ask for feedback on my regular expressions and making it more open to expansion (adding error messages, etc).</p>
<p>My code:</p>
<pre><code>#!/usr/bin/perl
$/ = undef;
while(<>) {
print "#include <SDL2/SDL.h>\n#include <stdint.h>\n\n";
s/.include ([^;]+);/#include "\1"/g;
s/^include ([^;]+);/#include <\1>/g;
s/entry:/int main(void) {/g;
s/entry ([A-z][A-z0-9]*)\s*,\s*([A-z][A-z0-9]*)\s*:/int main(int \1, char* \2\[\]) {\n\tSDL_Init(SDL_INIT_EVERYTHING);/g;
s/([A-z][A-z0-9]*)\s+:u(8|16|32|64)(\**)/uint\2_t\3 \1/g;
s/([A-z][A-z0-9]*)\s+:(8|16|32|64)(\**)/int\2_t\3 \1/g;
s/([A-z][A-z0-9]*)\s+:Color\s+({[^}]+})/struct { uint8_t r, g, b, a; }\1 = \2/g;
s/([A-z][A-z0-9]*)\s+:Color/struct\s+{ uint8_t r, g, b, a; }\1;/g;
s/([A-z][A-z0-9]*)\s+:-([A-z][A-z0-9]*)/struct \2 \1/g;
s/([A-z][A-z0-9]*)\s+:Win\s*{([^}]+)}/SDL_Window* \1 = SDL_CreateWindow(\2)/g;
s/([A-z][A-z0-9]*)\s+:Win/SDL_Window* \1/g;
s/([A-z][A-z0-9]*)\s+:Ren\s*{([^}]+)}/SDL_Renderer* \1 = SDL_CreateRenderer(\2)/g;
s/([A-z][A-z0-9]*)\s+:Ren/SDL_Renderer* \1/g;
s/@([A-z][A-z0-9]*)\s*\(([^)]+)\)/typedef struct \1 {\2} \1;/g;
s/([A-z][A-z0-9]*)\s+:@@\s*\(([^)]+)\)/struct {\2}\1;/g;
s/@/struct /g;
s/([A-z][A-z0-9]*)\s+:([A-z][A-z0-9]*) ({[^}]*})/\2 \1 = \3/g;
s/([A-z][A-z0-9]*)\s+:([A-z][A-z0-9]*)/\2 \1/g;
s/Wait\s+a\s+minute!!!/SDL_Delay(60*1000);/g;
s/wait\s+([0-9bx]+)/SDL_Delay(\1)/g;
s/clear\s+([A-z][A-z0-9]*)/SDL_RenderClear(\1)/g;
s/set\s+([A-z][A-z0-9]*)\s+color\s+to\s+([A-z][A-z0-9]*)/SDL_SetRenderDrawColor(\1, \2.r, \2.g, \2.b, \2.a)/g;
s/set\s+([A-z][A-z0-9]*)\s+([A-z][A-z0-9]*)\s+to\s+([A-z0-9*\/+-]+)/\1.\2 = \3/g;
s/show\s+([A-z][A-z0-9]*)/SDL_RenderPresent(\1)/g;
s/([A-z][A-z0-9]*)\s([A-z][A-z0-9]*\**)\s+([A-z][A-z0-9]*)\s*:/void \1(\2 \3) {/g;
s/([A-z][A-z0-9]*)\s*:/void \1(void) {/g;
s/-!-/}/g;
print;
}
print "\n";
</code></pre>
<p>Sample input:</p>
<pre class="lang-c prettyprint-override"><code>q :@@(
a :u8;
)
@pixel (
r :u8; g :u8; b :u8; a :u8;
)
huh a :u8*:
-!-
letmecheck this :pixel:
-!-
entry:
p :pixel {0, 255, 0, 255};
win :Win {"Hello world!", 300, 300, 600, 600, 0};
ren :Ren {win, -1, 0};
set p g to 127;
set ren color to p;
clear ren;
show ren;
wait 500;
set p b to 127;
set ren color to p;
clear ren;
show ren;
wait 500;
set p r to 127;
set ren color to p;
clear ren;
show ren;
wait 500;
-!-
</code></pre>
<p>output:</p>
<pre class="lang-c prettyprint-override"><code>#include <SDL2/SDL.h>
#include <stdint.h>
struct {
uint8_t a;
}q;
typedef struct pixel {
uint8_t r; uint8_t g; uint8_t b; uint8_t a;
} pixel;
void huh(uint8_t* a) {
}
void letmecheck(pixel this) {
}
int main(void) {
pixel p = {0, 255, 0, 255};
SDL_Window* win = SDL_CreateWindow("Hello world!", 300, 300, 600, 600, 0);
SDL_Renderer* ren = SDL_CreateRenderer(win, -1, 0);
p.g = 127;
SDL_SetRenderDrawColor(ren, p.r, p.g, p.b, p.a);
SDL_RenderClear(ren);
SDL_RenderPresent(ren);
SDL_Delay(500);
p.b = 127;
SDL_SetRenderDrawColor(ren, p.r, p.g, p.b, p.a);
SDL_RenderClear(ren);
SDL_RenderPresent(ren);
SDL_Delay(500);
p.r = 127;
SDL_SetRenderDrawColor(ren, p.r, p.g, p.b, p.a);
SDL_RenderClear(ren);
SDL_RenderPresent(ren);
SDL_Delay(500);
}
</code></pre>
<p>I am open to any and all feedback, thanks in advance!</p>
<p><strong>EDIT: This is asking for a review of the PERL code, not the C code</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T23:04:05.537",
"Id": "478545",
"Score": "1",
"body": "It's a good idea, but a not so good implementation. You should take a look at compiler construction. Regexes will greatly limit you in speed and development efficiency; You should use a lexer and parser instead. A side note: I like your regexes :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:07:34.903",
"Id": "490639",
"Score": "0",
"body": "Not mentioned by answers: You have a bug. `A-z` should be `A-Za-z`. These are not equivalent."
}
] |
[
{
"body": "<blockquote>\n <p>open to expansion</p>\n</blockquote>\n\n<p><strong>Avoid naked undocumented numbers</strong></p>\n\n<p>Code has <code>SDL_Delay(500);</code> 3 times. Are the values related? 500 what?</p>\n\n<p>Since it is likely the values are to change in common, create code the reflects that. This makes for easier to expand/maintain code.</p>\n\n<pre><code>#define VIEWING_PAUSE (500 /* ms */)\n\n// SDL_Delay(500);\nSDL_Delay(VIEWING_PAUSE);\n</code></pre>\n\n<p>Likewise for 127, 300, 600 .... as maybe <code>HALF_RED, WIDTH, HEIGHT</code></p>\n\n<blockquote>\n <p>I am open to any and all feedback</p>\n</blockquote>\n\n<p><strong>Minor: keywords</strong></p>\n\n<p>When forming C code, even though not required, recommend to avoid C++ keywords like <code>this</code>. (<code>delete</code>, <code>new</code>, <code>class</code>, ....)</p>\n\n<pre><code>// void letmecheck(pixel this) {\nvoid letmecheck(pixel this_pixel) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:52:18.490",
"Id": "478176",
"Score": "1",
"body": "I think I need to adjust the question in some way. I was actually asking for advice on the perl code that outputs the C code that you responded too. Sorry about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T17:00:49.320",
"Id": "478179",
"Score": "0",
"body": "@Shipof123 My thoughts here are meant to imply a change to the perl code to effect the suggested changes in C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T17:41:35.317",
"Id": "478185",
"Score": "1",
"body": "I think that adding definitions into the perl output could cause collisions, that being said, adding comments into the output code that reflect the input would be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T07:25:26.533",
"Id": "478231",
"Score": "1",
"body": "The repetitions of 500 come from the **input** to the perl code. The transpiler could recognize repeated constants in the input and turn them into a single definition, but that's a feature request and not a code review."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:13:08.273",
"Id": "243619",
"ParentId": "243612",
"Score": "4"
}
},
{
"body": "<h2>Making shebang line more portable</h2>\n\n<p>Fixing the <code>perl</code> binary to <code>/usr/bin/perl</code> in the shebang will not work if you are using <code>perlbrew</code> instead of the system <code>perl</code>. Using <code>/usr/bin/env perl</code> will be a more portable alternative.</p>\n\n<h2>use <code>strict</code> and <code>warnings</code> pragmas to catch error at an early stage</h2>\n\n<p>By adding <code>warnings</code> you will get quite a few warnings, as discussed below.</p>\n\n<h2>Unescaped left brace in a regex is deprecated and will be illegal from perl version 5.32 on</h2>\n\n<p>You have two lines (line 11 and 21) where you have used a literal <code>{</code> in your regex without escaping it. The warning you will get is:</p>\n\n<pre><code>Unescaped left brace in regex is deprecated here (and will be fatal in Perl 5.32), passed through in regex; marked by <-- HERE in m/([A-z][A-z0-9]*)\\s+:([A-z][A-z0-9]*) ({ <-- HERE [^}]*})/ \n</code></pre>\n\n<h2>Unrecognized escape <code>\\s</code> used in substitution text</h2>\n\n<p>On line 12 you have a <code>\\s</code> in the substitution text. This is not a valid escape in a text string (it is only valid in the regex part of the substitution operator).</p>\n\n<pre><code>Unrecognized escape \\s passed through at ./p.pl line 12.\n</code></pre>\n\n<p>You can replace <code>\\s+</code> with a single space for example.</p>\n\n<h2>\\1 better written as $1</h2>\n\n<p>Replace all uses of the back references <code>\\1</code>, <code>\\2</code>, <code>\\3</code> with <code>$1</code>, <code>$2</code>, <code>$3</code>, see <a href=\"https://perldoc.perl.org/perlre.html#Warning-on-%5c1-Instead-of-%241\" rel=\"noreferrer\">perldoc perlre</a> for the details behind this warning.</p>\n\n<h2>Use <code>say</code> instead of <code>print</code> to avoid having to type <code>\\n</code> at the end of a string.</h2>\n\n<p>Since perl version 5.10 you can add <code>use feature qw(say)</code> to your program to use this feature.</p>\n\n<h2>use <code>local</code> to avoid clobbering special (global) variables</h2>\n\n<p>Even if it is not necessary in your short program, you should localize <code>$/</code> when you set it to <code>undef</code>: This will avoid bugs from creeping in at a later time when your program grows larger. If you do not localize the variable it will be set globally for your whole program to <code>undef</code>.</p>\n\n<h2>Use dedicated parsing modules to simplify maintenance and readability of your code</h2>\n\n<p>Your code is already starting to become hard to read and maintain (due to the complicated syntax of the regexes). Consider using a dedicated grammar and a parser like <a href=\"https://metacpan.org/pod/Regexp::Grammars\" rel=\"noreferrer\"><code>Regexp::Grammars</code></a> to make your program readable and easier to maintain.</p>\n\n<p>Here is a modified version of your code incorporating some of the changes suggested above:</p>\n\n<pre><code>#!/usr/bin/env perl\n\nuse feature qw(say);\nuse strict;\nuse warnings;\n\nlocal $/ = undef;\nwhile(<>) {\n say \"#include <SDL2/SDL.h>\\n#include <stdint.h>\\n\";\n s/.include ([^;]+);/#include \"$1\"/g;\n s/^include ([^;]+);/#include <$1>/g;\n s/entry:/int main(void) {/g;\n s/entry ([A-z][A-z0-9]*)\\s*,\\s*([A-z][A-z0-9]*)\\s*:/int main(int $1, char* $2\\[\\]) {\\n\\tSDL_Init(SDL_INIT_EVERYTHING);/g;\n s/([A-z][A-z0-9]*)\\s+:u(8|16|32|64)(\\**)/uint$2_t$3 $1/g;\n s/([A-z][A-z0-9]*)\\s+:(8|16|32|64)(\\**)/int$2_t$3 $1/g;\n s/([A-z][A-z0-9]*)\\s+:Color\\s+(\\{[^}]+\\})/struct { uint8_t r, g, b, a; }$1 = $2/g;\n s/([A-z][A-z0-9]*)\\s+:Color/struct { uint8_t r, g, b, a; }$1;/g;\n s/([A-z][A-z0-9]*)\\s+:-([A-z][A-z0-9]*)/struct $2 $1/g;\n s/([A-z][A-z0-9]*)\\s+:Win\\s*{([^}]+)}/SDL_Window* $1 = SDL_CreateWindow($2)/g;\n s/([A-z][A-z0-9]*)\\s+:Win/SDL_Window* $1/g;\n s/([A-z][A-z0-9]*)\\s+:Ren\\s*{([^}]+)}/SDL_Renderer* $1 = SDL_CreateRenderer($2)/g;\n s/([A-z][A-z0-9]*)\\s+:Ren/SDL_Renderer* $1/g;\n s/@([A-z][A-z0-9]*)\\s*\\(([^)]+)\\)/typedef struct $1 {$2} $1;/g;\n s/([A-z][A-z0-9]*)\\s+:@@\\s*\\(([^)]+)\\)/struct {$2}$1;/g;\n s/@/struct /g;\n s/([A-z][A-z0-9]*)\\s+:([A-z][A-z0-9]*) (\\{[^}]*\\})/$2 $1 = $3/g;\n s/([A-z][A-z0-9]*)\\s+:([A-z][A-z0-9]*)/$2 $1/g;\n s/Wait\\s+a\\s+minute!!!/SDL_Delay(60*1000);/g;\n s/wait\\s+([0-9bx]+)/SDL_Delay($1)/g;\n s/clear\\s+([A-z][A-z0-9]*)/SDL_RenderClear($1)/g;\n s/set\\s+([A-z][A-z0-9]*)\\s+color\\s+to\\s+([A-z][A-z0-9]*)/SDL_SetRenderDrawColor($1, $2.r, $2.g, $2.b, $2.a)/g;\n s/set\\s+([A-z][A-z0-9]*)\\s+([A-z][A-z0-9]*)\\s+to\\s+([A-z0-9*\\/+-]+)/$1.$2 = $3/g;\n s/show\\s+([A-z][A-z0-9]*)/SDL_RenderPresent($1)/g;\n s/([A-z][A-z0-9]*)\\s([A-z][A-z0-9]*\\**)\\s+([A-z][A-z0-9]*)\\s*:/void $1($2 $3) {/g;\n s/([A-z][A-z0-9]*)\\s*:/void $1(void) {/g;\n s/-!-/}/g;\n print;\n}\n\nsay \"\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T19:08:05.173",
"Id": "243631",
"ParentId": "243612",
"Score": "11"
}
},
{
"body": "<p>Along with the excellent answer of <a href=\"https://codereview.stackexchange.com/a/243631/225887\">Håkon Hægland</a>,</p>\n<p>Use perl's quoted regexes to simplify your code and improve readability massively.</p>\n<pre><code>my $keyword = qr/[A-z][A-z0-9]*/; \nmy $bits = qr/(?:8|16|32|64)/;\n</code></pre>\n<p>Makes:</p>\n<pre><code>s/entry ([A-z][A-z0-9]*)\\s*,\\s*([A-z][A-z0-9]*)\\s*:/int main(int \\1, char* \\2\\[\\]) {\\n\\tSDL_Init(SDL_INIT_EVERYTHING);/g;\ns/([A-z][A-z0-9]*)\\s+:u(8|16|32|64)(\\**)/uint\\2_t\\3 \\1/g;\n</code></pre>\n<p>into</p>\n<pre><code>s/entry ($keyword)\\s*,\\s*($keyword)\\s*:/int main(int \\1, char* \\2\\[\\]) {\\n\\tSDL_Init(SDL_INIT_EVERYTHING);/g;\ns/($keyword)\\s+:u($bits)(\\**)/uint\\2_t\\3 \\1/g;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:55:22.643",
"Id": "243671",
"ParentId": "243612",
"Score": "7"
}
},
{
"body": "<p>First of all, let me mention that if you want to build a production quality, maintainable, and scalable transpiler you should not do it using regular expressions. That is regardless of the language in which the regular expressions are written, even if perl. Without going into much detail, regular expressions work on plain text, and you need more than that to do anything non-trivial. You can look into compiler theory if you want to learn more about that.</p>\n<p>For your use, namely converting something you have full control over into something else you also have full control over in a simple line-by-line conversion, and that <em>only you will use</em> this is fine. Others have discussed the quality of your current code, I won't go into that.</p>\n<p>I will, however, mention that undocumented regular expressions are <em>very</em> hard to maintain. You should at least document each well - Perl has a verbose form well suited for this. You should have test cases that ensures that if you put in a known source file, you get exactly what you expect out in the other end. If not, something broke.</p>\n<p>You may also want to consider peer review. Have a colleague or fellow student to look at your code and listen to what baffles them. If it confuses them now, it will confuse you too later when you have forgotten the tiny details, which happens to each and every programmer at some point, and THAT is when important projects get rewritten. At the current state you will probably have a hard time convincing anybody to inherit maintainership of your code.</p>\n<p>Good luck - this is a very good exercise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T10:58:52.347",
"Id": "243712",
"ParentId": "243612",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T15:11:34.057",
"Id": "243612",
"Score": "12",
"Tags": [
"c",
"regex",
"perl",
"language-design"
],
"Title": "Simple C transpiler"
}
|
243612
|
<p>I have made a script to convert number from any base to decimal.</p>
<p>I am trying to optimize the code because I think it is bloated and can be improved but if I change anything it affects error handling negatively.
I tried removing the two while loops but then the user would need to enter their number again even if they only messed up their base that is something I want to avoid.</p>
<p>I think printing and handling the number can be optimized but I just cannot see how. Also if anyone can help me improve my code readability that would be helpful too.</p>
<pre><code>while True: #Main loop will keep the script running until user exits
negative_flag=False #flag to check if a value is negative or not. False by default
while True: # Loop made so that any error can be handled if input is not number
number=input("Enter a number : ")
try:
if type(int(number))==int:
break
except:
print("Wrong input. Only integers are allowed.")
continue
while True: # Loop made so that any error can be handled if input is not number
base_from=input("Enter the base number is in : ")
try:
if type(int(base_from))==int and int(base_from)>=2:
break
else:
print("Base should be greater than or equal to 2")
except:
print("Wrong input. Only integers are allowed.")
continue
if int(number)<0: #Check if a number is negative if it is convert it into a postive
(number)=int(number)*-1
negative_flag=True
number=str(number)
#Not useful just for reference base_to=10
number_size=len(number)
number_holder=0
for x in number: #Basic conversion of a number to decimal number system.
number_size-=1
base_raised=int(base_from)**number_size
number_multiplied=base_raised*int(x)
number_holder=number_holder+number_multiplied
if negative_flag==True: # Prints if the value is -ve
print( number_holder*-1 )
else:
print(number_holder)
while True: # Final loop asking users if they want to exit or not
response=input("Do you want to continue?(y or n) - ")
if response=='n' or response=='y':
break
else:
print("Wrong input")
continue
if response == 'n': # Conditions for only two valid answer.
break
elif response == 'y':
continue
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T18:51:01.910",
"Id": "478193",
"Score": "0",
"body": "Is your goal to [reinvent-the-wheel](https://codereview.stackexchange.com/questions/tagged/reinventing-the-wheel)? Because if not, 90% of your script code be replaced with one statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T06:05:58.310",
"Id": "478330",
"Score": "0",
"body": "@AJNeufeld I am just trying to learn. I know the functions already exist, doesn't mean I can't try to recreate them. I used to program in C so i am just trying to replicate as much code as I can in python, then start using the inbuilt functions once I get the hang of the language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T13:30:55.030",
"Id": "478358",
"Score": "0",
"body": "That's perfectly valid. If you know the function exists, but still want to implement it yourself, for practice or a better understanding of the inner workings, we call that \"reinventing the wheel\". Tagging the question with that tag is a signal for reviewers to ignore the \"just replace this lump of code with this one function call\" quick review option and instead provide more feedback on the \"lump of code\" itself. I'll add the tag for you, then I'll have to update my answer post accordingly."
}
] |
[
{
"body": "<h1>Typically, you have a single loop while user is doing input</h1>\n\n<p>Use try/except to handle loop flow.\nThe order you get things makes a difference as the next input's correctness may depend on previous input.</p>\n\n<h1>Separate out your steps into methods</h1>\n\n<p>There are three distinct parts to your flow, loop could be simplified by calling your methods one by one.</p>\n\n<h1>Indentation is important</h1>\n\n<p>My solution is untested (on my phone), but should give you a base to work off.</p>\n\n<p>More comments inline</p>\n\n<pre><code># you should only need one loop for stuff like this...\nnumber = None\nbase_from = None\nbase_to = 10 # this is implied by your code. You could allow user to specify this too...\nwhile True: #Main loop will keep the script running until user exits\n negative_flag=False #flag to check if a value is negative or not. False by default\n base_from=input(\"Enter the base number is in : \") if base_from is None else base_from # don't get this if we have it already\n try:\n base_from = int(base_from) # just want an int\n if base_from <= 1:\n raise ValueError(\"Base should be greater than or equal to 2\")\n except ValueError as e: # two types of ValueError, one is not int, other is less than 2\n base_from = None # need to clear this to get it again as current value is not ok\n print(\"Wrong input. {}\".format(e)) # you can make the messages friendlier yourself\n continue\n number=input(\"Enter a number : \") if number is None else number # keep this check simple. Ensure number is either None or set correctly\n try:\n # of course this only works for bases less than or equal to 10 as you haven't specified the notation for higher bases...\n result = 0\n for char in number:\n if char == '-':\n negative_flag = True\n continue\n result *= base_from # mathematically identical to 'shift left' in specified base\n digit = int(char) # int() raises ValueError if char is not int\n if not (0<=digit<base_from):\n raise ValueError(\"digits must be between 0 and {} for base {}\".format(base_from-1,base_from))\n # digit must be ok...\n result += digit\n except ValueError as e: # only catch specific exception... we don't know how to (and shouldn't) handle other exceptions here\n number = None # need to reset this to start over as the number is not ok\n print(\"Wrong input. {}\".format(e))\n continue\n print(-result if negative_flag else result)\n\n # this one could be a separate loop depending how fancy you need it. But if that is the case, should be a separate method and call it and either break or continue based on return value... shouldn't throw exceptions as that will be difficult to catch here\n response=input(\"Do you want to continue?(y or n) - \")\n if response.lower().startswith('n'):\n break\n else:\n base_from = None\n number = None\n continue\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:07:33.407",
"Id": "478163",
"Score": "0",
"body": "Answers on Code Review must include at least one insightful observation in the body of the post. Posting only a code dump with no further explanation goes against the point of Code Review which is to teach users to become better programmers. Rather than give users a fish that only lasts a day. Please [edit] your post to address this problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:10:50.147",
"Id": "478164",
"Score": "0",
"body": "comments are inline"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:17:54.670",
"Id": "478166",
"Score": "0",
"body": "Can you clarify the use of None in 'if base_from is None' .I know it is sort of null value but this is my first program in python so i am not sure about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:23:42.530",
"Id": "478168",
"Score": "0",
"body": "@arsh you're right, it's specifically setting it to None to indicate it is not set. There is a difference between setting to None and not declaring at all. If I left undeclared, it would be easy to hit a \"name 'basefrom' dose not exist\" - which is often hard to figure out why. However, setting to None is not always the right thing to do, better to leave undeclared in the case you do want things to break if names don't exist when you expect them to be. Here, we are looping until we get all the bits we need from the user, so we use None to indicate what we still need to get."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:37:49.760",
"Id": "478169",
"Score": "0",
"body": "Alright so basically we are checking if the value is Null or not. If it is, we take the input from the user and if not then we don't. Replacing the need for two while loops. Is that right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:43:33.613",
"Id": "478173",
"Score": "0",
"body": "In a nutshell, yes. Also the exception handling is simplified. Embrace the exceptions rather than avoid them. And raise extra ones if you have stricter criteria than python (ie, positive integer or integer within range). Don't catch Exception (the general Exception class) as a rule. Instead, catch all and only specific exceptions you can handle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:46:48.387",
"Id": "478174",
"Score": "0",
"body": "Note that I don't set result to None as that should never exist outside of where we set and display it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:02:10.300",
"Id": "243615",
"ParentId": "243614",
"Score": "3"
}
},
{
"body": "<h1>PEP-8</h1>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> has many recommendations for the formatting of Python code that all developers should (must!) follow. These include</p>\n<ul>\n<li>single blank space around binary operators, eg <code>negative_flag = False</code>, not <code>negative_flag=False</code></li>\n<li>no blanks after <code>(</code> or before <code>)</code>, eg <code>print(number_holder * -1)</code> not <code>print( number_holder*-1 )</code></li>\n</ul>\n<h1>Useless code</h1>\n<p><code>int(number)</code> can only ever return an <code>int</code>, or raise an exception. There are no other possibilities. So if no exception is raised, the <code>if</code> condition will always be true, making the <code>if</code> statement an unnecessary control structure:</p>\n<pre><code>try:\n if type(int(number)) == int:\n ...\nexcept:\n ...\n</code></pre>\n<p>Similarly you only exit this loop if <code>response == 'n' or response == 'y'</code></p>\n<pre><code>while True:\n response = input("Do you want to continue?(y or n) - ")\n if response=='n' or response=='y':\n break\n else:\n print("Wrong input")\n continue\n</code></pre>\n<p>So why test both possibilities?</p>\n<pre><code>if response == 'n': # Conditions for only two valid answer.\n break\nelif response == 'y':\n continue\n</code></pre>\n<p>From the comment, it seems you have already realized this. So why <code>elif response == 'y':</code>? Why not simple <code>else:</code>?</p>\n<p>Finally, every last one of the <code>continue</code> statements is used as the last statement in a control structure, in a loop. Without the <code>continue</code> statement, the loop would be restarting anyway, so these can all be omitted.</p>\n<h1>Only catch the exceptions you expect</h1>\n<p>Consider this code:</p>\n<pre><code>while True:\n number = input("Enter a number : ")\n try:\n if type(int(number)) == int:\n break\n except:\n print("Wrong input. Only integers are allowed.")\n continue\n</code></pre>\n<p>Try pressing <code>Control-C</code> at the input prompt to quit the program. Whoops! Why isn't the program terminating? Because <code>Control-C</code> raises the <code>KeyboardInterrupt</code> exception, which you catch, display an inappropriate error messages, and then loop back for another try. How unexpected.</p>\n<p>You want to catch <code>ValueError</code> exceptions, only.</p>\n<pre><code>while True:\n try:\n number = int(input("Enter a number: "))\n break\n except ValueError:\n print("Wrong input. Only integers are allowed.")\n</code></pre>\n<p>Note the absence of useless <code>if</code> statements and <code>continue</code> statements.</p>\n<h1>Any Base?</h1>\n<p>Your program is supposed to convert from "any base" to decimal. But really, you only allow base 2 through base 10 input. You don't allow <code>FF</code> to be converted from base 16 to base 10.</p>\n<h1>To Base 10</h1>\n<p>You've got a lot of code to convert a number to base 10. This functionality is built-in to Python. If your intention is not <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a>, you should use the <a href=\"https://docs.python.org/3/library/functions.html?highlight=int#int\" rel=\"nofollow noreferrer\"><code>int(x, base=10)</code></a> function.</p>\n<h1>Reworked Code</h1>\n<pre><code>while True:\n\n number = input("Enter a number: ")\n\n while True:\n try:\n base = int(input("Enter the base the number is in: "))\n if base >= 2:\n break\n print("Base should be greater than or equal to 2")\n except ValueError:\n print("Wrong input. Only integers are allowed")\n\n try:\n print(int(number, base))\n except ValueError:\n print(f"Unable to convert {number!r} to base {base}")\n\n while True:\n response = input("Do you want to continue? (y or n): ")\n if response in {'y', 'n'}:\n break\n print("Wrong input")\n\n if response == 'n':\n break\n</code></pre>\n<p>Or super condensed:</p>\n<pre><code>print("Press Control-C to stop.")\nwhile True:\n try:\n print(int(input("Number: "), int(input("Base: "))))\n except ValueError as err:\n print("Invalid input:", err)\n except KeyboardInterrupt:\n print("Conversions to base-10 complete.")\n break\n\n\n \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T23:25:40.687",
"Id": "243641",
"ParentId": "243614",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243615",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T16:01:11.950",
"Id": "243614",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"reinventing-the-wheel",
"number-systems"
],
"Title": "Program to convert number from any base to decimal"
}
|
243614
|
<p>I'm wondering how to "beautify"/"simplify" this code:</p>
<pre class="lang-js prettyprint-override"><code>function handleKeyDown (e) {
if (e.key === 'Enter') {
e.preventDefault()
myCustomEvent(e)
return
}
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
e.key === 'ArrowDown'
? document &&
document.activeElement &&
document.activeElement.nextElementSibling &&
document.activeElement.nextElementSibling.focus()
: document &&
document.activeElement &&
document.activeElement.previousElementSibling &&
document.activeElement.previousElementSibling.focus()
}
}
</code></pre>
<p>It seems too verbose to me. Is there something I'm doing wrong? How can I write it better?</p>
|
[] |
[
{
"body": "<p>well I have a question, does <code>document && document.activeElement</code> is mandatory?</p>\n\n<p>If so, then there is a way to refactor it:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function handleKeyDown (e) {\n if (e.key === 'Enter') {\n e.preventDefault()\n myCustomEvent(e)\n return\n }\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n e.preventDefault()\n focusSibling(e.key === 'ArrowDown' && document && document.activeElement)\n }\n}\n\nfunction focusSibling(isNextElemSibling) {\n if (isNextElementSibling && document.activeElement.nextElementSibling)\n document.activeElement.nextElementSibling.focus()\n else if (document.activeElement.previousElementSibling)\n document.activeElement.previousElementSibling.focus()\n}\n\n</code></pre>\n\n<p>Note: Probably you didn't know, but when you do an if or a boolean (true or false) condition the program executes an AND <code>&&</code> operator from left to right, and if the first value is <code>false</code>, it stops the comparison, because if one value in an AND is false, the statement is false. So, that was a way to simplify your code.</p>\n\n<p>If <code>document && document.activeElement</code> is not mandatory, then only change this line:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> focusSibling(e.key === 'ArrowDown')\n</code></pre>\n\n<p>I hope it helped you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T18:26:06.383",
"Id": "243629",
"ParentId": "243627",
"Score": "2"
}
},
{
"body": "<p>It may be wise to consider <a href=\"https://dev.to/adriennemiller/semicolons-in-javascript-to-use-or-not-to-use-2nli\" rel=\"nofollow noreferrer\">not omitting semicolons</a> in your code</p>\n\n<p>To streamline the code, you can try extracting the 'focus'-function and use a small object to determine where to focus.</p>\n\n<pre><code>const tryToFocus = key => {\n e.preventDefault();\n const prevNext = {\n ArrowDown: \"nextElementSibling\",\n ArrowUp: \"previousElementSibling\"\n };\n if (Object.keys(prevNext).find(k => key === k)) {\n document &&\n document.activeElement &&\n document.activeElement[prevNext[key]] &&\n document.activeElement[prevNext[key]].focus();\n }\n}\n\nfunction handleKeyDown (e) {\n if (e.key === 'Enter') {\n e.preventDefault(); // may be handled in myCustomEvent?\n return myCustomEvent(e);\n }\n tryToFocus(e.key);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T11:41:18.743",
"Id": "243659",
"ParentId": "243627",
"Score": "2"
}
},
{
"body": "<p>Through clever usage of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring</a> and using objects to store possible events, you can do this.</p>\n<pre><code>function focus(key){\n const {activeElement:{[key]: elementSibling} = {}} = document;\n if(elementSibling){\n elementSibling.focus();\n }\n}\n\nconst ACTIONS = {\n ArrowDown: () => focus('nextElementSibling'),\n ArrowUp: () => focus('previousElementSibling'),\n Enter: (e) => myCustomEvent(e)\n}\n\nfunction handleKeyDown (e) {\n const handler = ACTIONS[e.key];\n if(handler) {\n e.preventDefault();\n handler(e);\n }\n}\n</code></pre>\n<p>Here is a working example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function focus(key){\n const {activeElement:{[key]: elementSibling} = {}} = document;\n if(elementSibling){\n elementSibling.focus();\n }\n}\n\nconst ACTIONS = {\n ArrowDown: () => focus('nextElementSibling'),\n ArrowUp: () => focus('previousElementSibling'),\n Enter: (e) => myCustomEvent(e)\n}\n\nfunction handleKeyDown (e) {\n console.log(e.key, e.target);\n const handler = ACTIONS[e.key];\n if(handler) {\n e.preventDefault();\n handler(e);\n }\n}\n\n// simulating an event\nwindow.addEventListener('keyup', handleKeyDown);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><h3>Click on an element then press ArrowUp or ArrowDown</h3>\n<input type=\"text\"/>\n<input type=\"text\"/>\n<input type=\"text\"/>\n<input type=\"text\"/></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T20:24:42.627",
"Id": "478736",
"Score": "1",
"body": "Really amazing! Do you mean `const { activeElement: { [key]: elementSibling } = {} } = document`, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T20:28:09.800",
"Id": "478738",
"Score": "1",
"body": "@FredHors good catch and no worries"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T18:32:29.660",
"Id": "507956",
"Score": "0",
"body": "I'm trying to use this code with Typescript today and it errors with: `(parameter) key: string\nType 'Element | {} | null' has no matching index signature for type 'string'.ts(2537)`. Any fix?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T23:45:22.497",
"Id": "507976",
"Score": "0",
"body": "Idk, I need more information to be able to help you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:18:35.680",
"Id": "508002",
"Score": "0",
"body": "https://stackoverflow.com/questions/66643784/how-to-fix-this-typescript-type-element-null-has-no-matching-index-sig"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:14:28.763",
"Id": "243666",
"ParentId": "243627",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243666",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T17:46:02.103",
"Id": "243627",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"ecmascript-8"
],
"Title": "Handling arrow keys and tabIndex"
}
|
243627
|
<p><a href="https://bitbucket.org/daniel_kashtan/raycaster/src/1f26fab702403f1bb04e303d4d5a7b7d52b6bc43/RayCaster1.cpp#lines-15" rel="nofollow noreferrer">Bitbucket link to repo</a></p>
<p><a href="https://lodev.org/cgtutor/raycasting.html" rel="nofollow noreferrer">Tutorial I have been following</a></p>
<p>I decided to make a raycaster app and try to understand how it really works. So far so good, I have it up and running. If you download the source and execute make, it should pop out a test.exe. I am developing on Ubunutu using Windows Subsystem for Linux 2. I have made changes to the tutorial and I have tried to code it from scratch while following the tutorial's algorithm. Performance is okay, but at 900x900 on my laptop, the frame-rate is about 40fps, which seems low. I cannot figure out where the bottlenecks are at this point. I'd expect to be clearing 100fps easily.</p>
<p>RayCaster1.cpp</p>
<pre><code>#include "include/SDLWrapper.h"
#include <iostream>
#include <vector>
#define WINDOW_WIDTH 900
#define mapWidth 24
#define mapHeight 24
//export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0
//run vcxsrv in windows "XLaunch"
//make sure to check access control checkbox and uncheck the opengl option
//./test.exe
int worldMap[mapWidth][mapHeight]=
{
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,2,2,2,2,2,0,0,0,0,3,0,3,0,3,0,0,0,1},
{1,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,2,0,0,0,2,0,0,0,0,3,0,0,0,3,0,0,0,1},
{1,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,2,2,0,2,2,0,0,0,0,3,0,3,0,3,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,0,4,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,0,0,0,0,5,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,0,4,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,0,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
};
uint32_t* rasterPixels = new uint32_t[WINDOW_WIDTH*WINDOW_WIDTH];
double posX = 22, posY = 12; //x and y start position
double dirX = -1, dirY = 0; //initial direction vector
double planeX = 0, planeY = 0.66; //the 2d raycaster version of camera plane
double moveSpeed; //the constant value is in squares/second
double rotSpeed; //the constant value is in radians/second
uint32_t red = 16711680;
uint32_t dark_red = 8388608;
uint32_t green = 65280;
uint32_t dark_green = 32768;
uint32_t blue = 255;
uint32_t dark_blue = 128;
uint32_t white = 16777215;
uint32_t gray = 8421504;
uint32_t yellow = 16776960;
uint32_t dark_yellow = 8421376;
void initRasterPixels(){
//Fill the raster with pixel information
for(int i = 0; i < WINDOW_WIDTH; i++) {
for(int j = 0; j < WINDOW_WIDTH; j++){
rasterPixels[i+(WINDOW_WIDTH*j)] = 0;
}
}
}
void addVerticalLineOfPixels(int row, uint32_t* rasterPixels, uint32_t color, int start, int end) {
for(int i = 0; i < WINDOW_WIDTH; i++) {
if(i >= start && i <= end) {
rasterPixels[(i*WINDOW_WIDTH)+row] = color;
} else {
rasterPixels[(i*WINDOW_WIDTH)+row] = 0;
}
}
}
uint32_t* generateRaster(KeyboardState keyboardState, double frameTime){
if (keyboardState.keyUp)
{
if(worldMap[int(posX + dirX * moveSpeed)][int(posY)] == false) posX += dirX * moveSpeed;
if(worldMap[int(posX)][int(posY + dirY * moveSpeed)] == false) posY += dirY * moveSpeed;
}
//move backwards if no wall behind you
if (keyboardState.keyDown)
{
if(worldMap[int(posX - dirX * moveSpeed)][int(posY)] == false) posX -= dirX * moveSpeed;
if(worldMap[int(posX)][int(posY - dirY * moveSpeed)] == false) posY -= dirY * moveSpeed;
}
//rotate to the right
if (keyboardState.keyRight)
{
//both camera direction and camera plane must be rotated
double oldDirX = dirX;
dirX = dirX * cos(-rotSpeed) - dirY * sin(-rotSpeed);
dirY = oldDirX * sin(-rotSpeed) + dirY * cos(-rotSpeed);
double oldPlaneX = planeX;
planeX = planeX * cos(-rotSpeed) - planeY * sin(-rotSpeed);
planeY = oldPlaneX * sin(-rotSpeed) + planeY * cos(-rotSpeed);
}
//rotate to the left
if (keyboardState.keyLeft)
{
//both camera direction and camera plane must be rotated
double oldDirX = dirX;
dirX = dirX * cos(rotSpeed) - dirY * sin(rotSpeed);
dirY = oldDirX * sin(rotSpeed) + dirY * cos(rotSpeed);
double oldPlaneX = planeX;
planeX = planeX * cos(rotSpeed) - planeY * sin(rotSpeed);
planeY = oldPlaneX * sin(rotSpeed) + planeY * cos(rotSpeed);
}
//main for loop for calculating wall heights
for(int x = 0; x < WINDOW_WIDTH; x++) {
//calculate ray position and direction
double cameraX = 2 * x / double(WINDOW_WIDTH) - 1; //x-coordinate in camera space, normalized, -1 is left, 1 is right, 0 is center
double rayDirX = dirX + planeX * cameraX;
double rayDirY = dirY + planeY * cameraX;
//which box of the map we are in
int mapX = int(posX);
int mapY = int(posY);
//length of ray from current position to next x or y-side
double sideDistX;
double sideDistY;
//length of ray from one x or y-side to next x or y-side
double deltaDistX = abs(1 / rayDirX);
double deltaDistY = abs(1 / rayDirY);
double perpWallDist;
//what direction to step in x or y-direction (either +1 or -1)
int stepX;
int stepY;
int hit = 0;
int side; //0 is x-side hit, 1 is y-side hit
//calculate step and initial sideDist
if (rayDirX < 0)
{
stepX = -1;
sideDistX = (posX - mapX) * deltaDistX;
}
else
{
stepX = 1;
sideDistX = (mapX + 1.0 - posX) * deltaDistX;
}
if (rayDirY < 0)
{
stepY = -1;
sideDistY = (posY - mapY) * deltaDistY;
}
else
{
stepY = 1;
sideDistY = (mapY + 1.0 - posY) * deltaDistY;
}
//perform DDA
while (hit == 0)
{
//jump to next map square, OR in x-direction, OR in y-direction
if (sideDistX < sideDistY)
{
sideDistX += deltaDistX;
mapX += stepX;
side = 0;
}
else
{
sideDistY += deltaDistY;
mapY += stepY;
side = 1;
}
//Check if ray has hit a wall
if (worldMap[mapX][mapY] > 0) hit = 1;
}
//Calculate distance projected on camera direction (Euclidean distance will give fisheye effect!)
if (side == 0) perpWallDist = (mapX - posX + (1 - stepX) / 2) / rayDirX;
else perpWallDist = (mapY - posY + (1 - stepY) / 2) / rayDirY;
//Calculate height of line to draw on screen
int lineHeight = (int)(WINDOW_WIDTH / perpWallDist);
//calculate lowest and highest pixel to fill in current stripe
int drawStart = -lineHeight / 2 + WINDOW_WIDTH / 2;
if(drawStart < 0)drawStart = 0;
int drawEnd = lineHeight / 2 + WINDOW_WIDTH / 2;
if(drawEnd >= WINDOW_WIDTH)drawEnd = WINDOW_WIDTH - 1;
//choose wall color
uint32_t color;
//give x and y sides different brightness
if (side == 1) {
switch(worldMap[mapX][mapY])
{
case 1: color = dark_red; break; //red
case 2: color = dark_green; break; //green
case 3: color = dark_blue; break; //blue
case 4: color = gray; break; //white
default: color = dark_yellow; break; //yellow
}
} else {
switch(worldMap[mapX][mapY])
{
case 1: color = red; break; //red
case 2: color = green; break; //green
case 3: color = blue; break; //blue
case 4: color = white; break; //white
default: color = yellow; break; //yellow
}
}
//draw the pixels of the stripe as a vertical line
uint32_t column[WINDOW_WIDTH];
addVerticalLineOfPixels(x, rasterPixels, color, drawStart, drawEnd);
}
//speed modifiers
moveSpeed = frameTime * 5.0;
rotSpeed = frameTime * 3.0;
return rasterPixels;
}
//Need a separate method here to handle input. The SDLWrapper will send inkeys and keypressed to be operated on here
//and have access to all the file scope vars like pos, wroldmap, dir, plane
int main(int /*argc*/, char */*argv*/[])
{
SDLWrapper sdlWrapper;
initRasterPixels();
sdlWrapper.setupSDLRenderer(WINDOW_WIDTH, generateRaster);
};
</code></pre>
<p>SDLWrapper.cpp</p>
<pre><code>#include <iostream>
#include <SDL2/SDL.h>
#include "include/SDLWrapper.h"
#include <SDL2/SDL_ttf.h>
#include <sstream>
#include <time.h>
using namespace std;
#define TICK_INTERVAL 4
static Uint32 next_time;
double currTime = 0; //time of current frame
double oldTime = 0; //time of previous frame
double frameTime; //frameTime is the time this frame has taken, in seconds
TTF_Font* sans_font;
////////////////////////////////////////////////////////////////////////////////
//KEYBOARD FUNCTIONS////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool SDLWrapper::keyDown(int key) //this checks if the key is held down, returns true all the time until the key is up
{
return (inkeys[key] != 0);
}
bool SDLWrapper::keyPressed(int key) //this checks if the key is *just* pressed, returns true only once until the key is up again
{
if(keypressed.find(key) == keypressed.end()) keypressed[key] = false;
if(inkeys[key])
{
if(keypressed[key] == false)
{
keypressed[key] = true;
return true;
}
}
else keypressed[key] = false;
return false;
}
///// End of KEYBOARD FUNCTIONS ////
int SDLWrapper::setupSDLRenderer(int WINDOW_WIDTH, uint32_t* (*generateRaster)(KeyboardState, double)){
SDL_Event event;
SDL_Renderer *renderer;
SDL_Window *window;
bool run = true;
KeyboardState keyboardState;
uint32_t color = 0;
printf("setupSDLRenderer start");
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
window = SDL_CreateWindow("test", 0, 0, WINDOW_WIDTH, WINDOW_WIDTH, SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
// https://gamedev.stackexchange.com/questions/157604/how-to-get-access-to-framebuffer-as-a-uint32-t-in-sdl2
SDL_Texture* framebuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, WINDOW_WIDTH, WINDOW_WIDTH);
uint32_t* pixels = new uint32_t[WINDOW_WIDTH*WINDOW_WIDTH];
if(TTF_Init()==-1) {
printf("TTF_Init: %s\n", TTF_GetError());
exit(2);
}
sans_font = TTF_OpenFont("font/Sans.ttf", 12); //this opens a font style and sets a size
if(!sans_font) {
printf("TTF_OpenFont: %s\n", TTF_GetError());
}
SDL_Rect message_rect; //create a rect
message_rect.x = 0; //controls the rect's x coordinate
message_rect.y = 0; // controls the rect's y coordinte
message_rect.w = 20; // controls the width of the rect
message_rect.h = 20; // controls the height of the rect
SDL_Texture* message;
next_time = SDL_GetTicks() + TICK_INTERVAL;
while (run) {
//Start of future render function
SDL_RenderClear(renderer);
rasterPixels = (*generateRaster)(keyboardState, frameTime);
SDL_UpdateTexture(framebuffer , NULL, rasterPixels, WINDOW_WIDTH * sizeof (uint32_t));
SDL_RenderCopy(renderer, framebuffer , NULL, NULL);
// printf("time_left: %d", time_left());
SDL_Delay(time_left()); //remove this to allow for more than 60 iterations a second
next_time = SDL_GetTicks() + TICK_INTERVAL;
//timing for input and FPS counter
oldTime = currTime;
currTime = SDL_GetTicks();
frameTime = (currTime - oldTime) * 0.001; //frameTime is the time this frame has taken, in seconds
SDL_Color White = {255, 255, 255}; // this is the color in rgb format, maxing out all would give you the color white, and it will be your text's color
std::stringstream ss;
ss << (int)(1.0 / frameTime);
const char* str = ss.str().c_str();
SDL_Surface* surfaceMessage = TTF_RenderText_Solid(sans_font, str, White); // as TTF_RenderText_Solid could only be used on SDL_Surface then you have to create the surface first
message = SDL_CreateTextureFromSurface(renderer, surfaceMessage); //now you can convert it into a texture
//Now since it's a texture, you have to put RenderCopy in your game loop area, the area where the whole code executes
SDL_RenderCopy(renderer, message, NULL, &message_rect); //you put the renderer's name first, the Message, the crop size(you can ignore this if you don't want to dabble with cropping), and the rect which is the size and coordinate of your texture
//Don't forget too free your surface and texture
SDL_RenderPresent(renderer);
while (SDL_PollEvent(&event)) {
keyboardState.reset();
//Start of handleInput function
if (event.type == SDL_QUIT) {
run = false;
}
inkeys = SDL_GetKeyboardState(NULL);
if (keyDown(SDL_SCANCODE_UP) || keyDown(SDL_SCANCODE_W)) {
keyboardState.keyUp = true;
} else if (keyDown(SDL_SCANCODE_DOWN) || keyDown(SDL_SCANCODE_S)) {
keyboardState.keyDown = true;
} else if (keyDown(SDL_SCANCODE_LEFT) || keyDown(SDL_SCANCODE_A)) {
keyboardState.keyLeft = true;
} else if (keyDown(SDL_SCANCODE_RIGHT) || keyDown(SDL_SCANCODE_D)) {
keyboardState.keyRight = true;
}
//End of handleInput function
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
uint32_t SDLWrapper::peek(int x, int y, int WINDOW_WIDTH){
return rasterPixels[x+(WINDOW_WIDTH*y)];
}
int SDLWrapper::time_left(void)
{
Uint32 now;
now = SDL_GetTicks();
//rendered too slow, don't wait
if(next_time < now) {
return 0;
}
else {
// rendered too fast, wait until the next tick amount
return next_time - now;
}
}
void KeyboardState::reset(){
keyUp = false;
keyDown = false;
keyLeft = false;
keyRight = false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I figured out how to cross-compile to windows using mingw compiler. When I run this app in Windows natively, it runs much faster, well over 200fps on my laptop at 900x900 instead of 40-60fps. I believe if I was running this natively on linux and not with wsl2 I would have never had performance concerns.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T17:44:40.847",
"Id": "243675",
"ParentId": "243630",
"Score": "0"
}
},
{
"body": "<p>I suggest figuring out how to use a cpu profiler for your particular platform (Visual Studio has a nice one, but there are simpler ones like "Very Sleepy" to give a quick overview).</p>\n<p>These will sample your code as it runs (make sure you run an optimized build, not a debug build), and provide detailed feedback as to which line of code takes up the most time.</p>\n<hr />\n<p>I put together a quick test project with your code, and ran it under Very Sleepy, which provides output like the following:</p>\n<pre><code>Name Exclusive Inclusive %Exclusive %Inclusive Module Source File Source Line Address\n\ngenerateRaster 13.94s 13.94s 77.24% 77.24% App D:\\Projects\\SDLProject\\Code\\App\\main.cpp 332 0x7ff6550b14ea\nmemcpy 0.98s 0.98s 5.43% 5.43% App d:\\A01\\_work\\6\\s\\src\\vctools\\crt\\vcruntime\\src\\string\\amd64\\memcpy.asm 436 0x7ff65516f120\n[00007FF934D6EFD0] 0.01s 0.01s 0.04% 0.04% App 0 0x7ff934d6efd0\nD3D_UpdateTextureRep 0.01s 0.99s 0.04% 5.50% App D:\\Projects\\SDLProject\\Code\\SDL\\src\\render\\direct3d\\SDL_render_d3d.c 760 0x7ff6550c7b6c\n</code></pre>\n<p>So a quick glance shows that more than 75% of the time spent running the program was in the <code>generateRaster</code> function.</p>\n<p>It also gives a line by line overview of where the time is spent. (Some lines don't really show up due to optimizations).</p>\n<p><a href=\"https://i.stack.imgur.com/c2NoI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c2NoI.png\" alt=\"profiler hot lines\" /></a></p>\n<p>We can see that <code>addVerticalLineOfPixels()</code> is the culprit.</p>\n<pre><code>void addVerticalLineOfPixels(int row, uint32_t* rasterPixels, uint32_t color, int start, int end) {\n for(int i = 0; i < WINDOW_WIDTH; i++) {\n if(i >= start && i <= end) {\n rasterPixels[(i*WINDOW_WIDTH)+row] = color;\n } else {\n rasterPixels[(i*WINDOW_WIDTH)+row] = 0;\n }\n }\n}\n</code></pre>\n<p>This isn't very surprising, since the function effectively touches every single pixel on our screen texture.</p>\n<p>We might try to reduce the number of pixels we have to touch by clearing the texture some other way (e.g. blitting to it on the GPU instead). This means we'd only have to manually set the pixels between <code>start</code> and <code>end</code> to <code>color</code>.</p>\n<p>However, even if we did that, there's another problem which is described at the very bottom of the linked tutorial:</p>\n<blockquote>\n<p>Raycasting works with vertical stripes, but the screen buffer in\nmemory is laid out with horizontal scanlines. So drawing vertical\nstripes is bad for memory locality for caching (it is in fact a worst\ncase scenario), and the loss of good caching may hurt the speed more\nthan some of the 3D computations on modern machines. It may be\npossible to program this with better caching behavior (e.g. processing\nmultiple stripes at once, using a cache-oblivious transpose algorithm,\nor having a 90 degree rotated raycaster), but for simplicity the rest\nof this tutorial ignores this caching issue.</p>\n</blockquote>\n<p>In other words, using <code>rasterPixels[(i*WINDOW_WIDTH)+row] = ...</code> skips across a large amount of memory, and only sets a single pixel in every <code>WINDOW_WIDTH</code>. We repeat this skipping for every column in the texture.</p>\n<p>Instead, we would like to do <code>rasterPixels[row * WINDOW_WIDTH + i] = ...</code>, so we set every pixel in a contiguous block.</p>\n<p>It's actually a simple change:</p>\n<pre><code>void addVerticalLineOfPixels(int row, uint32_t* rP, uint32_t color, int start, int end) {\n std::fill_n(rP + (row * WINDOW_WIDTH), start, 0);\n std::fill_n(rP + (row * WINDOW_WIDTH) + start, (end - start), color);\n std::fill_n(rP + (row * WINDOW_WIDTH) + end, (WINDOW_WIDTH - end), 0);\n}\n</code></pre>\n<p>(We use <code>std::fill_n</code> for neatness and performance - we're effectively doing 3 loops over the index ranges <code>[0, start)</code>, <code>[start, end)</code> and <code>[end, WINDOW_WIDTH)</code> ).</p>\n<p>Then we can replace the texture blitting function <code>SDL_RenderCopy</code> with <code>SDL_RenderCopyEx</code>, which lets us rotate the texture while blitting:</p>\n<pre><code>SDL_RenderCopyEx(renderer, framebuffer, NULL, NULL, -90.0, NULL, SDL_RendererFlip::SDL_FLIP_NONE);\n</code></pre>\n<p>Measuring these changes with the profiler shows that <code>generateRaster</code> now takes up <2.5% of the program run time.</p>\n<p><code>:)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T13:35:58.103",
"Id": "251813",
"ParentId": "243630",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T18:45:40.617",
"Id": "243630",
"Score": "1",
"Tags": [
"c++",
"performance",
"sdl",
"raycasting"
],
"Title": "Improving performance of raycaster application"
}
|
243630
|
<p>Given a CSS file the script generates an HTML preview of all the CSS definitions by recursively drilling down the chain of nested classes, ids and tag names. Rules with <code>position: absolute|fixed|sticky</code> are wrapped into <code>iframe</code> elements in order to avoid overlap.</p>
<p>The output goes to stdout since I wanted to avoid keeping storing too much data in memory. Content that goes inside iframes is printed first to a temporary buffer rather than stdout because that text needs to be html-escaped.</p>
<p>Would be interested to get feedback on:</p>
<ul>
<li>performance and efficiency (CPU, memory): is there anything inherently inefficient/slow with the chosen approach that can be optimised?</li>
<li>code organisation</li>
<li>obvious (or subtle) code smells</li>
<li>naming and legibility</li>
<li>possible criteria to check correctness or well-formedness of the generated output</li>
</ul>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Generates an HTML file for previewing all styles defined in a CSS file
#
# dependencies: cssutils
# USAGE:
# css_preview_generator.py style.css > preview.html
import html
import io
import sys
import cssutils
image_placeholder = "data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='150' viewBox='0 0 300 150'%3E%3Crect fill='yellow' width='300' height='150'/%3E%3Ctext fill='rgba(0,0,0,0.5)' x='50%25' y='50%25' text-anchor='middle'%3E300×150%3C/text%3E%3C/svg%3E"
def render(s, out):
if out and not out.closed:
return print(s, end='', file=out)
else:
print(s, flush=True)
def down_the_rabbit_hole(chunks, full_selector, out=None):
if len(chunks):
chunk = chunks.pop(0)
render_open_tag(chunk, out)
down_the_rabbit_hole(chunks, full_selector, out)
render_close_tag(chunk, out)
else:
render(full_selector, out)
prefix_map = {
'.': 'class',
'#': 'id'
}
def extract_class_id(defn, extracted_attrs=''):
try:
for prefix in prefix_map.keys():
if prefix in defn:
items = defn.split(prefix)
value = ' '.join(items[1:])
# return a tuple of (tagname, 'class="bla blu"') or (tagname, 'id="abc"')
tag = items[0]
if any(suffix in tag for suffix in prefix_map.keys()):
return extract_class_id(tag, f'{prefix_map[prefix]}="{value}"')
else:
return items[0], f'{extracted_attrs} {prefix_map[prefix]}="{value}"'
except Exception as e:
print(e, file=sys.stderr)
return defn, ''
def render_open_tag(definition, out):
if definition.startswith(('.', '#')):
_, class_or_id = extract_class_id(definition)
render(f'<div {class_or_id}>', out)
else:
if definition == 'a' or definition.startswith(('a.', 'a#')):
tag, class_or_id = extract_class_id(definition)
render(f'''<a {class_or_id} href="#">''', out)
elif definition == 'img' or definition.startswith(('img.','img#')):
render(f'<img src="{image_placeholder}" alt="[image]">', out)
else:
tag, class_or_id = extract_class_id(definition)
if tag.lower() == 'td':
render(f'<table><thead><tr><th>[th]</th></thead><tbody><tr><td {class_or_id}>[td]<br/>', out)
else:
render(f'<{tag} {class_or_id}>', out)
def render_close_tag(definition, out):
if definition.startswith(('.', '#')):
render('</div>', out)
else:
if definition == 'a' or definition.startswith(('a.', 'a#')):
render(f'⚓️ {definition}</a>', out)
else:
tag, _ = extract_class_id(definition)
if tag.lower() == 'td':
render('</td></tr></tbody></table>', out)
else:
render(f'</{tag}>', out)
if __name__ == '__main__':
if len(sys.argv) == 1 or sys.argv[1] in ('-h', '--help'):
print(f'Usage: {sys.argv[0]} style.css > preview.html')
sys.exit(-1)
already_seen = []
css_file = sys.argv[1]
sheet = cssutils.parseFile(css_file)
print(f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS preview: {css_file}</title>
<link href="{css_file}" rel="stylesheet" type="text/css" />
</head>
<body>
''')
selectors_requiring_iframe = []
# build a list of absolute & fixed rules
for rule in sheet:
if isinstance(rule, cssutils.css.CSSStyleRule):
position = getattr(rule.style, 'position', None)
if position in ('fixed', 'absolute', 'sticky'):
for single_selector in rule.selectorList: # type: cssutils.css.Selector
selectors_requiring_iframe.append(single_selector.selectorText)
# deduplicate list
selectors_requiring_iframe = list(dict.fromkeys(selectors_requiring_iframe))
for rule in sheet:
if isinstance(rule, cssutils.css.CSSStyleRule):
selectors: cssutils.css.SelectorList = getattr(rule, 'selectorList', [])
full_selectors_text = rule.selectorText
print(f'CSS Rule: {full_selectors_text}', file=sys.stderr)
for single_selector in selectors: # type: cssutils.css.Selector
current_selector_text = single_selector.selectorText
if not single_selector or current_selector_text.startswith(('html', 'body')):
continue
# 1. convert '>' to space
# 2. '~' '*' '+' and '[]' (not supported, ignoring them, convert to space, breaks semantics FIXME)
for c in '>*~+':
if c in current_selector_text:
current_selector_text = current_selector_text.replace(c, ' ')
for c in ':[':
if c in current_selector_text:
current_selector_text = current_selector_text.split(c)[0]
if current_selector_text in already_seen:
continue
else:
already_seen.append(current_selector_text)
if ' ' in current_selector_text:
current_selector_text = current_selector_text.replace(' ', ' ')
position = getattr(rule.style, 'position', None)
# if current selector is a child of an absolute/fixed rule then also wrap it in an iframe
matching_abs_parents = [sel for sel in selectors_requiring_iframe if sel in current_selector_text]
need_iframe = position in ('fixed', 'absolute', 'sticky') or len(matching_abs_parents)
need_table = False
out = None
if need_iframe:
print(
f'''<iframe style="border:1px dotted #acad9e;" width="400" height="300" srcdoc="{html.escape(f'<html><head><link href="{css_file}" rel="stylesheet" type="text/css"/></head><body style="background:#f6f4ee">')}''',
end='')
out = io.StringIO()
print(f'\t{current_selector_text}', file=sys.stderr)
down_the_rabbit_hole(current_selector_text.split(), full_selectors_text, out)
if need_iframe:
print(html.escape(out.getvalue()), end='')
out.close()
print('"></iframe>')
print('''
</body>
</html>''')
</code></pre>
<p>The latest version is <a href="https://github.com/glowinthedark/css_stylesheet_preview_generator/blob/master/css_preview_generator.py" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T07:56:35.837",
"Id": "478577",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T10:50:44.670",
"Id": "478584",
"Score": "0",
"body": "@Mast: thanks; wasn't aware of the codereview policy."
}
] |
[
{
"body": "<p>Since you only use <code>already_seen</code> to check if <code>current_selector_text</code> has been seen, consider changing the type of <code>already_seen</code> from <code>list</code> to <code>set</code> (slight performance improvement).</p>\n<p>The function name <code>down_the_rabbit_hole</code> is unclear as to what it does. This will confuse people who have not heard of this phrase before.</p>\n<p>Since you are already checking for arguments with <code>if len(sys.argv) == 1 or sys.argv[1] in ('-h', '--help'):</code>, consider handling the case when more than 1 argument is given (rather than just ignoring the rest of them).</p>\n<p>You assign <code>False</code> to <code>need_table</code>, but <code>need_table</code> is unused.</p>\n<p>The line <code># -*- coding: utf-8 -*-</code> is <a href=\"https://stackoverflow.com/questions/14083111/should-i-use-encoding-declaration-in-python-3\">unnecessary in Python 3 under most cases</a>.</p>\n<p>You only have 1 type annotation on line 125 (<code>selectors: cssutils.css.SelectorList = getattr(rule, 'selectorList', [])</code>). Is there a reason why none of the other variables have an annotation (or why just this line has one)?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:27:40.900",
"Id": "478568",
"Score": "0",
"body": "Thanks! What name would you suggest for the method? My first urge was something like `recurse` or `process_definitions` but that seemed too dull so I just used a placeholder name. Naming is [hard](https://martinfowler.com/bliki/TwoHardThings.html). On a more general level, what would be the best practice for naming recursive methods? In production code I tend to name them as `recurseABC` or `descendABC` to make it more obvious, but not sure that's the best approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:30:32.027",
"Id": "478569",
"Score": "0",
"body": "The single annotation was added in order to ease debugging. Where the types are obvious and easily inferred by the IDE, e.g. `bla = []` I normally don't add them explicitly. What is the recommended practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:41:09.280",
"Id": "478570",
"Score": "1",
"body": "I got into the habit of using `# -*- coding: utf-8 -*-` exclusively as a reminder to myself that the source code contains non-ascii characters, *not* for the IDE support or anything else."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T00:54:07.947",
"Id": "243796",
"ParentId": "243636",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243796",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T20:37:11.603",
"Id": "243636",
"Score": "3",
"Tags": [
"python",
"html",
"css",
"generator"
],
"Title": "CSS preview generator (in python)"
}
|
243636
|
<p>I have the below implementation of the BFS algorithm, in which I've used <code>OrderedDict</code> instead of a <code>list</code> or <code>set</code>. <strong>(</strong> I've used <code>OrderedDict</code> in DFS to preserve the order of visited vertices <strong>)</strong>. Is this an efficient implementation of BFS and any other suggestions for improvements?</p>
<p>(<strong>Note</strong>: My use case is a sparse graph, i.e., the input will always be an adjacency list)</p>
<pre><code>import collections
def bfs_iterative(graph, vertex):
visited = collections.OrderedDict()
queue = collections.deque([vertex])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited[vertex] = True
queue.extend(graph[vertex])
return list(visited.keys())
def main():
test_graph1 = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
test_graph2 = {
1: [2, 4, 5],
2: [3, 6, 7],
3: [],
4: [],
5: [],
6: [],
7: []
}
print(bfs_iterative(test_graph1, 'A')) # output: ['A', 'B', 'C', 'D', 'E', 'F']
print(bfs_iterative(test_graph2, 1)) # output: [1, 2, 4, 5, 3, 6, 7]
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T23:04:48.220",
"Id": "478221",
"Score": "3",
"body": "As of Python 3.7, the built in [dict class](https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict) preserves insertion order (see last paragraph in the docs). So a regular `dict` will work and the `OrderedDict` isn't needed."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T22:45:58.460",
"Id": "243639",
"Score": "3",
"Tags": [
"python",
"algorithm",
"graph",
"breadth-first-search"
],
"Title": "Breadth First Search Python Implementation"
}
|
243639
|
<p>In working on <a href="https://codereview.stackexchange.com/questions/241635/command-line-based-game-with-players-and-monsters/243570#243570">this answer</a> it occurred to me that it might be interesting to further expand the idea.</p>
<h1>The game</h1>
<p>This is an extremely simple (and boring!) text-based game that creates a few monsters which attack the player and which the player can attack. The goal is for player to defeats all of the monsters before dying. To fight monsters, the player types the generic name of the monster, e.g "Orc" and if there are multiple Orcs, the program will register a hit on each of them. The game is very boring, to play but it was intended as a proof-of-concept rather than a fully fleshed out game. With that said, it is complete and runs without error.</p>
<h2>Features</h2>
<p>Some features of the game are that it's multi-threaded with the monsters being driven in one thread and the user I/O in another. It uses a <code>std::priority_queue</code> to keep track of the timing of the monster attacks on the player. That is, the monsters act in real time and autonomously, independent of the player.</p>
<p>It <em>can</em> use the C++20 <code>std::osyncstream</code> if available, but has a substitute for C++11 or above which is why it has both tags.</p>
<h2>Questions</h2>
<p>I'm particularly interested in:</p>
<ol>
<li>Is the <code>Game</code> object design easy to understand?</li>
<li>Does the scheduling mechanism make sense?</li>
<li>I could have used <code>std::initializer_list<Monster></code> as the argument instead of <code>std::initializer_list<std::pair<std::string, unsigned>></code> for the constructor. I chose not to because I didn't want temporary copies of <code>Monster</code>s made. What do you think of that choice?</li>
<li>Are there any flaws in the multithreading?</li>
<li>The game currently ends via an <code>exit</code> call to kill all threads. Is there a more elegant way to approach this?</li>
</ol>
<h2>Game.h</h2>
<pre><code>#ifndef GAME_H
#define GAME_H
#include <atomic>
#include <initializer_list>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
class Game {
struct Monster {
static unsigned serial;
Monster(std::string name, unsigned interval);
Monster(const Monster &other) = delete;
std::string name;
unsigned interval;
unsigned deadline;
int health = 4;
unsigned id;
};
std::vector<std::shared_ptr<Monster>> Monster_list;
std::mutex monster_lock;
std::atomic_uint enemy_count{0};
std::atomic_uint player_health{10};
void listEnemies();
unsigned hit(std::shared_ptr<Monster> victim);
public:
void monsters();
void player();
Game(std::initializer_list<std::pair<std::string, unsigned>> init);
};
#endif // GAME_H
</code></pre>
<h2>Game.cpp</h2>
<pre><code>#include "Game.h"
#include <atomic>
#include <chrono>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
#if __has_include(<syncstream>)
#include <syncstream>
std::osyncstream sync_out{std::cout};
#else
class syncstr {
std::mutex cout_lock;
std::ostream& out;
public:
syncstr(std::ostream& out) : out{out} {}
syncstr& operator<<(const char *item) {
std::lock_guard<std::mutex> lock(cout_lock);
out << item;
out.flush();
return *this;
}
syncstr& operator<<(const std::string &item) {
std::lock_guard<std::mutex> lock(cout_lock);
out << item;
out.flush();
return *this;
}
syncstr& operator<<(char item) {
std::lock_guard<std::mutex> lock(cout_lock);
out << item;
out.flush();
return *this;
}
syncstr& operator<<(unsigned item) {
std::lock_guard<std::mutex> lock(cout_lock);
out << item;
out.flush();
return *this;
}
syncstr& operator<<(int item) {
std::lock_guard<std::mutex> lock(cout_lock);
out << item;
out.flush();
return *this;
}
syncstr& operator<<(long int item) {
std::lock_guard<std::mutex> lock(cout_lock);
out << item;
out.flush();
return *this;
}
};
syncstr sync_out{std::cout};
#endif
Game::Monster::Monster(std::string name, unsigned interval) :
name{name},
interval{interval},
deadline{interval},
id{++serial}
{ }
Game::Game(std::initializer_list<std::pair<std::string, unsigned>> init) {
std::cin.tie(nullptr);
for (auto &temp : init) {
Monster_list.emplace_back(std::make_shared<Monster>(temp.first, temp.second));
++enemy_count;
}
}
void Game::listEnemies() {
std::lock_guard<std::mutex> mlock(monster_lock);
sync_out << "Surrounding you are " << enemy_count << " enemies:\n";
for (const auto &m: Monster_list) {
if (m->health) {
sync_out << m->name << m->id << '\n';
}
}
sync_out << "What would you like to attack? ";
}
unsigned Game::hit(std::shared_ptr<Monster> victim) {
if (victim->health) {
if (--victim->health == 0) {
sync_out << victim->name << victim->id << " defeated!\n";
--enemy_count;
}
}
return victim->health;
}
void Game::monsters() {
static auto compare_deadlines = [](std::shared_ptr<Monster> a, std::shared_ptr<Monster> b){
return a->deadline > b->deadline;
};
std::priority_queue<std::shared_ptr<Monster>, std::vector<std::shared_ptr<Monster>>, decltype(compare_deadlines)> monster{compare_deadlines};
for (auto m : Monster_list) {
monster.push(m);
}
auto start = std::chrono::system_clock::now();
while (!monster.empty()) {
std::this_thread::sleep_for(std::chrono::seconds(monster.top()->deadline));
std::unique_lock<std::mutex> mlock(monster_lock);
// if the moster is already dead, don't let it attack
if (hit(monster.top())) {
sync_out << std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start).count() << " "
<< monster.top()->name << monster.top()->id << " attacks! Health = " << monster.top()->health << '\n'
<< "Your health = " << --player_health << '\n';
}
// is the game over?
if (player_health == 0 || enemy_count == 0) {
mlock.unlock();
if (enemy_count) {
sync_out << "You have died -- Game over!\n";
} else {
sync_out << "All enemies are defeated!!\n";
}
// this also kills the other thread
exit(0);
}
// adjust the priority queue
auto elapsed = monster.top()->deadline;
decltype(monster) m2{std::move(monster)};
while (!m2.empty()) {
auto current = m2.top();
m2.pop();
if (current->deadline > elapsed) {
current->deadline -= elapsed;
} else {
current->deadline = current->interval;
}
if (current->health) {
monster.push(current);
}
}
}
}
void Game::player() {
while (enemy_count) {
listEnemies();
std::string enemy;
std::cin >> enemy;
unsigned hitcount{0};
for (auto &m: Monster_list) {
std::lock_guard<std::mutex> mlock(monster_lock);
if (m->name == enemy && m->health) {
sync_out << "Hacking away at " << m->name << m->id << '\n';
hit(m);
++hitcount;
}
}
if (hitcount == 0) {
sync_out << "No living enemy named " << enemy << '\n';
}
}
}
unsigned Game::Monster::serial{0};
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include "Game.h"
#include <thread>
#include <functional>
int main() {
Game game{ {"Dragon",8}, {"Orc", 3}, {"Wumpus", 5}, {"Edward", 7}, {"Orc", 4} };
auto m = std::thread(&Game::monsters, std::ref(game));
game.player();
m.join();
}
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<ol>\n<li>Is the Game object design easy to understand?</li>\n</ol>\n</blockquote>\n<p>It's not too hard. But I would have expected a <code>struct Player</code> (even if there is only one instance of it, so no need to put it in a container), and I also expected <code>class Game</code> to manage the monster thread.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Does the scheduling mechanism make sense?</li>\n</ol>\n</blockquote>\n<p>Yes, but it is a bit too complicated. Instead of storing intervals, you can store absolute times, and use <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_until\" rel=\"nofollow noreferrer\"><code>std::this_thread::sleep_until()</code></a>. This avoids having to adjust all the deadlines every time a monster gets to do something. Then you can just do:</p>\n<pre><code>while (!monster.empty()) {\n auto current = monster.top();\n std::this_thread::sleep_until(current->deadline);\n\n // let the monster do its thing\n\n monster.pop();\n\n if (current->health) {\n current->deadline += current->interval;\n monster.push(current);\n }\n}\n</code></pre>\n<p>It helps if you declare <code>deadline</code> and <code>interval</code> with the correct <code>std::chrono</code> types, so you avoid a lot of casts.</p>\n<blockquote>\n<ol start=\"3\">\n<li>I could have used <code>std::initializer_list<Monster></code> as the argument instead of <code>std::initializer_list<std::pair<std::string, unsigned>></code> for the constructor. I chose not to because I didn't want temporary copies of Monsters made. What do you think of that choice?</li>\n</ol>\n</blockquote>\n<p>But now it has to create temporary <code>std::pair<std::string, unsigned></code>s. I would rather use an initializer list that takes <code>Monster</code>s. This will also make it more future proof, for example if you add more overloads to the constructor of <code>Monster</code>.</p>\n<blockquote>\n<ol start=\"4\">\n<li>Are there any flaws in the multithreading?</li>\n</ol>\n</blockquote>\n<p>Not that I can see. Of course, if you use an event loop that handles both timeouts and keyboard input, then you wouldn't need threads at all, and you would avoid having to use mutexes.</p>\n<blockquote>\n<ol start=\"5\">\n<li>The game currently ends via an exit call to kill all threads. Is there a more elegant way to approach this?</li>\n</ol>\n</blockquote>\n<p>It depends on what you think is elegant. <code>exit()</code> is not very nice, but on the other hand it is just a simple, small statement that takes care of your problems.</p>\n<p>One approach, again, is to use an event loop, which is terminated as soon as all monsters are dead or when the player is dead. There are no delays this way, neither when the monsters are killed or the player is killed. I would consider this the most elegant.</p>\n<p>You can still use multiple threads, but then use an event loop in <code>player()</code> that checks both <code>cin</code> and a <a href=\"https://stackoverflow.com/questions/384391/how-to-signal-select-to-return-immediately\">self pipe</a>. When the monsters kill the player, they send something over the self pipe so the player thread can react immediately. You still have a potential delay if the player kills all monsters.</p>\n<p>If you can use C++20, then also consider using <a href=\"https://en.cppreference.com/w/cpp/thread/jthread\" rel=\"nofollow noreferrer\"><code>std::jthread</code></a> for a little extra elegantness.</p>\n<h1>You don't need the monster <code>id</code></h1>\n<p>You already have a <code>std::vector</code> of <code>Monster</code>s, so the index of the monster in the array is already a unique identifier. And if you use the index as the identifier, you no longer need to scan the array to find the monster.</p>\n<p>If you don't want to use indices into an array or vector as an identifier, then I would store the <code>Monster</code>s in a <code>std::map</code> or <code>std::unordered_map</code>.</p>\n<h1>Naming things</h1>\n<p>There are some inconsistencies in how you name things. For example, <code>Monster_list</code> is a variable but it starts with an upper case. This makes it easier to confuse it for a type name. Also, don't encode the type of container in the name. It's not a list in any case. I would just call this vector <code>monsters</code>.</p>\n<p>Prefer using nouns for variable names, and verbs for function names. So instead of the function <code>monsters()</code>, name it <code>do_monsters()</code> or <code>process_monsters()</code>. The same goes for <code>player()</code>.</p>\n<h1>Add <code>const</code> where appropriate</h1>\n<p>Some member variables of <code>Monster</code> can be made <code>const</code>, and some member functions of <code>Game</code> can be made <code>const</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-19T17:22:01.263",
"Id": "245716",
"ParentId": "243640",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245716",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T23:22:31.477",
"Id": "243640",
"Score": "5",
"Tags": [
"c++",
"c++11",
"game",
"multithreading",
"c++20"
],
"Title": "Multithreaded console-based monster battle with earliest-deadline-first scheduler"
}
|
243640
|
<p>I created this game just to practice my skills. I've been coding for a few years and I'm decent at data structures and algorithms. I want to know how to improve my implementation. </p>
<pre><code>#include <iostream>
using namespace std;
const string QUIT = "q";
const string PLAY = "p";
class Player{
// constructor
public:
Player(string player_symbol){
this->player_symbol = "";
}
void play(string player_symbol);
string get_player();
void set_player(string symbol_str);
private:
int player_moves[10];
string player_symbol;
};
string Player::get_player(){
return player_symbol;
}
void Player::set_player(string symbol_str){
this->player_symbol = symbol_str;
}
string board[10] = {"0","1","2", "3", "4", "5", "6","7","8","9"};
int victory_check(){
// horizontal win
if (board[1] == board[2] && board[2] == board[3]){
if(board[1] == "X") return 1;
else return 0;
}
if (board[4] == board[5] && board[5] == board[6]){
if(board[4] == "X") return 1;
else return 0;
}
if (board[7] == board[8] && board[8] == board[9]){
if(board[8] == "X") return 1;
else return 0;
}
// vertical
if (board[1] == board[4] && board[4] == board[7]){
if(board[7] == "X") return 1;
else return 0;
}
if (board[2] == board[5] && board[5] == board[8]){
if(board[5] == "X") return 1;
else return 0;
}
if (board[3] == board[6] && board[6] == board[9]){
if(board[6] == "X") return 1;
else return 0;
}
// diagonal
if (board[1] == board[5] && board[5] == board[9]){
if(board[9] == "X") return 1;
else return 0;
}
if (board[3] == board[5] && board[5] == board[7]){
if(board[3] == "X") return 1;
else return 0;
}
return -1;
}
void create_board();
void reset_board();
void check_illegal(int move_number, string player_symbol);
bool tie_game();
int main(){
cout << "\n\n\tTic Tac Toe\n\n";
cout << "Player 1 (X) - Player 2 (O)" << endl << endl;
cout << endl;
Player player_1("");
player_1.set_player("X");
Player player_2("");
player_2.set_player("O");
string player_move;
bool game_over = false;
bool player1_turn = true;
bool tie = tie_game();
tie = false;
while(!game_over){
create_board();
if(player1_turn){
cout << "PLAYER 1: enter your move: ";
}
else{
cout << "PLAYER 2: enter your move: ";
}
cin >> player_move;
if(player_move == QUIT){
game_over = true;
}
else if(player_move == PLAY){
string my_symbol = player_1.get_player();
if(player1_turn){
player_1.play(my_symbol);
}else{
player_2.play(player_2.get_player());
}
}
int winner = victory_check();
if(winner == 1){
create_board();
cout << "CONGRATULATIONS Player 1, You won" << endl;
cout << "Do you want to play again [y/n]" << endl;
cin >> player_move;
if(player_move == "y"){
reset_board();
}else{
game_over = true;
}
}
else if(winner == 0){
create_board();
cout << "CONGRATULATIONS Player 2, You won" << endl;
cout << "Do you want to play again [y/n]" << endl;
cin >> player_move;
if(player_move == "y"){
reset_board();
create_board();
}else{
game_over = true;
}
game_over = true;
}else if(tie == true){
cout << "this game is a tie" << endl;
}
player1_turn = !player1_turn;
}
//player1_turn = false;
}
void create_board(){
cout << " | | " << endl;
cout << " " << board[1] << " | " << board[2] << " | " << board[3] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[4] << " | " << board[5] << " | " << board[6] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[7] << " | " << board[8] << " | " << board[9] << endl;
cout << " | | " << endl << endl;
}
void reset_board(){
for (int i = 0; i < 10; i++){
board[i] = to_string(i);
}
}
void Player::play(string player_symbol){
int move_number;
cout << "Enter your move number: ";
cin >> move_number;
while(board[move_number] == "X" || board[move_number] == "O"){
cout << "This position is already taken, try again: ";
cin >> move_number;
}
board[move_number] = player_symbol;
}
bool tie_game(){
for(int i = 0; i < 10; i++){
if (board[i] != "X" && board[i] != "O"){
return false;
}
}
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T08:48:23.713",
"Id": "478237",
"Score": "0",
"body": "You have a player class, but the rest of the code is hardly object-oriented written. Is there a reason the other functions aren't methods?"
}
] |
[
{
"body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The code contains these two lines:</p>\n\n<pre><code>bool tie = tie_game();\ntie = false;\n</code></pre>\n\n<p>I'm sure that you can see why that's a bug if you think about it for a bit.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. </p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The <code>player_symbol</code> parameter that is passed to the <code>Player</code> constructor is never used. Also <code>player_moves</code> isn't used anywhere. All of these should be eliminated from the code.</p>\n\n<h2>Avoid the use of global variables</h2>\n\n<p>I see that <code>QUIT</code>, <code>PLAY</code> and <code>board</code> are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. For example, both <code>QUIT</code> and <code>PLAY</code> could easily be local to <code>main</code> and <code>board</code> could become an object with many of the functions turning into member functions.</p>\n\n<h2>Fix your formatting</h2>\n\n<p>There are inconsistent spaces at the beginning of lines, inconsistent indentation and inconsistent use and placement of curly braces <code>{}</code>. Being consistent helps others read and understand your code.</p>\n\n<h2>Don't use std::endl unless you really need to flush the stream</h2>\n\n<p>The difference between <code>std::endl</code> and <code>'\\n'</code> is that <code>std::endl</code> actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.</p>\n\n<h2>Use constant string concatenation</h2>\n\n<p>This code currently has a number of instances that look like this:</p>\n\n<pre><code>cout << \"CONGRATULATIONS Player 2, You won\" << endl;\ncout << \"Do you want to play again [y/n]\" << endl;\n</code></pre>\n\n<p>This calls the <code><<</code> operator four times. Instead, you could write this:</p>\n\n<pre><code>cout << \"CONGRATULATIONS Player 2, You won\\n\"\n \"Do you want to play again [y/n]\\n\";\n</code></pre>\n\n<p>This only calls <code><<</code> once. The compiler automatically concatenates the string literals together.</p>\n\n<h2>Use all required <code>#include</code>s</h2>\n\n<p>The code uses <code>to_string</code> and <code>string</code> which means that it should <code>#include <string></code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n\n<h2>Don't write getters and setters for every class</h2>\n\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. Instead, move setter functionality into constructors and think very carefully about whether a getter is needed at all. In this code, there are better options for both getter and setter for <code>Player</code>, which emphasizes why they shouldn't be written in the first place.</p>\n\n<h2>Rethink the class design</h2>\n\n<p>The <code>Player</code> class holds only a single character, while the missing <code>Board</code> class has a lot more responsibility. I'd suggest removing the <code>Player</code> class and turning <code>Board</code> into an object. The design would be much clearer if you did so.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T03:35:55.237",
"Id": "243644",
"ParentId": "243642",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T01:18:42.600",
"Id": "243642",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe implementation c++"
}
|
243642
|
<p>I am having a trouble speeding up my implementation. The question is, given a range of numbers from long a to long b, find how many lucky numbers are between a and b inclusive. A number is a lucky number if it contains either 1 or 3. If it contains both 1 and 3, it is not a lucky number.</p>
<p>Currently, I am iterating over from a to b, inclusive, using for loop, and have a while loop in each iteration where a while loop continues until current number is > 0. In the while loop, I use modulo 10 to get the last digit, check if it's 1 or 3, then set the current number to the number/10.</p>
<p>Is there a way to make this more efficient for range from 10000000000 to 20000000000? With my implementation, it takes around 160 seconds.</p>
<p>Here is my code: </p>
<pre><code>public class Main {
public static void main(String[] args) {
long start = 10000000000L;
long end = 20000000000L;
int total = 0;
double startTime = System.nanoTime();
for (long i = start;i <= end; i++) {
int numOf1 = 0;
int numOf3 = 0;
long number = i;
while (number > 0) {
long lastDigit = number % 10;
if (lastDigit == 1) {
numOf1++;
} else if (lastDigit == 3) {
numOf3++;
}
if (numOf1 > 0 && numOf3 > 0) {
break;
}
number /= 10;
}
if (numOf1 > 0 || numOf3 > 0) {
total++;
}
}
System.out.println(total);
double endTime = System.nanoTime();
System.out.println((endTime - startTime) / 1000000000);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T07:59:34.293",
"Id": "478233",
"Score": "1",
"body": "Welcome to Code Review. The title of your question is slightly misleading from the task you described in your post, please modify it to make it more inherent to the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T11:53:09.190",
"Id": "478252",
"Score": "0",
"body": "If I am not toally mistaken, there's a bug: if you find at least one 1 *and* at least one 3, you break the inner loop, as (numOf1 > 0 && numOf3 > 0). Then, in the outer loop, (numOf1 > 0 || numOf3 > 0) is also true (as both are > 0) and thus you count the number as a lucky number, which is wrong according to the problem statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:23:13.093",
"Id": "478277",
"Score": "0",
"body": "Thank you for pointing out the bug. Also, I edited the title, sorry about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T11:09:42.303",
"Id": "478348",
"Score": "0",
"body": "Is this an interview question? Then asking here might not be a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T18:26:38.563",
"Id": "478385",
"Score": "0",
"body": "It is similar to one of the questions I got on online technical assessment and I was already done with it when I posted the question. I was just curious of a solution that can solve a larger range in 3 seconds because I didn't pass that test case and I wanted to find out. Should I delete this post?"
}
] |
[
{
"body": "<h1>A Bug</h1>\n\n<blockquote>\n<pre><code>if (numOf1 > 0 || numOf3 > 0) {\n total++;\n}\n</code></pre>\n</blockquote>\n\n<p>That overcounts. The definition of \"lucky number\" included \"if it contains both 1 and 3, it is not a lucky number\", but numbers that contain both a 1 and a 3 <em>are</em> counted. The <code>break</code> in the <code>while</code>-loop exits that loop when that condition is detected, but then the code above still runs. You could use:</p>\n\n<pre><code>if ((numOf1 > 0) != (numOf3 > 0)) {\n total++;\n}\n</code></pre>\n\n<p>The <code>!=</code> between two booleans is a slightly tricky way to say \"one of them but not both\". Of course that can be written out more explicitly.</p>\n\n<h1>An other bug</h1>\n\n<blockquote>\n<pre><code>int total = 0;\n</code></pre>\n</blockquote>\n\n<p>Do you know how big the result is? By my count it's just over 3.48 billion. That's a problem, <code>int</code> only goes just over 2.14 billion. The count doesn't go over 4.29 billion, so you <em>could</em> still use <code>int</code>, and then interpret it as an unsigned integer later (eg printing <code>total & 0xFFFFFFFFL</code>). But that's strange, a bit advanced, not for beginners. Using <code>long total = 0;</code> is a simpler and more sensible solution.</p>\n\n<blockquote>\n <p><strong>Is there a way to make this more efficient for range from 10000000000 to 20000000000?</strong></p>\n</blockquote>\n\n<p>There are some specific properties of that range that you could use.</p>\n\n<p>First, let's ignore 20000000000 itself, it contains neither a <code>1</code> nor a <code>3</code>.</p>\n\n<p>Then, every number in the range for sure has at least one <code>1</code> in it, so you don't need to test it, this is something you already know. That would let you simplify the test to \"check if there is any <code>3</code> in the number\".</p>\n\n<h1>Counting without brute force</h1>\n\n<p>Forgetting the leading 1, the numbers in our range have 10 \"variable\" digits.\nHow many 10-digit strings of digits 0..9 <em>don't</em> have a 3 in them? Every place has 9 possible digits left instead of 10, so rather than <code>pow(10, 10)</code> it will be <code>pow(9, 10)</code>.</p>\n\n<p><code>pow(9, 10)</code> is something that you can calculate easily, even with just <code>Math.pow(9, 10)</code>. It's normally not really proper to use <code>double</code>s for integer calculations, but this one works.</p>\n\n<blockquote>\n <p><strong>With my implementation, it takes around 160 seconds.</strong></p>\n</blockquote>\n\n<p>Does it actually? That's an order of magnitude faster than it runs on my PC.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:19:46.737",
"Id": "478274",
"Score": "0",
"body": "Thank you for pointing out the bugs. Sorry to ask again, but if I am trying to calculate between the range from 59 to 5203987742 for example, how can that be calculated without brute force? Also, when I ran the code again after fixing the bugs, it gave me 4826085154 lucky numbers between 10000000000 and 20000000000, but pow(9, 10) should give 3486784401. Am I doing something wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:33:19.600",
"Id": "478278",
"Score": "0",
"body": "@JuhyeonLee I'll add something about different ranges later. I'm not sure what that other trouble is, if I test it for 100000000 to 200000000 (less range, to make it faster), it all comes out fine. Besides, as far as I can tell, the math checks out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:41:31.330",
"Id": "478280",
"Score": "0",
"body": "Thank you. That will be really helpful. And when I test for 100000000 to 200000000, it comes out as 52539010. Is that the number you got?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:42:42.057",
"Id": "478281",
"Score": "0",
"body": "@JuhyeonLee I get 43046721 (with both implementations)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:15:43.673",
"Id": "478285",
"Score": "0",
"body": "I got the right number for 100000000-200000000 and 10000000000-20000000000. I was trying with different digits like 4 and 8 instead of 1 and 3 for lucky numbers. After changing back to 1 and 3, it worked fine. If you have a time later, any idea on how to calculate between 2 random ranges like 29382938-84720398 would be very helpful! Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:39:59.160",
"Id": "478295",
"Score": "0",
"body": "@JuhyeonLee OK sorry I changed my mind, different ranges are too annoying for me to work out, you do something recursive"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T21:27:21.047",
"Id": "478305",
"Score": "0",
"body": "I'll try to figure it out. Thank you for your help!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T11:55:12.963",
"Id": "243660",
"ParentId": "243645",
"Score": "3"
}
},
{
"body": "<p>Say you are at a number <em>abcdef</em>. If b==1 and d==3 you can skip from <em>abcd00</em> to <em>abc(d+1)00</em>. That is the gist of optimizing the algorithm.</p>\n<p>Needing the individual digits and intelligently stepping to the next digits seems a better approach. (Now decomposing <em>every</em> number in digits.)</p>\n<p>Use an array of digits, and compose the lucky numbers.</p>\n<p>As far as a <strong>review</strong> of the existing code goes, is the review from <strong>@harold</strong> fine.</p>\n<hr />\n<p><em><strong>Clarification, schematic solution:</strong></em></p>\n<p>Your code walks <em>all</em> numbers and for every number looks at its digits:</p>\n<pre><code>// Loop for every number i:\nfor (long i = start; i <= end; i++) {\n\n // Loop to determine all digits again:\n long number = i;\n while (number > 0) {\n long lastDigit = number % 10; ...\n number /= 10;\n }\n</code></pre>\n<p>It would be better to have the digits as array or char array/StringBuilder (the inner loop):</p>\n<p>If you store the digits with the least significant first 1234 as {4, 3, 2, 1}\nthen you use for loops with ++.</p>\n<pre><code>int[] startDigits = ...\nint[] endDigits = ...\nassert startDigits.length == endDigits.length;\n\nint[] digits = startDigits();\nwhile (!Arrays.equals(digits, endDigits); stepNext(digits)) {\n int p1 = digits.indexOf(1);\n int p3 = digits.indexOf(3);\n if ((p1 >= 0) != (p3 >= 0) {\n // Lucky\n print number ... a[2] a[1] a[0]\n } else {\n int p = Math.min(p1, p3);\n for (int i = 0; i < p; ++i) {\n a[i] = 9;\n }\n }\n // increment digits from a[0] .. a[n-1]\n for (int i = 0; i < n; ++i) {\n boolean carry = a[i] == 9;\n if (carry) {\n a[i] = 0;\n } else {\n ++a[i];\n break;\n }\n }\n}\n</code></pre>\n<p>The above shows one shortcut for having an unlucky number with first position of 1 or 3 at p. There are other possibilities too.</p>\n<hr />\n<p><em><strong>An abstract solution of the problem:</strong></em></p>\n<p>A lucky number looks a bit like <code>abc...X...def</code> where X is 1 or 3, and a, b, c, d, e, f are not Y (3 or 1) - but may be X.</p>\n<p>How many different combinations are there? And then from start to end?</p>\n<p>For N digits with n Xs you need the number of possible combinations (math) (times 2 for X in {1, 3}) and the other digits can each have 8 values (not 1 or 3). In fact this subproblem is like counting the number of 1s/0s in a binary number of N bits: 10000, 11000, 10100, ... - There are 2^N - 1 different combinations with at one 1. 00000 being the exception. If 1 represents X,\nthe number with 3 0s would be N over 3 which would add 2<em>8^(N over 3) = (1 or 3)</em>(8 candidates for the N-3 0s).</p>\n<p>Start and end restrictions are the difficult part. Simplify by excluding the common prefix. And then you need to walk the actual patterns 1101001 and check which digits are allowed there.</p>\n<p>To exclude 000 == without 1, and get all bit patterns:</p>\n<pre><code>long luckyNumbers = 0;\nassert N < 64;\nfor (long bitPattern = 1; bitPattern < (1L << N); ++bitPattern) {\n // Check the possible number of digits for every bit.\n ...\n</code></pre>\n<p>This reduces the problem merely from N digits to N bits, but you have only lucky numbers and need not create all 10^N numbers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:21:28.763",
"Id": "478275",
"Score": "0",
"body": "Thank you for commenting. I am sorry, but I do not fully understand the logic where you said to use an array of digits. Could you please explain in more detail if that's fine with you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:09:42.060",
"Id": "478292",
"Score": "0",
"body": "Thank you for explaining more in detail! I will try to understand the code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T22:35:57.920",
"Id": "478396",
"Score": "0",
"body": "Thank you for the abstract solution of the problem. If you can have multiple 1s or 3s in a number, would that change the solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T05:37:48.460",
"Id": "478437",
"Score": "0",
"body": "Lucky numbers are multiple of either 1s or 3s and the other digits _not 3 or 1_. Hence you can use a bit pattern 0010010 for here two 3s or two 1s and five other chars: the count of lucky numbers would be 2*8^5 , the factor 2 for 1 or 3, 8 for the remaining 8 digits and 5 for the 0-positions. So yes. Be aware that a solution is not that easy as the filled in ten digits must form a number between start and end."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:03:29.600",
"Id": "243665",
"ParentId": "243645",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T04:03:27.203",
"Id": "243645",
"Score": "1",
"Tags": [
"java",
"performance",
"algorithm"
],
"Title": "How to efficiently find if numbers in a given range contains either 1 or 3, but not both?"
}
|
243645
|
<p>The point was that we have a series of dynamic data that comes from the server and must be added to the view, and the other thing is that given the property of the objects that are true and false, add a series of classes to it.
For example, I created an array myself, so that you know an understanding of the data structure that the server will come up with</p>
<p>Below is my first code:</p>
<pre><code> var works = [{
workTitle: "WW II military operations",
answered: true
},
{
workTitle: "Female scientist",
answered: false
},
{
workTitle: "Animals (like Apple who have used Jaguar, Leopard, Panther etc for OS X versions)",
answered: false
},
{
workTitle: "Myths and legends, like American rockets",
answered: true
},
{
workTitle: "iot.js",
answered: true
},
{
workTitle: "Random code name generators",
answered: true
},
{
workTitle: "Dinosaur names",
answered: false
},
{
workTitle: "Myths and legends, like American rockets Animals (like Apple who have used Jaguar, Leopard, Panther etc for OS X versions)",
answered: true
},
{
workTitle: "Try your hand at creating your next project (or product) name with this cool name generator! Project Jive-theory is just around the",
answered: true
},
];
//create section tag and add class to that
let mainElement = document.getElementById("main");
let containerWorks = document.createElement('section');
containerWorks.classList.add("works-container")
//generate HTML code by dynamic values
let len = works.length - 1;
let i = len;
for (; i >= 0; i--) {
if (works[i].answered) {
containerWorks.innerHTML += `<div class="not-allowed work-box d-flex justify-content-center align-items-center p-3"
ui-sref="App.Managment.UsersManagment.UserList">
<div class="title">
${works[i].workTitle}
</div>
<i class="fas fa-lock text-white fa-2x lock-icon"></i>
<div class="not-answer-box font-weight-bold">Previously Evaluated</div>
</div>`;
} else {
containerWorks.innerHTML += `<div class="pointer work-box d-flex justify-content-center align-items-center p-3"
ui-sref="App.Managment.UsersManagment.UserList">
<div class="title">
${works[i].workTitle}
</div>
<i class="fas fa-reply text-white fa-2x enter-icon"></i>
<div class="answer-box font-weight-bold">Click To Evaluate</div>
</div>`;
}
}
mainElement.appendChild(containerWorks);
</code></pre>
<p>But this is suggested code for me by others and we have written this code:</p>
<pre><code>...
//generate HTML code by dynamic values
let len = works.length - 1;
let i = len;
let condition = {
'false': {
iClass: `fa-reply enter-icon`,
divClass: `pointer`,
textContent: 'Click To Evaluate'
},
'true': {
iClass: `fa-lock lock-icon`,
divClass: `not-allowed`,
textContent: "Previously Evaluated"
}
}
for (; i >= 0; i--) {
let cond = condition[works[i].answered];
containerWorks.innerHTML += `<div class="` + cond.divClass + ` work-box d-flex justify-content-center align-items-center p-3"
ui-sref="App.Managment.UsersManagment.UserList">
<div class="title">
${works[i].workTitle}
</div>
<i class="fas ` + cond.iClass + ` text-white fa-2x"></i>
<div class="answer-box font-weight-bold">` + cond.textContent + `</div>
</div>`;
}
mainElement.appendChild(containerWorks);
</code></pre>
<p>I think the suggested code is better in some ways, but I am not sure! and why?<br>
If it's really better can someone tell me why?<br>
And also is there any better way to write that part of the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T07:04:18.440",
"Id": "478229",
"Score": "0",
"body": "@downvoters care to comment!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T07:44:41.760",
"Id": "478232",
"Score": "4",
"body": "Didn't downvote, but you must be author of the code you post and you write yourself, that the second variant isn't yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T08:07:51.037",
"Id": "478234",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T09:17:18.373",
"Id": "478238",
"Score": "0",
"body": "@RoToRa no, the second one is suggested to me and we have written in my code, but i don't know which one better and i don't know is there other way.\nboth of them are my code, but the second one is suggested code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T11:17:08.567",
"Id": "478251",
"Score": "0",
"body": "@BCdotWEB I edited the question bro."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:41:24.877",
"Id": "478288",
"Score": "1",
"body": "\"_Why is suggested code is better in for loop to generate dynamic HTML code?_\" does not sounds like a decent description of **the task accomplished by the code**. Perhaps something like \"_Display list of works to evaluate_\" would be fitting..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:10:01.467",
"Id": "478370",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ edited bro"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T22:08:37.890",
"Id": "478392",
"Score": "2",
"body": "The \"authorship rule\" does not literally require code typed or dreamt up by the user asking. They should be a maintainer, if not author, and in a position to put the code under *creative commons* by presenting it here."
}
] |
[
{
"body": "<p>The suggested code might be considered better because it has less duplicate code. In this case most of the HTML strings are duplicated in your first example. Code with less duplication is less work and less error prone to change. For example, if the classes for the outer div needed to be changed, then in your example you would have to change two places instead of one, and you might forget to change one of the two places, causing a bug. </p>\n\n<p>For a case like this, where there are only two cases, and the two pieces of code are nearby the benefits are smaller than if there were more cases than true or false. Say there was a partially-completed state that needed to be added. Whether it makes sense to reduce duplication in this particular case is a matter of opinion, I would argue, since it does make the code a little more complicated. It might be fine or even better to just wait until the next time the requirements change, since then you will know more about how the code should be at that point. If there were 10 different cases, then the duplication and therefore the chances of making a mistake go up, so it would be clearer what the right choice is. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T08:26:34.763",
"Id": "243652",
"ParentId": "243648",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243652",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T06:28:16.620",
"Id": "243648",
"Score": "-1",
"Tags": [
"javascript",
"performance",
"array"
],
"Title": "Why is suggested code is better in for loop to generate dynamic HTML code to display list of works to evaluate?"
}
|
243648
|
<p>I'm working on a large project that requires a ton of data to be processed. I was thinking that using classes would be the best way, and it is, until it has to dump out the memory at the end of every process I start.</p>
<p>The code for this project is large, but I uplodaded a file with only the necessary means to test my current problem, the destroying time of a lot of objects created by my process. </p>
<p>The example in my code outputs this:</p>
<p>job time: 17008,5989ms.</p>
<p>total time: 85488,3443ms.</p>
<p>The difference between the job time and the total time is just before the <code>Set class = nothing</code> and after.</p>
<pre><code>Sub RecargaProgramaciones()
AhorroMemoria True
Dim Temporizador As New aTimer
Temporizador.StartCounter
Dim MiClase As New Programaciones
MiClase.CargaDatosAgentes
Debug.Print "job time: " & Temporizador.TimeElapsed & "ms."
Set MiClase = Nothing
AhorroMemoria False
Debug.Print "total time: " & Temporizador.TimeElapsed & "ms."
End Sub
</code></pre>
<p>Am I using classes correctly? Should I rebuild this in any other way to avoid this dumping time?</p>
<p>I'd appreciate any help with this because is driving me crazy and execution time is important.</p>
<p><a href="https://github.com/GominoloGris/Test" rel="nofollow noreferrer">Here</a> the link to download the file.</p>
<p>Edit: The sub above calls this class, named <code>Programaciones</code>(forecast) which has this code:</p>
<pre><code>Option Explicit
Private m_Modo As Dictionary
Private Property Get Modos(ByVal Key As String) As Modos
With m_Modo
If Not .Exists(Key) Then .Add Key, New Modos
End With
Set Modos = m_Modo(Key)
End Property
Private Sub Class_Initialize()
Set m_Modo = New Dictionary
End Sub
Private Sub Class_Terminate()
Set m_Modo = Nothing
End Sub
Private Property Get Keys() As Variant
Keys = m_Modo.Keys
End Property
Public Sub CargaDatosAgentes()
Horarios
MisModos
End Sub
Private Sub Horarios()
With ThisWorkbook.Sheets("Base Acc")
Dim arr As Variant: arr = .UsedRange.Value
Dim ColAgente As Long: ColAgente = .Rows(1).Find("ORIGEN", LookAt:=xlWhole).Column + 1
End With
Dim i As Long
Dim j As Long
For i = 2 To UBound(arr)
For j = ColAgente To UBound(arr, 2)
If arr(i, j) Like "*:*" Then
CargaTramos arr, i, j
End If
Next j
Next i
Erase arr
End Sub
Private Sub CargaTramos(arr As Variant, i As Long, j As Long)
Dim fecha As Date: fecha = arr(1, j)
Dim MiFecha As Fechas
Dim Saltar As Boolean
If Month(arr(1, j)) <> Month(arr(1, UBound(arr, 2))) Then Saltar = True
Dim arrHorario As Variant: arrHorario = Split(arr(i, j), "/")
Dim HoraI As Date
Dim HoraF As Date
Dim y As Long
Dim x As Long
Dim Hora As String
Dim Modo As String
Dim DesfaseI As Byte
Dim DesfaseF As Byte
Dim DesfasadoI As Boolean
Dim DesfasadoF As Boolean
Dim Minutos As Byte
For y = LBound(arrHorario) To UBound(arrHorario)
DesfasadoI = False
DesfasadoF = False
HoraI = Left(Trim(arrHorario(y)), 5)
HoraF = Right(Trim(arrHorario(y)), 5)
If Minute(HoraI) < 30 And Minute(HoraI) > 0 Then
DesfaseI = 30 - Minute(HoraI)
HoraI = TimeSerial(Hour(HoraI), 0, 0)
DesfasadoI = True
ElseIf Minute(HoraI) > 30 And Minute(HoraI) < 60 Then
DesfaseI = 60 - Minute(HoraI)
HoraI = TimeSerial(Hour(HoraI), 30, 0)
DesfasadoI = True
End If
If Minute(HoraF) < 30 And Minute(HoraF) > 0 Then
DesfaseF = Minute(HoraF)
HoraF = TimeSerial(Hour(HoraF), 0, 0)
DesfasadoF = True
ElseIf Minute(HoraF) > 30 And Minute(HoraF) < 60 Then
DesfaseF = Minute(HoraF) - 30
HoraF = TimeSerial(Hour(HoraF), 30, 0)
DesfasadoF = True
End If
If HoraF = "00:00:00" Then HoraF = "23:30:00"
If HoraF < HoraI Then HoraF = HoraF + 1
For x = 0 To DateDiff("n", HoraI, HoraF) / 30 - 1
If DesfasadoI And x = 0 Then
Minutos = DesfaseI
ElseIf DesfasadoF And x = DateDiff("n", HoraI, HoraF) / 30 - 1 Then
Minutos = DesfaseF
Else
Minutos = 30
End If
Hora = Format(HoraI + TimeSerial(0, x * 30, 0), "hh:mm")
If Hora < HoraI Then
Saltar = False
fecha = arr(1, j) + 1
If Month(fecha) <> Month(arr(1, UBound(arr, 2))) Then Saltar = True
End If
If Saltar Then GoTo SiguienteTramo
Set MiFecha = Modos(arr(i, 7)).Centros(arr(i, 4)).Fechas(fecha)
If arr(i, 7) = "Plani" Then 'Como el horario se solapa con el de ACC, restamos el tiempo a los de ACC
If Modos("ACC").Centros(arr(i, 4)).Fechas(fecha).Tramos(Hora).Agentes(arr(i, 3)).Presentes = Minutos Then
Modos("ACC").Centros(arr(i, 4)).Fechas(fecha).Tramos(Hora).BorrarAgente arr(i, 3)
End If
End If
MiFecha.Tramos(Hora).Agentes(arr(i, 3)).Presentes = Minutos
SiguienteTramo:
Next x
Next y
End Sub
Private Sub MisModos()
Dim arr As Variant: arr = ThisWorkbook.Sheets("Mapa Habilidades").UsedRange.Value
Dim Encabezados As New Dictionary
Dim MisAgentes As New Dictionary
Dim i As Long
For i = 2 To UBound(arr)
MisAgentes.Add arr(i, 1) & arr(i, 6), i
Next i
For i = 7 To UBound(arr, 2)
Encabezados.Add arr(1, i), i
Next i
CargaModosTramos arr, MisAgentes, Encabezados
m_Modo.Remove "ACC"
m_Modo.Remove "Plani"
Erase arr
End Sub
Private Sub CargaModosTramos(arr As Variant, MisAgentes As Dictionary, Encabezados As Dictionary)
Dim Modo As Variant
Dim centro As Variant
Dim fecha As Variant
Dim tramo As Variant
Dim agente As Variant
Dim MiModo As String
For Each Modo In m_Modo.Keys
If Not Modo = "ACC" And Not Modo = "Plani" Then GoTo SiguienteModo
For Each centro In Modos(Modo).Keys
For Each fecha In Modos(Modo).Centros(centro).Keys
For Each tramo In Modos(Modo).Centros(centro).Fechas(fecha).Keys
For Each agente In Modos(Modo).Centros(centro).Fechas(fecha).Tramos(tramo).Keys
MiModo = CalculaModo(arr, MisAgentes, Encabezados, agente & Modo, fecha)
Modos(MiModo).Centros(centro).Fechas(fecha).Tramos(tramo).Agentes(agente).Presentes = _
Modos(Modo).Centros(centro).Fechas(fecha).Tramos(tramo).Agentes(agente).Presentes
Modos(Modo).Centros(centro).Fechas(fecha).Tramos(tramo).BorrarAgente agente
Next agente
Next tramo
Next fecha
Next centro
SiguienteModo:
Next Modo
End Sub
Private Function CalculaModo(arr As Variant, MisAgentes As Dictionary, Encabezados As Dictionary, agente As Variant, fecha As Variant) As String
Dim i As Long: i = MisAgentes(agente)
Dim j As Long: j = Encabezados(CDate(fecha))
CalculaModo = arr(i, j)
End Function
</code></pre>
<p>The above class host another one called <code>Modos</code>(Services) with the following code:</p>
<pre><code>Option Explicit
Private m_Centro As Dictionary
Public Property Get Centros(ByVal Key As String) As Centros
With m_Centro
If Not .Exists(Key) Then .Add Key, New Centros
End With
Set Centros = m_Centro(Key)
End Property
Private Sub Class_Initialize()
Set m_Centro = New Dictionary
End Sub
Private Sub Class_Terminate()
Set m_Centro = Nothing
End Sub
Public Property Get Keys() As Variant
Keys = m_Centro.Keys
End Property
Public Sub BorrarModo()
m_Centro.RemoveAll
End Sub
Public Sub BorrarCentro(centro As Variant)
m_Centro.Remove CStr(centro)
End Sub
</code></pre>
<p>The above class hosts anothe class called <code>Centros</code>(Locations) with this code:</p>
<pre><code>Option Explicit
Private m_NombrePlantilla As String
Private m_Fecha As Dictionary
Private m_Porcentaje As Dictionary
Public Property Get Fechas(ByVal Key As String) As Fechas
With m_Fecha
If Not .Exists(Key) Then .Add Key, New Fechas
End With
Set Fechas = m_Fecha(Key)
End Property
Public Property Get Porcentajes(ByVal Key As String) As Porcentajes
With m_Porcentaje
If Not .Exists(Key) Then .Add Key, New Porcentajes
End With
Set Porcentajes = m_Porcentaje(Key)
End Property
Private Sub Class_Initialize()
Set m_Fecha = New Dictionary
Set m_Porcentaje = New Dictionary
End Sub
Private Sub Class_Terminate()
Set m_Fecha = Nothing
Set m_Porcentaje = Nothing
End Sub
Public Property Get Keys() As Variant
Keys = m_Fecha.Keys
End Property
Public Property Get NombrePlantilla() As String
NombrePlantilla = m_NombrePlantilla
End Property
Public Property Let NombrePlantilla(param As String)
m_NombrePlantilla = param
End Property
Public Property Get ExistePorcentaje(KPI As String) As Boolean
If m_Porcentaje.Exists(KPI) Then ExistePorcentaje = True
End Property
Public Sub BorrarFecha(fecha As Variant)
m_Fecha.Remove CStr(fecha)
End Sub
</code></pre>
<p>Centros hosts the next class which is <code>Fechas</code>(Dates) with the following code:</p>
<pre><code>Option Explicit
Private m_Fecha As Dictionary
Public Property Get Fechas(ByVal Key As String) As Fechas
With m_Fecha
If Not .Exists(Key) Then .Add Key, New Fechas
End With
Set Fechas = m_Fecha(Key)
End Property
Private Sub Class_Initialize()
Set m_Fecha = New Dictionary
End Sub
Private Sub Class_Terminate()
Set m_Fecha = Nothing
End Sub
Public Property Get Keys() As Variant
Keys = m_Fecha.Keys
End Property
</code></pre>
<p>Fecha hosts another class called <code>Tramo</code>(intervals) which has this code:</p>
<pre><code>Option Explicit
Private m_Tramo As Dictionary
Private m_Horario As String
Public Property Get Tramos(ByVal Key As String) As Tramos
With m_Tramo
If Not .Exists(Key) Then .Add Key, New Tramos
End With
Set Tramos = m_Tramo(Key)
End Property
Private Sub Class_Initialize()
Set m_Tramo = New Dictionary
End Sub
Private Sub Class_Terminate()
Set m_Tramo = Nothing
End Sub
Public Property Get Keys() As Variant
Keys = m_Tramo.Keys
End Property
Public Property Get Horario() As String
Horario = m_Horario
End Property
Public Property Let Horario(param As String)
m_Horario = param
End Property
Public Sub BorrarTramo(tramo As Variant)
m_Tramo.Remove CStr(tramo)
End Sub
</code></pre>
<p>Finally, Tramos hosts the last class, <code>Agentes</code>(Agents) with this code:</p>
<pre><code>Option Explicit
Private m_Agente As Dictionary
Property Get Agentes(ByVal Key As String) As Agentes
With m_Agente
If Not .Exists(Key) Then .Add Key, New Agentes
End With
Set Agentes = m_Agente(Key)
End Property
Private Sub Class_Initialize()
Set m_Agente = New Dictionary
End Sub
Private Sub Class_Terminate()
Set m_Agente = Nothing
End Sub
Public Property Get Keys() As Variant
Keys = m_Agente.Keys
End Property
</code></pre>
<p>The code for the class <code>Agentes</code> is this:</p>
<pre><code>Option Explicit
Private m_Presentes As Long
Public Property Get Presentes() As Long
Presentes = m_Presentes
End Property
Public Property Let Presentes(param As Long)
m_Presentes = m_Presentes + param
End Property
</code></pre>
<p>What this is doing is basically, going to the sheet <code>BaseACC</code> and fill for every worker and every day at what intervals is present. It's doing this under the temporal services (ACC/Plani).</p>
<p>After this, goes to the sheet <code>Mapa Habilidades</code> and checks if it`s ACC/Plani to adjust the presents to the services that can be found on that sheet.</p>
<p>This is just the loadup for the next steps. But I feel that if I could build this someway better when the whole process ends won't take forever to purge the memory, or worse, run out of memory.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T13:27:52.340",
"Id": "478262",
"Score": "0",
"body": "Your data seems pivoted, with lots of data duplicated everywhere. You would need much fewer iterations and objects with normalized data. Avoid declaring anything `As New`, that runs the `Initialize` handler in a not-necessarily expected way. Also `Set thing = Nothing` is nuking your auto-instantiated object, but then if you do `Debug.Print miClase Is Nothing` it will print `False` and have re-created the internal dictionary, because of the `As New`. Never declare things `As New` when you want to control when objects live and die."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:23:07.883",
"Id": "478276",
"Score": "0",
"body": "@MathieuGuindon I don't actually have data duplicated if you mean on my sheets. If not, Could you elaborate that? Also, what is the difference between `Dim X As Object` and `Set X = New Object` and `Dim X As New Object`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:39:35.970",
"Id": "478279",
"Score": "1",
"body": "I haven't looked in details, but looking at the worksheet the date columns should not be columns but rows; there should be a *Date* column with the date, and then one other column to hold the data for that date - that's what *pivoted* means =) as for the implications of `As New`, see [Rubberduck](https://rubberduckvba.com/Inspections/Details/SelfAssignedDeclaration)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:54:47.757",
"Id": "478283",
"Score": "0",
"body": "@MathieuGuindon I get the pivoted now... But I would trade the iterations in the column for more iterations in rows, right? Would that improve anything? If so is a good tip, but still won't change my problem... I'd really appreaciate if you had the time to look throughly into my test workbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T10:43:27.207",
"Id": "478347",
"Score": "1",
"body": "@MathieuGuindon you were right, transposing the Dates to a single column spared me like 70s on execution time! That's something :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T06:43:29.023",
"Id": "243649",
"Score": "3",
"Tags": [
"object-oriented",
"vba",
"excel"
],
"Title": "Setting a forecast for 2,5k workers intraday for a whole month"
}
|
243649
|
<p>A 1D binary string has the following dynamics
<span class="math-container">$$1100 \to 1010,\quad 1101\to 1011$$</span>
each with rate <span class="math-container">\$p<1\$</span>. That is if we see <span class="math-container">\$110\$</span> in the string, then we change to <span class="math-container">\$101\$</span> with probability <span class="math-container">\$p\$</span>. I am interested in the count of <span class="math-container">\$00,01\$</span> and <span class="math-container">\$11,\$</span> and <span class="math-container">\$1100\$</span> in the binary string. For this, I have written the following code which I want to optimize (time).</p>
<p>This model is known as the Restricted Asymmetric Simple Exclusion Process (or RASEP), a modified version of <a href="https://demonstrations.wolfram.com/TotallyAsymmetricSimpleExclusionProcessTASEP/" rel="nofollow noreferrer">TASEP</a>.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from random import random
sweeps = 1000
n = 1000
p = 0.5
rho = 0.5
ensemble_size = 100
"""preparing 1D lattice with n number of 1s and L-n number of 0s.
Convinient to work with rho = n/L."""
def initialize(rho = 0.25, L = 100):
config = np.array([1]*int(rho*L)+[0]*(L-int(rho*L)))
np.random.shuffle(config)
return config
#N0 = number of 00, N1 = number of 01 and 10, N3 = number of 11, and N12 = number of 1100
def count(state):
n = len(state)
n0 = n1 = n3 = n12 = 0
for j in range(n):
neighbour_sum = int(f"{state[j%n]}{state[(j+1)%n]}{state[(j+2)%n]}{state[(j+3)%n]}",2)
if neighbour_sum % 4 == 0:
n0 += 1
if neighbour_sum == 12:
n12 += 1
elif neighbour_sum % 4 == 3:
n3 += 1
n1 = n - n0 - n3
return n0, n1, n3, n12
"""Dynamics"""
def dynamics(state, sweeps, p):
n = len(state)
n0, n1, n3, n12 = count(state)
N0, N1, N3, N12 = np.zeros(sweeps), np.zeros(sweeps), np.zeros(sweeps), np.zeros(sweeps)
# random state indices
J = np.random.randint(0, n, size=(sweeps, n))
#loop
for t in range(sweeps):
for tt in range(n):
# random indices
j = J[t, tt]
neighbour_sum = int(f"{state[j%n]}{state[(j+1)%n]}{state[(j+2)%n]}{state[(j+3)%n]}",2)
if neighbour_sum == 12 and random() < p:
state[(j+1)%n], state[(j+2)%n] = 0, 1
n0 -= 1
n1 += 2
n3 -= 1
n12 -= 1
elif neighbour_sum == 13 and random() < p:
state[(j+1)%n], state[(j+2)%n] = 0, 1
if state[(j+4)%n] == 0 and state[(j+5)%n] == 0:
n12 += 1
N0[t], N1[t], N3[t], N12[t] = n0, n1, n3, n12
return N0/n, N1/n, N3/n, N12/n
def ensembleAvg(ensemble_size):
ensemble = np.zeros((4, ensemble_size, sweeps))
for _ in range(ensemble_size):
state = initialize(rho, n)
ensemble[0,_], ensemble[1,_], ensemble[2,_], ensemble[3,_] = dynamics(state, sweeps, p)
return np.average(ensemble,axis = 1)
avg_ensemble = ensembleAvg(ensemble_size)
N0, N1, N3, N12 = avg_ensemble[0], avg_ensemble[1], avg_ensemble[2], avg_ensemble[3]
plt.title(f"size:{n}", color='b');
plt.plot(np.arange(sweeps), N0, color='blue', label = "00")
plt.plot(np.arange(sweeps), N1, color='darkgreen', label = "01 & 01")
plt.plot(np.arange(sweeps), N3, color='purple', label = "11")
plt.plot(np.arange(sweeps), N12, color='red', label = "1100")
plt.legend()
plt.xlabel("Sweeps", fontsize=20);
plt.ylabel("Number density", fontsize=20);
plt.axis('tight');
plt.savefig(f"{n}.pdf")
plt.show()
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T06:47:50.323",
"Id": "243650",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"simulation"
],
"Title": "Monte Carlo Simulation of a Markov Process"
}
|
243650
|
<p><strong>Requirement</strong></p>
<p>We use a tool where we have Jython as one of the scripting languages available for making custom scripts. The requirement is that we need to make multiple API calls (in parallel) and aggregate those results in a single JSON using a script.</p>
<p><strong>Previous attempts</strong></p>
<p>My go-to instinct was to use <code>requests</code> but it didn't work out. Please refer to the following StackOverflow question.</p>
<p><a href="https://stackoverflow.com/q/59976126/6042824">Jython: Getting SSLError when doing requests get</a></p>
<p>In my local environment, the simple Java way of doing it worked but when trying to do the same thing in the tool, it gave me an error.</p>
<p><strong>Working implementation</strong></p>
<p>So, the only other option that we could think of was using cURL. Following is a similar implementation that we have.</p>
<p><strong>Note:</strong> I used the <a href="https://jsonplaceholder.typicode.com/" rel="nofollow noreferrer">jsonplaceholder APIs</a> for doing this test.</p>
<pre class="lang-py prettyprint-override"><code>import json
import subprocess
from threading import Thread
import pprint
def execute_get_api(url, key, results):
p1 = subprocess.Popen([
'curl', '--location', '--request', 'GET', url
], stdout=subprocess.PIPE, shell=False)
out, err = p1.communicate()
results[key] = json.loads(out)
def get_post(post_id):
post_url = 'https://jsonplaceholder.typicode.com/posts/%s' % post_id
comments_url = 'https://jsonplaceholder.typicode.com/posts/%s/comments' % post_id
# Temporary dictionary to store responses from the API calls
results = {
"post": "",
"comments": ""
}
# Making the API calls
threads = []
get_posts = Thread(target=execute_get_api,
args=[post_url, 'post', results])
get_comments = Thread(target=execute_get_api,
args=[comments_url, 'comments', results])
get_posts.start()
get_comments.start()
threads.append(get_posts)
threads.append(get_comments)
for th in threads:
th.join()
return results
def driver():
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(get_post(1))
if __name__ == '__main__':
driver()
</code></pre>
<p><strong>Output</strong></p>
<pre><code>{ 'comments': [ { u'body': u'laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium',
u'email': u'Eliseo@gardner.biz',
u'id': 1,
u'name': u'id labore ex et quam laborum',
u'postId': 1},
{ u'body': u'est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et',
u'email': u'Jayne_Kuhic@sydney.com',
u'id': 2,
u'name': u'quo vero reiciendis velit similique earum',
u'postId': 1},
{ u'body': u'quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione',
u'email': u'Nikita@garfield.biz',
u'id': 3,
u'name': u'odio adipisci rerum aut animi',
u'postId': 1},
{ u'body': u'non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati',
u'email': u'Lew@alysha.tv',
u'id': 4,
u'name': u'alias odio sit',
u'postId': 1},
{ u'body': u'harum non quasi et ratione\ntempore iure ex voluptates in ratione\nharum architecto fugit inventore cupiditate\nvoluptates magni quo et',
u'email': u'Hayden@althea.biz',
u'id': 5,
u'name': u'vero eaque aliquid doloribus et culpa',
u'postId': 1}],
'post': { u'body': u'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto',
u'id': 1,
u'title': u'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
u'userId': 1}}
</code></pre>
<p>I'm not sure if there is any other way of doing this. Also, do let me know if this approach can be improved.</p>
<p>Any help will be appreciated :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:05:44.043",
"Id": "478284",
"Score": "0",
"body": "In that StackOverflow thread you show Python 2.7.1 which is end of life and no longer supported. You should stop using it. *Maybe* [this](https://stackoverflow.com/a/31812342/6843158) can help (just a guess). Another hint: if the server you are trying to reach uses Server Name Indication (SNI) this could be the cause of a handshake failure. I think your Python version is too old to support that. Upgrade your environment and your scripts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T06:07:43.933",
"Id": "478331",
"Score": "0",
"body": "@Anonymous - It was not that long back that I installed Jython and it was the latest version at that time. Still, I see that they have a newer version 2.7.2. Will install and test that out."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T06:55:59.963",
"Id": "243651",
"Score": "0",
"Tags": [
"multithreading",
"curl",
"jython"
],
"Title": "Use cURL and threads to make API calls"
}
|
243651
|
<p><strong>UPDATE</strong>: I have changed some of the code from feedback provided on #cpp_review</p>
<p>I created a little project that will basically move all header files into one (mostly for libs).</p>
<p>The project is small, only 2 classes and a main file for the cli options
The projects github is here: <a href="https://github.com/AntonioCS/only_one_header" rel="nofollow noreferrer">https://github.com/AntonioCS/only_one_header</a></p>
<p>Here are the files:</p>
<p><a href="https://github.com/AntonioCS/only_one_header/blob/master/src/main.cpp" rel="nofollow noreferrer">main.cpp</a> (please ignore the duplicate <code>static const char</code> I am trying to figure out some issues)</p>
<pre><code>#include <docopt.h>
//#include <iostream>
#include "HeaderManager.h"
static const char USAGE2[] =
R"(Usage: onlyoneheader [-ho <file>] [--output=<file>] [--remove_comments] [--no_separators] [--no_timestamp] [--silent] <path>
-h --help show this
-o <file> --output=<file> specify output file [default: ./default.h]
--remove_comments remove one line comments from the header files
--no_separators don't add // <filename> START|END separators
--no_timestamp don't add timestamp
--silent no info text
)";
static const char USAGE[] =
R"(Usage: onlyoneheader [-h] [--output=<file>] [--remove_comments] [--no_separators] [--no_timestamp] [--silent] <path>
-h --help show this
--output=<file> specify output file [default: ./allinone.h]
--remove_comments remove one line comments from the header files
--no_separators don't add // <filename> START|END separators
--no_timestamp don't add timestamp
--silent no info text
)";
int main(int argc, char** argv) {
std::map<std::string, docopt::value> args = docopt::docopt(
USAGE,
{ argv + 1, argv + argc },
true,
"Only One Header v0.1"
);
#if 0
for (auto const& arg : args) {
std::cout << arg.first << ": " << arg.second << std::endl;
}
#endif
OnlyOneHeader::HeaderManager headerManager{args["<path>"].asString()};
headerManager.setOptionAddSeparatorState(args["--no_separators"].asBool() == false);
headerManager.setOptionAddTimestampState(args["--no_timestamp"].asBool() == false);
headerManager.setOptionRemoveCommentsState(args["--remove_comments"].asBool());
headerManager.setOptionSilentState(args["--silent"].asBool());
headerManager.process();
const auto output_file_name{ args["--output"].isString() ? args["--output"].asString() : "all_in_one.h" };
headerManager.output(output_file_name);
}
</code></pre>
<p><a href="https://github.com/AntonioCS/only_one_header/blob/master/src/HeaderManager.h" rel="nofollow noreferrer">HeaderManager.h</a></p>
<pre><code>#pragma once
#include <vector>
#include <string>
#include <unordered_map>
#include "HeaderFile.h"
namespace OnlyOneHeader {
class HeaderManager
{
std::vector<HeaderFile> m_all_hf{};
std::string m_dir_path{};
std::unordered_map<std::string, HeaderFile*> m_header_filename_connection;
std::unordered_map<std::string, uint16_t> m_global_includes;
std::string m_output_file{ "all_in_one.h" };
std::vector<std::string> m_unused_hf{};
double m_elapsed_process{};
double m_elapsed_ouput{};
struct {
bool add_separators{ true };
bool add_timestamp{ true };
bool remove_comments{ false };
bool silent{ false };
} m_options;
public:
HeaderManager(const std::string& path) : m_dir_path(path) {}
void process();
void output(const std::string& output_file);
void setOptionAddSeparatorState(bool state) { m_options.add_separators = state; }
void setOptionAddTimestampState(bool state) { m_options.add_timestamp = state; }
void setOptionRemoveCommentsState(bool state) { m_options.remove_comments = state; }
void setOptionSilentState(bool state) { m_options.silent = state; }
private:
void displayInfo() const;
void grabAllHeaderFiles();
void removeUnIncludedFiles();
void grabAllGlobalIncludesFromHeaderFile(const HeaderFile& hf);
void createFileNameHeaderFileConnection();
void order();
void decreaseAllIncluded(HeaderFile& hf);
};
}
</code></pre>
<p><a href="https://github.com/AntonioCS/only_one_header/blob/master/src/HeaderManager.cpp" rel="nofollow noreferrer">HeaderManager.cpp</a></p>
<pre><code>#include <fstream>
#include "HeaderManager.h"
#include <chrono>
#include <iostream>
namespace OnlyOneHeader {
double getMsCount(const std::chrono::steady_clock::time_point& begin)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - begin).count() / 1000.0;
}
void HeaderManager::process()
{
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
grabAllHeaderFiles();
removeUnIncludedFiles(); //this must come before createFileNameHeaderFileConnection()
createFileNameHeaderFileConnection();
order();
m_elapsed_process = getMsCount(begin);
}
void HeaderManager::output(const std::string& output_file)
{
m_output_file = output_file;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
std::fstream output{m_output_file, std::ios::out};
if (output.is_open()) {
output << "#pragma once\n\n";
if (m_options.add_timestamp) {
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
output << "////////////////////////////////////////\n";
output << "//AUTO GENERATED FILE - DO NOT EDIT\n";
output << "//Generated on " << std::put_time(&tm, "%Y-%m-%d at %H:%M:%S") << "\n";
output << "////////////////////////////////////////\n\n";
}
for (const auto& [globalInc, v] : m_global_includes) {
output << "#include <" << globalInc << ">\n";
}
output << '\n';
for (const auto& hf : m_all_hf) {
if (m_options.add_separators) output << "/*** " << hf.filename() << " START ***/\n";
output << hf.getContents();
if (m_options.add_separators) output << "/*** " << hf.filename() << " END ***/\n";
}
output.close();
m_elapsed_ouput = getMsCount(begin);
if (!m_options.silent) displayInfo();
}
else {
throw std::runtime_error{"Unable to open output file"};
}
}
void HeaderManager::grabAllHeaderFiles()
{
if (!fs::is_directory(m_dir_path)) {
throw std::runtime_error{ "Invalid directory: " + m_dir_path };
}
for (const auto& p : fs::directory_iterator(m_dir_path)) {
if (p.path().extension() == ".h" || p.path().extension() == ".hpp") {
auto hf = m_all_hf.emplace_back(p.path(), m_options.remove_comments);
if (hf.hasGlobalIncludes()) {
grabAllGlobalIncludesFromHeaderFile(hf);
}
}
}
}
void HeaderManager::removeUnIncludedFiles()
{
std::vector<HeaderFile> included_files;
for (const auto& hf : m_all_hf) {
if (!hf.hasLocalIncludes()) {
bool was_not_included{true};
//since this file doesn't include any other local file
//I'm looping all the other include files and checking them to see if they include this file
for (const auto& hf2 : m_all_hf) {
if (hf2.isInLocalIncludes(hf.filename())) {
included_files.push_back(hf);
was_not_included = false;
break;
}
}
if (was_not_included) {
m_unused_hf.emplace_back(hf.filename().data());
}
}
else {
included_files.push_back(hf);
}
}
m_all_hf = included_files;
}
void HeaderManager::grabAllGlobalIncludesFromHeaderFile(const HeaderFile& hf)
{
for (const auto& gi : hf.allGlobalIncludes()) {
m_global_includes[gi] += 1;
}
}
void HeaderManager::createFileNameHeaderFileConnection()
{
for (auto& hf : m_all_hf) {
m_header_filename_connection[hf.filename()] = &hf;
}
}
void HeaderManager::order()
{
for (auto& hf : m_all_hf) {
if (hf.hasLocalIncludes()) {
decreaseAllIncluded(hf);
}
}
std::sort(
m_all_hf.begin(),
m_all_hf.end(),
[](const HeaderFile& a, const HeaderFile& b)
{
return a.position_value < b.position_value;
}
);
}
void HeaderManager::decreaseAllIncluded(HeaderFile& hf)
{
constexpr std::size_t order_decrease_amount{100};
for (const auto& infile : hf.allLocalIncludes()) {
auto initv = m_header_filename_connection[infile]->position_value;
while (m_header_filename_connection[infile]->position_value >= hf.position_value) {
m_header_filename_connection[infile]->position_value -= order_decrease_amount;
}
if (
m_header_filename_connection[infile]->position_value != initv &&
m_header_filename_connection[infile]->hasLocalIncludes()
) {
decreaseAllIncluded(*m_header_filename_connection[infile]);
}
}
}
void HeaderManager::displayInfo() const
{
std::cout << "Time for procesing: " << m_elapsed_process << "ms\n";
std::cout << "Time for outputing: " << m_elapsed_ouput << "ms\n";
std::cout << "Total time: " << (m_elapsed_ouput + m_elapsed_process) << "ms\n";
std::cout << "Total global headers: " << m_global_includes.size() << '\n';
std::cout << "File - Times it was included\n";
for (const auto& [globalInc, v] : m_global_includes) {
std::cout << globalInc << " - " << v << '\n';
}
std::cout << "Total local headers: " << m_header_filename_connection.size() + m_unused_hf.size() << '\n';
std::cout << "Total headers not included: " << m_unused_hf.size() << '\n';
}
}
</code></pre>
<p><a href="https://github.com/AntonioCS/only_one_header/blob/master/src/HeaderFile.h" rel="nofollow noreferrer">HeaderFile.h</a></p>
<pre><code>#pragma once
#include <filesystem>
#include <vector>
#include <string>
namespace OnlyOneHeader {
namespace fs = std::filesystem;
class HeaderFile
{
fs::path m_path{};
std::vector<std::string> m_local_includes{};
std::vector<std::string> m_global_includes{};
std::string m_filename{};
std::string m_contents{};
inline static const std::string m_bom_string{ "\xEF\xBB\xBF" };
bool m_remove_comments{ false };
public:
std::size_t position_value{ 9999 };
HeaderFile(const fs::path& p, bool remove_comments = false) : m_path(p), m_filename(p.filename().string()), m_remove_comments(remove_comments)
{
extractData();
}
[[nodiscard]] const std::vector<std::string>& allLocalIncludes() const
{
return m_local_includes;
}
[[nodiscard]] const std::vector<std::string>& allGlobalIncludes() const
{
return m_global_includes;
}
[[nodiscard]] bool isInLocalIncludes(const HeaderFile& hf) const;
[[nodiscard]] bool isInLocalIncludes(std::string_view file) const;
[[nodiscard]] std::string filename() const
{
return m_filename;
}
void extractData();
[[nodiscard]] std::string getContents() const
{
return m_contents;
}
[[nodiscard]] std::string path() const
{
return m_path.string();
}
[[nodiscard]] bool hasLocalIncludes() const
{
return !m_local_includes.empty();
}
[[nodiscard]] bool hasGlobalIncludes() const
{
return !m_global_includes.empty();
}
private:
void extractIncludeFilename(const std::string& line);
[[nodiscard]] bool startsWith(std::string_view str, std::string_view startsWithThis) const;
};
}
</code></pre>
<p><a href="https://github.com/AntonioCS/only_one_header/blob/master/src/HeaderFile.cpp" rel="nofollow noreferrer">HeaderFile.cpp</a></p>
<pre><code>
#include <fstream>
#include <algorithm> //std::sort
#include "HeaderFile.h"
namespace OnlyOneHeader {
enum class ExtractState
{
BOM_CHECK,
READ_CODE
};
bool HeaderFile::isInLocalIncludes(const HeaderFile& hf) const
{
return isInLocalIncludes(hf.filename());
}
bool HeaderFile::isInLocalIncludes(std::string_view file) const
{
return (std::find(m_local_includes.begin(), m_local_includes.end(), file) != m_local_includes.end());
}
void HeaderFile::extractData()
{
std::fstream f{path(), std::ios::in};
if (!f.is_open()) {
throw std::runtime_error{ "Unable to open file: " + path() };
}
ExtractState state{ ExtractState::BOM_CHECK };
std::string line{};
while (std::getline(f, line)) {
switch (state) {
case ExtractState::BOM_CHECK:
{
//detect BOM
if (startsWith(line, m_bom_string)) {
line.erase(0, m_bom_string.size()); //simple way to get rid of this thanks to Gaurav from cpplang slack
}
state = ExtractState::READ_CODE;
}
[[fallthrough]];
case ExtractState::READ_CODE:
{
if (startsWith(line, "#include ")) {
extractIncludeFilename(line);
}
else if (!startsWith(line, "#pragma once") && !line.empty()) {
if (m_remove_comments) {
auto it = std::find_if(line.begin(), line.end(), [](int c) { return !std::isspace(c); });
if (it != line.end() && *it == '/' && *(++it) == '/')
continue;
}
m_contents += line + '\n';
}
}
break;
}
}
}
void HeaderFile::extractIncludeFilename(const std::string& line)
{
auto f = line.find('"');
if (f != std::string::npos) {
auto f2 = line.find('"', f + 1);
if (f2 != std::string::npos) {
m_local_includes.push_back(line.substr(f + 1, f2 - f - 1));
}
}
else {
f = line.find('<');
if (f != std::string::npos) {
auto f2 = line.find('>');
if (f2 != std::string::npos) {
m_global_includes.push_back(line.substr(f + 1, f2 - f - 1));
}
}
}
}
bool HeaderFile::startsWith(std::string_view str, std::string_view startsWithThis) const
{
auto v = str.rfind(startsWithThis, 0);
return (v == 0);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This code is generally clean and easy to understand, which is good. Here are some things that may help you improve your code.</p>\n<h2>Make sure you have all required <code>#include</code>s</h2>\n<p>The code uses <code>sort</code> but doesn't <code>#include <algorithm></code> and <code>main</code> uses <code>map</code> but doesn't <code>#include <map></code>. For portability and immunity from changes to third party libraries, it's best to add includes for all of the functions your code uses, whether or not another library has already included them.</p>\n<h2>Add support for multiline comments</h2>\n<p>At the moment, if we have a header file which includes this:</p>\n<pre><code>// this is comment #1\n/* This is comment #2 */\n/* \n * This is a multiline comment #3\n */\n</code></pre>\n<p>only the first comment is excluded if we specify <code>--remove_comments</code>.</p>\n<h2>Use rational return values</h2>\n<p>Almost all of your member function return <code>void</code> and take no parameters. This is highly suspect. For example, it might be useful for <code>grabAllHeaderFiles</code> to report the number of files processed. Also, the <code>displayInfo()</code> might benefit from being passed a <code>std::ostream</code> rather than always printing to <code>std::cout</code>.</p>\n<h2>Rethink class data members</h2>\n<p>Is it really necessary to have all of those data structures only to throw most of them away? For instance, <code>m_unused_hf</code> could be replaced with a simple counter with no loss of functionality. Also it appears that the <code>--remove_comments</code> is properly part of <code>HeaderManager</code>, so why is it duplicated in every <code>HeaderFile</code>? It would probably be better to pass it in as a parameter.</p>\n<h2>Rethink the exposed interface</h2>\n<p>Only <code>HeaderManager</code> uses <code>HeaderFile</code> so it might make sense to put its definition inside <code>HeaderManager</code>. Also, the only thing that uses <code>HeaderFile::path()</code> is <code>HeaderFile::extractData()</code>. Instead of writing this:</p>\n<pre><code>std::fstream f{path(), std::ios::in};\n</code></pre>\n<p>I'd rewrite that as:</p>\n<pre><code>std::ifstream f{m_path};\n</code></pre>\n<p>Also, it seems to me that <code>extractData</code> should be <code>private</code>.</p>\n<h2>Consider a more efficient algorithm and data structure</h2>\n<p>The <code>removeUnIncludedFiles()</code> is not particularly efficient. Instead of making <span class=\"math-container\">\\$n^2\\$</span> comparisons, consider constructing a <code>map</code> and keeping a count of all local include files, as is done for the global include files, would be much simpler. Another possibility would be to simply keep a global m-ary tree for all files. Try running your program on <code>/usr/include</code> and see why reducing memory footprint might be a good idea. On my machine, use uses up the entire stack and crashes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T18:32:07.483",
"Id": "478299",
"Score": "0",
"body": "Thank you so much for you review. I have addressed some of your points.\nRegarding the `--remove_comments`, this is the 1st version, so I went with the easy and simple comments. I will update the code as soon as I commit everything. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T18:35:04.383",
"Id": "478300",
"Score": "1",
"body": "I'm glad you found it useful! You may already know this, but it may be helpful to read (or re-read) https://codereview.stackexchange.com/help/someone-answers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:24:25.230",
"Id": "243674",
"ParentId": "243653",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243674",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T08:38:10.317",
"Id": "243653",
"Score": "4",
"Tags": [
"c++",
"console"
],
"Title": "Small program to convert multiple header files into one"
}
|
243653
|
<p>I want to implement a random word generator that would not use Import statements. The solution is working for a *nix system. The solution does yield a random word, but please suggest:</p>
<ol>
<li>How to make the function optimally/safely return words with a higher position in the list(e.g. now we're almost guaranteed to return an 'A' word)</li>
<li>How to get a word with min/max length instead of length</li>
<li>Should I break this into smaller functions?</li>
<li>How to make the code more readable/higher performance</li>
<li>Is there a better approach to this problem? How to tell which modules are better off imported instead of implemented from scratch(except for the built-ins)?</li>
</ol>
<pre><code>def generate_random_word(length=8):
"""
Return a random string from /usr/share/dict/words on a *nix system
"""
with open('/usr/share/dict/words', 'r') as words_file, open("/dev/random", 'rb') as random_file:
random_words = words_file.read().split('\n')
size_words = [x for x in random_words if len(x) == length]
for _ in range(0, 100):
while True:
try:
random_word = size_words[(int.from_bytes(random_file.read(1), 'big'))]
except IndexError:
continue
break
return random_word
</code></pre>
|
[] |
[
{
"body": "<p>I am surprised that you chose to use <code>/dev/random</code> although I can understand that for some purposes like generating private keys a source of strong entropy is preferred and there are even <a href=\"https://www.crowdsupply.com/13-37/infinite-noise-trng\" rel=\"nofollow noreferrer\">devices</a> for that. Then <a href=\"https://unix.stackexchange.com/questions/324209/when-to-use-dev-random-vs-dev-urandom\">this discussion</a> could interest you. But the built-in <code>random</code> module in python should be sufficient here.</p>\n<p>To read the file to a list of items you can just do this:</p>\n<pre><code>with open('/usr/share/dict/words', 'r') as f:\n lines = f.read().splitlines()\n</code></pre>\n<p>Good thing is that you are using the context manager for the <code>open</code> function.</p>\n<p>Try to avoid <code>IndexError</code> rather than handle it and ignore it.</p>\n<p>If your file is small (check size before opening) you can be lazy, load all items to a list, then filter it, and return one item at random:</p>\n<pre><code>def generate_random_word(min_length=8, max_length=13):\n with open('/usr/share/dict/words', 'r') as f:\n lines = f.read().splitlines()\n\n # select words matching desired length\n # selection = [line for line in lines if len(line) <= max_length and len(line) >= min_length ]\n selection = [line for line in lines if min_length <= len(line) <= max_length]\n # no match found\n if len(selection) == 0:\n return None\n\n return random.choice(selection)\n</code></pre>\n<p>If no matching item is found (or the file is empty) then I chose to return None.</p>\n<p>If you want to filter lines at the source the implementation could be like this:</p>\n<pre><code>def generate_random_word(min_length=8, max_length=13):\n with open('/usr/share/dict/words', 'r') as f:\n selection = [line for line in f.read().splitlines() if min_length <= len(line) <= max_length]\n\n # no match found\n if len(selection) == 0:\n return None\n\n return random.choice(selection)\n</code></pre>\n<p>The file has to exist but it can be empty, then there is no error but the function will return None. Use <code>os.exists</code> to test that the file is present.</p>\n<p>Yes, there is an import but it is a built-in module, does not require installation of a third-party module with PIP. It is also portable and not just Unix.</p>\n<p>However, if you insist on <code>/dev/random</code> and want no import one thing you could do is retrieve a random integer like what you are doing now and use it in a modulo-type fashion against the list of matching items, to pick one word at random. Be careful with implementation as you may introduce unwanted bias in the selection. Random functions exist for a reason.</p>\n<p>While it is possible to rely solely on <code>/dev/random</code> reimplementing the functionality with decent randomization will result in more code and reinventing the wheel.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:45:30.570",
"Id": "478289",
"Score": "0",
"body": "Is there a better way to determine if a module is a built-in than what's described here https://stackoverflow.com/questions/4922520/determining-if-a-given-python-module-is-a-built-in-module ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:54:46.110",
"Id": "478290",
"Score": "1",
"body": "@KateVelasquez: Check out https://docs.python.org/3/library/ for a non-programmatic way. It just lists all modules in the standard library, which are included in all Python installations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:44:25.313",
"Id": "243669",
"ParentId": "243654",
"Score": "4"
}
},
{
"body": "<p>Even if you don't want to use the standard library <code>random</code> module, you might want to <a href=\"https://github.com/python/cpython/blob/3.8/Lib/random.py\" rel=\"nofollow noreferrer\">take a look at their implementation</a> and do something similar. This way you can always replace your random class with the standard library one. Here I directly copied the relevant methods:</p>\n<pre><code>def _random(numbytes):\n with open('/dev/random', 'rb') as f:\n return f.read(numbytes)\n\nclass Random:\n def getrandbits(self, k):\n """getrandbits(k) -> x. Generates an int with k random bits."""\n if k <= 0:\n raise ValueError('number of bits must be greater than zero')\n numbytes = (k + 7) // 8 # bits / 8 and rounded up\n x = int.from_bytes(_random(numbytes), 'big')\n return x >> (numbytes * 8 - k) # trim excess bits\n\n def _randbelow(self, n):\n "Return a random int in the range [0,n). Raises ValueError if n==0."\n\n getrandbits = self.getrandbits\n k = n.bit_length() # don't use (n-1) here because n can be 1\n r = getrandbits(k) # 0 <= r < 2**k\n while r >= n:\n r = getrandbits(k)\n return r\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\n return seq[i]\n</code></pre>\n<p>You can then use it like this:</p>\n<pre><code>random = Random()\n\ndef generate_random_word(length=8):\n with open('/usr/share/dict/words') as file:\n words = [word for line in file if len(word := line.strip()) == length]\n return random.choice(words)\n</code></pre>\n<p>If you need to do this more than once, then you might want to read the list of words only once and not every time you run the function. You can achieve this by using a nested function (you could also use a global variable or a class):</p>\n<pre><code>def random_word_generator(length=8):\n with open('/usr/share/dict/words') as file:\n words = [word for line in file if len(word := line.strip()) == length]\n def _generate():\n return random.choice(words)\n return _generate\n</code></pre>\n<p>Which you can use like this:</p>\n<pre><code>random = Random()\ngenerate_random_word = random_word_generator()\nrandom_word = generate_random_word()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T06:49:49.910",
"Id": "243903",
"ParentId": "243654",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T09:19:23.423",
"Id": "243654",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Python random word generator"
}
|
243654
|
<p>I have an excel sheet <code>G0.xlsx</code> which has 3 sheets in it <code>Winter</code>, <code>Summer</code>, <code>Rest</code></p>
<p>Since the file has multiple contents, I am sharing the link of the file: <a href="https://drive.google.com/file/d/1z_-wOJYF86WB0jbsN6PCwcyghhn_AEj0/view?usp=sharing" rel="nofollow noreferrer">Link to the file</a></p>
<p>I am trying to manipulate the data in all the 3 sheets in order to build one huge file for one entire year and the time must be of a 15min frequency (as it is in the file).</p>
<p>I also have the following conditions:</p>
<blockquote>
<p>Winter: 01.11 - 20.03</p>
<p>Summer: 15.05 - 14.09</p>
<p>Rest: 21.03 - 14.05 & 15.09 - 31.10</p>
</blockquote>
<p>and based on these conditions, the final table must contain the values.</p>
<p>The below code works perfectly fine for me, but it takes a lot of time for generating the output. I want to know if this code can be made more time-efficient. </p>
<pre><code>import pandas as pd
import holidays
import numpy as np
import functools
YEAR = 2020
seasons = ['Winter', 'Summer', 'Rest']
def get_holidays(year, country='DE', province=None):
if province is not None:
country_holidays = holidays.CountryHoliday(
country, years=int(year), prov=province)
else:
country_holidays = holidays.CountryHoliday(
country, years=int(year))
country_holidays = list(country_holidays.keys())
country_holidays = [d.strftime('%Y-%m-%d') for d in country_holidays]
return country_holidays
def calculate_day(x):
# get previous day for timestamp before hh:15
if x.hour == 0 and x.minute < 15:
return (x - pd.DateOffset(days=1)).day_name()
return x.day_name()
def date_editing_df(df, holiday_list, year):
year = str(year)
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
td = pd.to_timedelta(df['Time'].astype(str))
df1 = df.assign(Time=td.mask(td == pd.Timedelta(0),
td + pd.Timedelta(1, 'd')), a=1)
df2 = pd.DataFrame({'dates': pd.date_range(
'01.01.'+year, '31.12.'+year), 'a': 1})
df = df2.merge(df1, how='outer').drop('a', axis=1)
df['dates'] = df['dates'].add(
df.pop('Time')).dt.strftime('%d.%m.%Y %H:%M')
df['dates'] = pd.to_datetime(df['dates'], dayfirst=True)
df['day'] = df['dates'].apply(calculate_day)
df['day'].replace(weekdays, 'Werktag', inplace=True)
df['day'].replace(
{'Saturday': 'Samstag', 'Sunday': 'Sonntag'}, inplace=True)
holiday_list = pd.to_datetime(holiday_list).tolist()
comp = [(df['dates'] > h) & (df['dates'] <= h +
pd.offsets.DateOffset(days=1))
for h in holiday_list]
# join all mask by logical or
mask = np.logical_or.reduce(comp)
df['day'] = np.where(mask, 'Sonntag', df['day'])
df['Final'] = df.lookup(df.index, df['day'])
df.drop(['Samstag', 'Sonntag', 'Werktag'], axis=1, inplace=True)
return df
for season in seasons:
df = pd.read_excel('G0.xlsx', header=0, sheet_name=seasons)
w_df = df['Winter']
s_df = df['Summer']
r_df = df['Rest']
h_list = get_holidays(YEAR)
w_df = date_editing_df(w_df, h_list, YEAR)
s_df = date_editing_df(s_df, h_list, YEAR)
r_df = date_editing_df(r_df, h_list, YEAR)
w_df.rename(columns={'Final': 'winter'}, inplace=True)
s_df.rename(columns={'Final': 'summer'}, inplace=True)
r_df.rename(columns={'Final': 'rest'}, inplace=True)
all_dfs = [w_df, s_df, r_df]
final_df = functools.reduce(
lambda left, right: pd.merge(left, right, on='dates'), all_dfs)
d = pd.to_datetime(final_df['dates'].dt.strftime('%m-%d-' + str(YEAR)))
m1 = d.between(
str(YEAR)+'-11-01', str(YEAR)+'-12-31') | d.between(str(YEAR)+'-01-01',
str(YEAR)+'-03-20')
m2 = d.between(str(YEAR)+'-05-15', str(YEAR)+'-09-14')
final_df['Season'] = np.select(
[m1, m2],
['winter', 'summer'],
default='rest'
)
final_df['values'] = final_df.lookup(
final_df.index,
final_df['Season']
)
final_df = final_df[['dates', 'values']]
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T10:58:10.973",
"Id": "243656",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "How can the following pandas script be made more efficient?"
}
|
243656
|
<p>It stretches a bit the scope of C++, but hey, they gave us the 17 standard, so why not? Some snippet were found all over the internet, but the whole implementation is original.</p>
<p>Here is an example main:</p>
<pre><code>#include <string>
#include <iostream>
#include "NamedArgs.hpp"
// Declare named type arguments with the NamedArg helper macro
// NamedArg(TypeName, InterfaceName, TypedDefaultValue)
NamedArg(TName, n, std::string{"John"})
NamedArg(TSurn, s, std::string{"Doe"})
// Define a usual function using the TypesNames above
void intro( TName nm, TSurn sm) {
std::cout << "My name is " << sm << ", "
<< nm << " " << sm << std::endl;
}
int main() {
// Define a wrapper functor accepting position independent
// named arguments with the NamedArgsFunc helper macro
// NamedArgsFunc(Function, InterfaceName)
NamedArgsFunc(intro, I)
// Calling the wrapper function with InterfaceNames in any arrangement
I();
I( n="James" );
I( s="Bond", n="James" );
I( n="Bond", s="James" );
return 0;
}
</code></pre>
<p>...and its output:</p>
<pre><code>/****************************
My name is Doe, John Doe
My name is Doe, James Doe
My name is Bond, James Bond
My name is James, Bond James
****************************/
</code></pre>
<p>Here is <code>NamedArgs.hpp</code>:</p>
<pre><code>#pragma once
///////////////////
// User's macros //
///////////////////
// Declaration of Named Args
#define NamedArg(Name, ShortName, DefaultTypeValue) \
struct Name: NamedArgs::BaseType<decltype(DefaultTypeValue)> { \
Name(decltype(DefaultTypeValue) d = DefaultTypeValue): \
BaseType{std::move(d)} {} \
}; \
static const NamedArgs::Builder<Name> ShortName;
// Instantiate the wrapper for free and lambda functions
#define NamedArgsFunc(FunctionName, WrapperName) \
static const NamedArgs::FuncWrapper<FunctionName> WrapperName;
// Instantiate the wrapper for member functions -- use inside a class
// Example: NamedArgsMemeberFunc( &ClassName::MemberFunc, operator() )
#define NamedArgsMemberFunc(FunctionName, WrapperName) \
template <typename... Args> \
auto WrapperName(Args&& ... args) { \
return NamedArgs::FuncWrapper<FunctionName>{} \
(this, std::forward<Args>(args)...); \
}
////////////////////
// Implementation //
////////////////////
#include <tuple>
#include <type_traits>
namespace NamedArgs {
// check if T1 is the same of one of the T2...
template <typename T1, typename... T2>
constexpr bool check_for_type() {
return std::disjunction_v<std::is_same<std::decay_t<T1>, std::decay_t<T2>>...>;
}
// given a function construct a tuple with its list of arguments
template <typename R, typename... Args>
auto function_args(R (*)(Args...)) {
return std::tuple<Args...>();
}
// given a member function construct a tuple with its list of arguments
template <typename T, typename R, typename... Args>
auto function_args(R (T::*)(Args...)) {
return std::tuple<Args...>();
}
// given a const member function construct a tuple with its list of arguments
template <typename T, typename R, typename... Args>
auto function_args(R (T::*)(Args...) const) {
return std::tuple<Args...>();
}
// given a lambda function construct a tuple with its list of arguments
template <typename Lambda>
auto function_args(const Lambda &) {
return function_args(&Lambda::operator());
}
// Helper enabling syntax InterfaceName=value directly in the function call
template <typename T>
struct Builder {
T operator=(typename T::value_type&& value) const { return T{value}; }
Builder() = default;
Builder(Builder const&) = delete;
Builder(Builder&&) = delete;
Builder& operator=(Builder const&) = delete;
Builder& operator=(Builder&&) = delete;
};
// Base class for NamedArgs
template <typename T>
struct BaseType {
using value_type = T;
value_type value;
BaseType() = delete;
BaseType(BaseType const&) = default;
BaseType(BaseType&&) = default;
BaseType& operator=(BaseType const&) = default;
BaseType& operator=(BaseType&&) = default;
BaseType(value_type v): value{std::move(v)} {}
BaseType& operator=(value_type v) { value = std::move(v); return *this;}
operator value_type&() {return value;}
operator const value_type&() const {return value;}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const BaseType<T>& t) {
os << t.value;
return os;
}
template <auto func>
struct FuncWrapper {
template <typename... Args>
auto operator()(Args&& ... args) const {
auto passed_args = std::tie( args... );
auto needed_args = function_args(func);
auto copy_if_passed = [&passed_args]( auto & a ) {
if constexpr ( NamedArgs::check_for_type<decltype(a), Args...>() ) {
a = std::get<decltype(a)>(passed_args);
}
};
std::apply( [&](auto && ... needed_arg) {
(( copy_if_passed(needed_arg) ), ...);
}, needed_args);
if constexpr( std::is_member_function_pointer_v<decltype(func)> ) {
auto ClassPTR = std::get<0>(passed_args);
auto bind = [ClassPTR](auto &&... args) {
return (ClassPTR->*func)(std::forward<decltype(args)>(args)...);
};
return std::apply(bind, needed_args);
} else {
return std::apply(func, needed_args);
}
}
};
} //namespace NamedArgs
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T11:01:13.487",
"Id": "243657",
"Score": "3",
"Tags": [
"c++",
"c++17"
],
"Title": "Generic named functions arguments in C++17"
}
|
243657
|
<p>I want to count number of requests per second, minute. I want do it fast and thread-safe. I have 2 variables to count:</p>
<pre><code>private AtomicInteger count;
private AtomicInteger minutesCount;
</code></pre>
<p>And 2 variables for last second and minute:</p>
<pre><code>private AtomicInteger currentSecond;
private AtomicInteger currentMinute;
</code></pre>
<p>Constructor of my service:</p>
<pre><code>public StatisticServiceImpl() {
final Calendar calendar = Calendar.getInstance();
this.currentSecond = new AtomicInteger(calendar.get(Calendar.SECOND));
this.currentMinute = new AtomicInteger(calendar.get(Calendar.MINUTE));
this.count = new AtomicInteger();
this.minutesCount = new AtomicInteger();
}
</code></pre>
<p>And my method to count:</p>
<pre><code>public void count() {
final Calendar calendar = Calendar.getInstance();
int newSecond = calendar.get(Calendar.SECOND);
int newMinute = calendar.get(Calendar.MINUTE);
currentSecond.getAndUpdate(prev -> {
//if it is new second, then clear second count and set new current second
if (newSecond != prev) {
count = new AtomicInteger();
return newSecond;
} else {
count.incrementAndGet();
return prev;
}
});
currentMinute.getAndUpdate(prev -> {
//if it is new minute, then clear minute count and set new current minute
if (newMinute != prev) {
minutesCount = new AtomicInteger();
return newMinute;
} else {
minutesCount.incrementAndGet();
return prev;
}
});
}
</code></pre>
<p>So, is it better (in a sense of performance and accuracy) then solution from <a href="https://stackoverflow.com/questions/17562089/how-to-count-number-of-requests-in-last-second-minute-and-hour">this post?
(use LinkedList)</a></p>
<p>Or suggest better solution for this, please.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T04:25:56.687",
"Id": "478325",
"Score": "1",
"body": "your link is missing (*this post*) ...and what does better *better* mean? are you concering... readability? performance? threadsafty?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T07:01:28.630",
"Id": "478337",
"Score": "1",
"body": "@MartinFrank updated post - add link. Better for performance and accuracy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T07:08:43.583",
"Id": "478339",
"Score": "0",
"body": "Thanks and +1 for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:03:51.297",
"Id": "478367",
"Score": "0",
"body": "I'm not sure about the cost of `Calendar.getInstance()`. You should benchmark it against `System.currentTimeMillies()` and `System.nanoTime()` which you could set once an call each `count()` and calculate the offsets"
}
] |
[
{
"body": "<h1>The first thing I noticed.</h1>\n<p>The calendar in the constructor. If you wanted to test this class it would be really difficult because you\nare dependent on the Calendar implementation, and you have no control over the value it will return. It would be better to inject the calendar in to the\nconstructor, or Abstract the desired functionality in to an interface and inject that. This will also allow you to use one instance for your entire application.\ninstead of constructing a separate one in the <code>count</code> method.</p>\n<p>injecting the calendar:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public StatisticService(final Calendar calendar) {\n this.calender = calendar;\n this.currentSecond = new AtomicInteger(calendar.get(Calendar.SECOND));\n this.currentMinute = new AtomicInteger(calendar.get(Calendar.MINUTE));\n this.count = new AtomicInteger();\n this.minutesCount = new AtomicInteger();\n }\n</code></pre>\n<p>Creating an interface:\nUsing an interface gives you flexibility around the implementation of the counter. If in the future you want to change from using\na <code>Calendar</code> to something else only the code implementing the interface will change and classes dependent on it will be unchanged.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface TimeProviderService {\n Integer getSecond();\n\n Integer getMinute();\n}\n</code></pre>\n<h1>Second</h1>\n<p>It is a lot more expensive to create a new <code>AtomicInteger</code> class then to just set it to zero.\nSo here instead of constructing a new class just reset the integer.</p>\n<pre class=\"lang-java prettyprint-override\"><code>//if it is new second, then clear second count and set new current second\n if (newSecond != prev) {\n count.set(0);\n return newSecond;\n } else {\n count.incrementAndGet();\n return prev;\n }\n</code></pre>\n<h1>Third suggestions for locking.</h1>\n<p>Atomic classes are great but in this instance since you are wanting the entire count method to\nbe atomic I would suggest using your own lock. It simplifies the code for people trying to read it later and the entire\nmethod would be synchronized instead of just when you're accessing the atomic integers.</p>\n<p>Also, locking inside of a lock is asking for a deadlock. See Here.</p>\n<pre class=\"lang-java prettyprint-override\"><code>currentMinute.getAndUpdate(prev -> {\n ...\n minutesCount.incrementAndGet();\n ...\n });\n\n</code></pre>\n<h1>Finally</h1>\n<p>Here is what the class would look like if you implemented the suggestions I am proposing.</p>\n<p><strong>Time Providers</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface TimeProviderService {\n Integer getSecond();\n\n Integer getMinute();\n}\n\npublic class CalendarTimeProviderService implements TimeProviderService {\n private final Calendar calendar;\n\n public CalendarTimeProviderService(Calendar calendar) {\n this.calendar = calendar;\n }\n\n @Override\n public Integer getSecond() {\n return this.calendar.get(Calendar.SECOND);\n }\n\n @Override\n public Integer getMinute() {\n return this.calendar.get(Calendar.MINUTE);\n }\n}\n</code></pre>\n<p><strong>Statistic Service</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class StatisticService {\n private final TimeProviderService timeProviderService;\n private final Lock lock = new ReentrantLock();\n private int currentSecond;\n private int currentMinute;\n private int count;\n private int minutesCount;\n\n\n public StatisticService(TimeProviderService timeProviderService) {\n this.timeProviderService = timeProviderService;\n\n this.currentSecond = this.timeProviderService.getSecond();\n this.currentMinute = this.timeProviderService.getMinute();\n\n this.count = 0;\n this.minutesCount = 0;\n }\n\n\n public void count() {\n this.lock.lock();\n\n try {\n int newSecond = this.timeProviderService.getSecond();\n int newMinute = this.timeProviderService.getMinute();\n\n\n // seconds\n if (newSecond != currentSecond) {\n this.count = 0;\n this.currentSecond = newSecond;\n } else {\n this.count = this.count + 1;\n }\n\n // minutes\n if (newMinute != currentMinute) {\n this.minutesCount = 0;\n this.currentMinute = newMinute;\n } else {\n this.minutesCount = this.minutesCount + 1;\n }\n\n\n } finally {\n // make sure we are unlocking no matter what happens\n this.lock.unlock();\n }\n }\n}\n</code></pre>\n<h2>one final note</h2>\n<p>I did not change anything about how you were calculating the time I just changed the way you are doing it. I do not the problem you\nare trying to solve, so I cannot speak on the best way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:17:33.183",
"Id": "478766",
"Score": "0",
"body": "Thanks for your answer. The problem I want to solve is counting the number of requests with the least loss of quantity and with the best performance.\nUnfortunately, when creating a calendar, it is created once and each time you need to call `Calendar.getInstance()` again to get new values from `calendar.get(Calendar.SECOND);`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:58:19.377",
"Id": "243870",
"ParentId": "243658",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T11:41:00.027",
"Id": "243658",
"Score": "5",
"Tags": [
"java",
"multithreading",
"thread-safety",
"atomic"
],
"Title": "Count of request per second, minute in java"
}
|
243658
|
<p>I was working on a react hooks project.</p>
<p>I was making a form</p>
<p>In the form, I noticed myself writing a very wet code</p>
<p>Here is my code</p>
<pre><code>const FormInvite = (props) => {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [country, setCountry] = useState("")
const [email, setEmai] = useState("")
const changeSelectedCountry = (event) => {
setCountry(event.target.value)
}
const changeFirstName = (event) => {
setFirstName(event.target.value)
}
const changeLastName = (event) => {
setLastName(event.target.value)
}
const changeEmail = (event) => {
setEmail(event.target.value)
}
</code></pre>
<p>Can someone help me/give recommendation so that I don't write those one liner, kind of representative code?</p>
|
[] |
[
{
"body": "<p>Given your form fields use appropriate names (i.e. field names match state properties), and you don't mind using a single state object you can create a single change handler that merges in each field update (similar to how a class-based component's <code>this.setState</code> would handle it) using the field name as the key.</p>\n<pre><code>const FormInvite = (props) => {\n const [state, setState] = useState({\n firstName: '',\n lastName: '',\n country: '',\n email: '',\n });\n\n const changeHandler = e => {\n const { name, value} = e.target;\n setState(state => ({ ...state, [name]: value }));\n }\n ...\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const rootElement = document.getElementById(\"root\");\n\nconst FormInvite = props => {\n const [state, setState] = React.useState({\n firstName: \"\",\n lastName: \"\",\n country: \"\",\n email: \"\"\n });\n\n const changeHandler = e => {\n const { name, value } = e.target;\n setState(state => ({ ...state, [name]: value }));\n };\n\n React.useEffect(() => {\n console.log('firstname changed', state.firstName);\n }, [state.firstName]);\n React.useEffect(() => {\n console.log('lastname changed', state.lastName);\n }, [state.lastName]);\n React.useEffect(() => {\n console.log('country changed', state.country);\n }, [state.country]);\n React.useEffect(() => {\n console.log('email changed', state.email);\n }, [state.email]);\n\n return (\n <form>\n <label>\n First\n <input\n type=\"text\"\n value={state.firstName}\n name=\"firstName\"\n onChange={changeHandler}\n />\n </label>\n <label>\n Last\n <input\n type=\"text\"\n value={state.lastName}\n name=\"lastName\"\n onChange={changeHandler}\n />\n </label>\n <label>\n Country\n <input\n type=\"text\"\n value={state.country}\n name=\"country\"\n onChange={changeHandler}\n />\n </label>\n <label>\n email\n <input\n type=\"email\"\n value={state.email}\n name=\"email\"\n onChange={changeHandler}\n />\n </label>\n </form>\n );\n};\n\nReactDOM.render(\n <React.StrictMode>\n <FormInvite />\n </React.StrictMode>,\n rootElement\n);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input {\n width: 3rem;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js\"></script>\n\n<body>\n <div id=\"root\"></div>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><em>NOTE: This uses a functional state update to ensure/preserve previous state values that aren't currently being updated.</em></p>\n<p>Alternatively you can create a mapping of state => setState function and use a similar change handler as before, this time though you won't need to merge in updates manually.</p>\n<pre><code>const FormInvite = props => {\n const [firstName, setFirstName] = React.useState("");\n const [lastName, setLastName] = React.useState("");\n const [country, setCountry] = React.useState("");\n const [email, setEmail] = React.useState("");\n\n const fieldSetStateMap = {\n firstName: setFirstName,\n lastName: setLastName,\n country: setCountry,\n email: setEmail\n };\n\n const changeHandler = e => {\n const { name, value } = e.target;\n fieldSetStateMap[name](value);\n };\n ...\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const rootElement = document.getElementById(\"root\");\n\nconst FormInvite = props => {\n const [firstName, setFirstName] = React.useState(\"\");\n const [lastName, setLastName] = React.useState(\"\");\n const [country, setCountry] = React.useState(\"\");\n const [email, setEmail] = React.useState(\"\");\n\n const fieldSetStateMap = {\n firstName: setFirstName,\n lastName: setLastName,\n country: setCountry,\n email: setEmail\n };\n\n const changeHandler = e => {\n const { name, value } = e.target;\n fieldSetStateMap[name](value);\n };\n\n React.useEffect(() => {\n console.log(\"firstname changed\", firstName);\n }, [firstName]);\n React.useEffect(() => {\n console.log(\"lastname changed\", lastName);\n }, [lastName]);\n React.useEffect(() => {\n console.log(\"country changed\", country);\n }, [country]);\n React.useEffect(() => {\n console.log(\"email changed\", email);\n }, [email]);\n\n return (\n <form>\n <label>\n First\n <input\n type=\"text\"\n value={firstName}\n name=\"firstName\"\n onChange={changeHandler}\n />\n </label>\n <label>\n Last\n <input\n type=\"text\"\n value={lastName}\n name=\"lastName\"\n onChange={changeHandler}\n />\n </label>\n <label>\n Country\n <input\n type=\"text\"\n value={country}\n name=\"country\"\n onChange={changeHandler}\n />\n </label>\n <label>\n email\n <input\n type=\"email\"\n value={email}\n name=\"email\"\n onChange={changeHandler}\n />\n </label>\n </form>\n );\n};\n\nReactDOM.render(\n <React.StrictMode>\n <FormInvite />\n </React.StrictMode>,\n rootElement\n);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input {\n width: 3rem;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js\"></script>\n\n<body>\n <div id=\"root\"></div>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><em>NOTE: This can use a plain state update as each "piece of state" is fully independent of other state and the value is replaced each <code>onChange</code>.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T04:51:37.397",
"Id": "243702",
"ParentId": "243667",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:18:09.347",
"Id": "243667",
"Score": "4",
"Tags": [
"react.js",
"jsx"
],
"Title": "React avoid code repetation"
}
|
243667
|
<p>The <code>Article</code> model supports a bunch of transitions. Only two are shown below: <code>star()</code>/<code>unstar()</code>.</p>
<p>Is this a valid implementation of the state pattern?</p>
<pre><code>interface ArticleState {
star(): ArticleState;
unstar(): ArticleState;
// other transitions ...
}
export class InitialArticleState implements ArticleState {
star = () => new StarredArticleState();
unstar = () => this;
// other transitions ...
}
export class StarredArticleState implements ArticleState {
star = () => this;
unstar = () => new InitialArticleState();
// other transitions ...
}
export class Article {
state: ArticleState = new InitialArticleState();
star() { this.state = this.state.star(); }
unstar() { this.state = this.state.unstar(); }
}
</code></pre>
<p>The <code>Article</code> state operations are wrapped by the service which updates the feed:</p>
<pre><code>@Injectable()
export class ArticlesFeedService {
private feed$: Subject<Article[]> = new BehaviorSubject<Article[]>([]);
private store: Article[] = [];
private publishChanges() {
this.feed$.next(this.store);
}
starArticle(article: Article): void {
article.star();
// update the store then publish changes...
}
}
</code></pre>
<p>There's a component subscribed to get <strong>starred</strong> articles:</p>
<pre><code>getStarredArticles(): Observable<Article[]> {
return this.getArticles().pipe(
map((articles: Article[]) =>
articles.filter((article: Article) =>
article.state instanceof StarredArticleState
)
)
);
}
</code></pre>
<p>My motivation behind using the state pattern is that it helps reduce branching (decision making) in the feed service methods (e.g. <strong>starred</strong> article can't be <strong>blacklisted</strong>, only <strong>unstarred</strong> / <strong>initial</strong>).</p>
<ol>
<li>Is it okay to use state as public property of the <code>Article</code>? I thought about marking the article's state property as private and introducing a readonly string tag to each state (to <code>ArticleState</code> interface), so I could subscribe/filter using the tag. But it's a string and I'm tottally not sure if it's better.</li>
<li>How can I improve the design?</li>
<li>Are there any TypeScript features that could be used instead?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T17:47:00.033",
"Id": "478298",
"Score": "1",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/243670/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T07:39:20.843",
"Id": "478340",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ thanks! Well, I tried to be more descriptive, updated the title."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T14:52:30.467",
"Id": "243670",
"Score": "2",
"Tags": [
"design-patterns",
"angular-2+",
"state",
"rxjs"
],
"Title": "Switching article states using state pattern"
}
|
243670
|
<p>So, I created a class to avoid all the work behind the validation of input in a textbox.</p>
<p>The idea is to pass an existing textbox and a type of the desired content and the class will take care of block unacceptable input (for example letters in a numeric textbox), validate the text while the user writes and display a message if the content is invalid.</p>
<p>Exposed Methods</p>
<ul>
<li>Create: associates the existing textbox to the class, set the content type, and set appearance properties</li>
<li>Validate: checks validity of content and display the message</li>
</ul>
<p>Exposed properties</p>
<ul>
<li>TextBoxType: Let|Get custom - content type</li>
<li>MaxValue: Let|Get double - only valid for numeric types</li>
<li>MinValue: Let|Get double - only valid for numeric types</li>
<li>FixedFormat: Let|Get boolean - only valid for numeric types, maintain the format of the number while typing</li>
<li>ToCase: Let|Get custom - only valid for non-numeric types, change the case of the string while typing</li>
<li>InvalidValueMessage: Let|Get string - message showed by the Validate function if the content is not vald</li>
<li>IsValid: Get boolean - content validity by the type expected</li>
<li>ShowValidityThrough: Let|Get custom - IsValid property can colour the textbox to indicate to the user if the content is valid or not. You can choose to colour backcolor, forecolor or bordercolor</li>
<li>ValidColor: Let|Get long - the color of the ShowValidityThrough property if the content is valid</li>
<li>InvalidColor: Let|Get long - the colour of the ShowValidityThrough property if the content is not valid</li>
</ul>
<p>I would like to have some advice if you can on the design and on the possible errors you can see.
Also advises on other possible types are very welcome!
Thank you!</p>
<p>Class Name AdvTextBox</p>
<pre><code>Option Explicit
Private WithEvents txt As MSForms.TextBox
' properties storage
Private pTextBoxType As TextBoxTypes
Private pMaxValue As Double
Private pMinValue As Double
Private pFixedFormat As Boolean
Private pToCase As DesiredCase
Private pInvalidValueMessage As String
Private pIsValid As Boolean
Private pShowValidityThrough As ValidityProperty
Private pValidColor As Long
Private pInvalidColor As Long
' calculated
Private pAllowedCharacters As String
Private pEvaluateMinMax As Boolean
Private pAllowEvents As Boolean
Private pOutputFormat As String
Private pEnlarged As Boolean
Private DecimalSeparator As String
' constants
Private Const numbers As String = "0123456789"
Private Const letters As String = "abcdefghijklmnopqrstuvwxyz"
Private Const accented As String = "èéàòì"
Private Const numberPunctuation As String = ",."
Private Const otherPunctuation As String = " !?=_/|-@€+"
Private Const defaultInvalidColor As Long = &H5F5BDD
Public Enum TextBoxTypes
ShortText = 0
Notes = 1
Iban = 10
ItalianVatNumber = 11
Email = 12
WholeNumber = 20
Decimal1Digit = 21
Decimal2Digit = 22
Decimal3Digit = 23
Decimal4Digit = 24
Decimal5Digit = 25
Decimal6Digit = 26
End Enum
Public Enum DesiredCase
Normal = 0
UpperCase = 1
LowerCase = 2
ProperCase = 3
End Enum
Public Enum ValidityProperty
NoOne = 0
vBorders = 1
vBackColor = 2
vForeColor = 3
End Enum
' class
Private Sub Class_Initialize()
DecimalSeparator = Application.DecimalSeparator
pAllowEvents = True
pFixedFormat = True
pShowValidityThrough = NoOne
pToCase = Normal
pValidColor = -1
pInvalidColor = -1
End Sub
' let properties
Public Property Let InvalidValueMessage(value As String)
pInvalidValueMessage = value
End Property
Public Property Let ShowValidityThrough(value As ValidityProperty)
pShowValidityThrough = value
ColorTextBox pIsValid
End Property
Public Property Let ValidColor(value As Long)
pValidColor = value
ColorTextBox pIsValid
End Property
Public Property Let InvalidColor(value As Long)
pInvalidColor = value
ColorTextBox pIsValid
End Property
Public Property Let ToCase(value As DesiredCase)
pToCase = value
End Property
Public Property Let FixedFormat(value As Boolean)
pFixedFormat = value
Select Case pTextBoxType
Case WholeNumber
pOutputFormat = "#,##0"
pAllowedCharacters = numbers
Case Decimal1Digit
pOutputFormat = "#,##0.0"
pAllowedCharacters = numbers & IIf(value, vbNullString, numberPunctuation)
Case Decimal2Digit
pOutputFormat = "#,##0.00"
pAllowedCharacters = numbers & IIf(value, vbNullString, numberPunctuation)
Case Decimal3Digit
pOutputFormat = "#,##0.000"
pAllowedCharacters = numbers & IIf(value, vbNullString, numberPunctuation)
Case Decimal4Digit
pOutputFormat = "#,##0.0000"
pAllowedCharacters = numbers & IIf(value, vbNullString, numberPunctuation)
Case Decimal5Digit
pOutputFormat = "#,##0.00000"
pAllowedCharacters = numbers & IIf(value, vbNullString, numberPunctuation)
Case Decimal6Digit
pOutputFormat = "#,##0.000000"
pAllowedCharacters = numbers & IIf(value, vbNullString, numberPunctuation)
End Select
End Property
Private Property Let IsValid(value As Boolean)
pIsValid = value
ColorTextBox value
End Property
Public Property Let MinValue(value As Double)
pEvaluateMinMax = True
pMinValue = value
End Property
Public Property Let MaxValue(value As Double)
pEvaluateMinMax = True
pMaxValue = value
End Property
Private Property Let TextBoxType(value As TextBoxTypes)
Dim text As String
Dim maxLength As Long
pTextBoxType = value
Select Case value
Case ShortText
maxLength = 40
pAllowedCharacters = numbers & letters & numberPunctuation & otherPunctuation
Case Notes
txt.EnterKeyBehavior = True
txt.MultiLine = True
pAllowedCharacters = numbers & letters & numberPunctuation & otherPunctuation & accented & Chr(10) & Chr(13)
Case Iban
maxLength = 31
pAllowedCharacters = numbers & letters
Case ItalianVatNumber
maxLength = 11
pAllowedCharacters = numbers
Case Email
pAllowedCharacters = numbers & letters & numberPunctuation & otherPunctuation
Case WholeNumber
text = 0
pOutputFormat = "#,##0"
pAllowedCharacters = numbers
txt.ControlTipText = "Press ""-"" to change the sign"
Case Decimal1Digit
text = 0
pOutputFormat = "#,##0.0"
pAllowedCharacters = numbers & IIf(pFixedFormat, vbNullString, numberPunctuation)
txt.ControlTipText = "Press ""-"" to change the sign"
Case Decimal2Digit
text = 0
pOutputFormat = "#,##0.00"
pAllowedCharacters = numbers & IIf(pFixedFormat, vbNullString, numberPunctuation)
txt.ControlTipText = "Press ""-"" to change the sign"
Case Decimal3Digit
text = 0
pOutputFormat = "#,##0.000"
pAllowedCharacters = numbers & IIf(pFixedFormat, vbNullString, numberPunctuation)
txt.ControlTipText = "Press ""-"" to change the sign"
Case Decimal4Digit
text = 0
pOutputFormat = "#,##0.0000"
pAllowedCharacters = numbers & IIf(pFixedFormat, vbNullString, numberPunctuation)
txt.ControlTipText = "Press ""-"" to change the sign"
Case Decimal5Digit
text = 0
pOutputFormat = "#,##0.00000"
pAllowedCharacters = numbers & IIf(pFixedFormat, vbNullString, numberPunctuation)
txt.ControlTipText = "Press ""-"" to change the sign"
Case Decimal6Digit
text = 0
pOutputFormat = "#,##0.000000"
pAllowedCharacters = numbers & IIf(pFixedFormat, vbNullString, numberPunctuation)
txt.ControlTipText = "Press ""-"" to change the sign"
End Select
If maxLength > 0 Then txt.maxLength = maxLength
txt.text = text
End Property
' get properties
Public Property Get InvalidValueMessage() As String
InvalidValueMessage = pInvalidValueMessage
End Property
Public Property Get ShowValidityThrough() As ValidityProperty
ShowValidityThrough = pShowValidityThrough
End Property
Public Property Get ToCase() As DesiredCase
ToCase = pToCase
End Property
Public Property Get FixedFormat() As Boolean
FixedFormat = pFixedFormat
End Property
Public Property Get MaxValue() As Double
MaxValue = pMaxValue
End Property
Public Property Get MinValue() As Double
MinValue = pMinValue
End Property
Public Property Get IsValid() As Boolean
ColorTextBox pIsValid
IsValid = pIsValid
End Property
Public Property Get ValidColor() As Long
ValidColor = pValidColor
End Property
Public Property Get InvalidColor() As Long
InvalidColor = pInvalidColor
End Property
Private Property Get TextBoxType() As TextBoxTypes
TextBoxType = pTextBoxType
End Property
' exposed methods and functions
Public Function Create(ByVal obj As MSForms.TextBox, _
ByVal txtType As TextBoxTypes) As AdvTextBox
If pValidColor = -1 Then
Select Case pShowValidityThrough
Case NoOne, vBackColor
pValidColor = obj.BackColor
Case vBorders
pValidColor = obj.BorderColor
Case vForeColor
pValidColor = obj.ForeColor
End Select
End If
If pInvalidColor = -1 Then
pInvalidColor = defaultInvalidColor
End If
Set txt = obj
TextBoxType = txtType
Set Create = Me
End Function
Public Function Validate() As Boolean
ColorTextBox pIsValid
If (Not pIsValid) And (Not pInvalidValueMessage = vbNullString) Then MsgBox pInvalidValueMessage, vbInformation, "Invalid value"
Validate = pIsValid
End Function
' textbox events
Private Sub txt_Change()
If Not pAllowEvents Then Exit Sub
pAllowEvents = False
Dim valore As Variant
valore = txt.text
Select Case pTextBoxType
Case ShortText
If Not pToCase = Normal Then valore = StrConv(valore, pToCase)
Case Notes
If Not pToCase = Normal Then valore = StrConv(valore, pToCase)
Case Iban
IsValid = isValidIBAN(valore)
valore = UCase(valore)
Case ItalianVatNumber
IsValid = IsValidItalianVatNumber(valore)
Case Email
IsValid = IsValidEmail(valore)
valore = LCase(valore)
Case Else
Dim selectText As Boolean
If pFixedFormat Then
valore = Replace(Replace(valore, ",", vbNullString), ".", vbNullString)
If valore = vbNullString Then valore = 0
valore = CDbl(valore)
Select Case pTextBoxType
Case Decimal1Digit
valore = valore / 10
Case Decimal2Digit
valore = valore / 100
Case Decimal3Digit
valore = valore / 1000
Case Decimal4Digit
valore = valore / 10000
Case Decimal5Digit
valore = valore / 100000
Case Decimal6Digit
valore = valore / 1000000
End Select
Else
valore = Replace(valore, IIf(DecimalSeparator = ",", ".", ","), IIf(DecimalSeparator = ",", ",", "."))
If Not IsNumeric(valore) Then
valore = 0
selectText = True
End If
End If
If pEvaluateMinMax Then
IsValid = (Not valore < pMinValue) And (Not valore > pMaxValue)
End If
If pFixedFormat Then valore = Format(valore, pOutputFormat)
End Select
txt.text = valore
If selectText Then
txt.SelStart = 0
txt.SelLength = Len(CStr(valore))
End If
pAllowEvents = True
End Sub
Private Sub txt_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii = 45 Then
Select Case pTextBoxType
Case WholeNumber, Decimal1Digit, Decimal2Digit, Decimal3Digit, Decimal4Digit, Decimal5Digit, Decimal6Digit
txt.text = CDbl(txt.text) * -1
End Select
End If
If Not KeyAscii = 8 Then
If InStr(1, pAllowedCharacters, Chr(KeyAscii), vbTextCompare) = 0 Then KeyAscii = 0
End If
End Sub
' validation routines
Private Sub ColorTextBox(validity As Boolean)
If (Not pShowValidityThrough = NoOne) And (Not txt Is Nothing) Then
Select Case pShowValidityThrough
Case vBackColor
txt.BackColor = IIf(validity, pValidColor, pInvalidColor)
Case vBorders
txt.BorderStyle = fmBorderStyleSingle
txt.BorderColor = IIf(validity, pValidColor, pInvalidColor)
txt.Width = txt.Width + IIf(pEnlarged, -0.1, 0.1)
pEnlarged = Not pEnlarged
Case vForeColor
txt.ForeColor = IIf(validity, pValidColor, pInvalidColor)
End Select
End If
End Sub
Private Function IsValidItalianVatNumber(ByVal str As String) As Boolean
IsValidItalianVatNumber = False
If Not IsNumeric(str) Then Exit Function
If Not Len(str) = 11 Then Exit Function
Dim X As Long
Dim Y As Long
Dim z As Long
Dim t As Long
Dim i As Long
Dim c As Long
Dim ch As Variant
Dim pari As Boolean
pari = True
For i = 1 To Len(str) - 1
pari = Not pari
ch = CLng(Mid(str, i, 1))
If pari Then
Y = Y + (ch * 2)
If ch > 4 Then z = z + 1
Else
X = X + ch
End If
Next i
t = (X + Y + z) Mod 10
c = (10 - t) Mod 10
IsValidItalianVatNumber = (c = CLng(Right(str, 1)))
End Function
Private Function isValidIBAN(ByVal Iban As String) As Boolean
' Written by Davide Tonin
' Documentation at https://davidetonin.com/code-snippets/how-to-validate-an-iban-with-vba
isValidIBAN = False
Dim LengthByCountry As Long
Dim ReorderedIBAN As String
Dim NumericIBAN As String
Dim ch As String
Dim i As Long
Const Div As Integer = 97
Const SepaCountries As String = "AT20,BE16,BG22,CY28,HR21,DK18,EE20,FI18,FR27,DE22,GI23,GR27,GL18,IE22,IS26,FO18,IT27,LV21,LI21,LT20,LU20,MT31,MC27,NO15,NL18,PL28,PT25,GB22,CZ24,SK24,RO24,SM27,SI19,ES24,SE24,CH21,HU28"
If Iban = vbNullString Then Exit Function
'Check if the first 2 characters are letters
If IsNumeric(Left(Iban, 1)) Or IsNumeric(Mid(Iban, 2, 1)) Then Exit Function
'Get the expected legth by country
LengthByCountry = InStr(1, SepaCountries, Left(Iban, 2), vbTextCompare)
If LengthByCountry > 0 Then LengthByCountry = CInt(Mid(SepaCountries, LengthByCountry + 2, 2))
If Len(Iban) <> LengthByCountry Then Exit Function
'Move first 4 characters to right
ReorderedIBAN = Right(Iban, Len(Iban) - 4) & Left(Iban, 4)
'Loop through every single character in ReorderedIBAN and, if not numeric, return 10 based number from letter using string to store the returned value in place of number
For i = 1 To Len(ReorderedIBAN)
ch = Mid(ReorderedIBAN, i, 1)
If Not IsNumeric(ch) Then
NumericIBAN = NumericIBAN & CStr(Asc(UCase(ch)) - 55)
Else
NumericIBAN = NumericIBAN & CStr(ch)
End If
Next i
ch = vbNullString
'Perform primary school style division, digit by digit. I don't need to store the result, only the remainder
For i = 1 To Len(NumericIBAN)
ch = ch & Mid(NumericIBAN, i, 1)
'If is the last character in NumericIBAN I check if remainder is 1 - Only fired once
If i = Len(NumericIBAN) Then
isValidIBAN = ((CLng(ch) Mod Div) = 1)
Exit Function
End If
ch = IIf(CLng(ch) < Div, ch, CLng(ch) Mod Div)
Next i
End Function
Private Function IsValidEmail(ByVal emailAddress As String) As Boolean
IsValidEmail = False
Const emailPattern As String = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"
With CreateObject("VBScript.RegExp")
.Global = True
.IgnoreCase = True
.Pattern = emailPattern
IsValidEmail = .Test(emailAddress)
End With
End Function
</code></pre>
|
[] |
[
{
"body": "<p>The art of Oop is that you have objects which have a simple, clear and unambiguous roles which can be composed together to achieve the result you want. You don't use objects as a convenient place to hide a pile of disconnected activities.</p>\n<p>In the code you provide you have two main issues, collecting a text value and displaying the current validation status, and validating the incoming text value. Let's assume you are validating character by character.</p>\n<p>I would have one object (a text gatherer) whose task it is to collect the text input. At initialisation, the text gatherer object would be provided with a validator object.</p>\n<p>The text gatherer object provides each character to its validator object. The validator object has two functions.</p>\n<ol>\n<li><p>It indicates if the new character is accepted/not accepted according to the validation criteria.</p>\n</li>\n<li><p>Triggers a input completed event once an input that matches the desired input has been achieved.</p>\n</li>\n</ol>\n<p>The Validator objects would be written so as to work through an IValidator interface to facilitate intellisense and compiler checking..</p>\n<p>For VBA, if there are enumerations and constants that are used across multiple objects I would put these in the relevant interface, or a seperate helper class/module if there are also Methods used by all validator objects.</p>\n<p>For the text gatherer object I might also want to split this into an object that just gets text and a second object that displays the current validation status.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T11:34:01.377",
"Id": "478350",
"Score": "0",
"body": "Thank you very much! I'm quite new at OOP and this is the kind of suggestions that help to improve.\nAt the moment the abstraction level that I'm confident with is lower than this, but maybe trying:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T13:18:55.780",
"Id": "478355",
"Score": "0",
"body": "Take a look at the blog articles on the Rubberduck VBA addin website (News). They are very helpful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T07:12:22.577",
"Id": "243706",
"ParentId": "243672",
"Score": "2"
}
},
{
"body": "<p>The one class is trying to handle multiple types of textboxes. In this specific case it would seem a better approach to create a class for each textbox type. This keeps code specific to each textbox type very isolated, focused, and much more OO. So, how to get there...</p>\n<p>Below is an example refactoring that creates two of the classes needed: <code>DecimalDigitTextBox</code> and <code>EmailTextBox</code>. A standard module <code>AdvTextBoxFactory</code> is introduced to hold the common enums and constants. As the name implies, the module also acts as a Factory to create the specific of textbox validator class that is needed. And, most importantly, an <code>IAdvTextBox</code> interface is defined so that each textbox class can <em>look</em> the same for client code. Hope you find this useful.</p>\n<p><strong>IAdvTextBox</strong></p>\n<pre><code>Public Function Validate() As Boolean\nEnd Function\n\nPublic Property Get TextBoxType() As TextBoxTypes\nEnd Property\n\nPublic Property Get MaxValue() As Double\nEnd Property\n\nPublic Property Let MaxValue(ByVal value As Double)\nEnd Property\n\nPublic Property Get MinValue() As Double\nEnd Property\n\nPublic Property Let MinValue(ByVal value As Double)\nEnd Property\n\nPublic Property Get FixedFormat() As Boolean\nEnd Property\n\nPublic Property Let FixedFormat(ByVal value As Boolean)\nEnd Property\n\nPublic Property Get ToCase() As DesiredCase\nEnd Property\n\nPublic Property Let ToCase(ByVal value As DesiredCase)\nEnd Property\n\nPublic Property Get InvalidValueMessage() As String\nEnd Property\n\nPublic Property Let InvalidValueMessage(ByVal value As String)\nEnd Property\n\nPublic Property Get IsValid() As Boolean\nEnd Property\n\nPublic Property Let IsValid(ByVal value As Boolean)\nEnd Property\n\nPublic Property Get ShowValidityThrough() As ValidityProperty\nEnd Property\n\nPublic Property Let ShowValidityThrough(ByVal value As ValidityProperty)\nEnd Property\n\nPublic Property Get ValidColor() As Long\nEnd Property\n\nPublic Property Let ValidColor(ByVal value As Long)\nEnd Property\n\nPublic Property Get InvalidColor() As Long\nEnd Property\n\nPublic Property Let InvalidColor(ByVal value As Long)\nEnd Property\n\nPublic Property Get Enlarged() As Boolean\nEnd Property\n\nPublic Property Let Enlarged(ByVal value As Boolean)\nEnd Property\n\nPublic Property Get AllowedCharacters() As String\nEnd Property\n\nPublic Property Let AllowedCharacters(ByVal value As String)\nEnd Property\n</code></pre>\n<p><strong>AdvTextBoxFactory</strong></p>\n<pre><code>Option Explicit\n\nPublic Type TAdvTextBox\n TextBoxType As TextBoxTypes\n MaxValue As Double\n MinValue As Double\n FixedFormat As Boolean\n ToCase As DesiredCase\n InvalidValueMessage As String\n IsValid As Boolean\n ShowValidityThrough As ValidityProperty\n ValidColor As Long\n InvalidColor As Long\n AllowedCharacters As String\n outputFormat As String\n DecimalSeparator As String\n Enlarged As Boolean\nEnd Type\n\nPublic Enum TextBoxTypes\n ShortText = 0\n Notes = 1\n Iban = 10\n ItalianVatNumber = 11\n Email = 12\n WholeNumber = 20\n Decimal1Digit = 21\n Decimal2Digit = 22\n Decimal3Digit = 23\n Decimal4Digit = 24\n Decimal5Digit = 25\n Decimal6Digit = 26\nEnd Enum\n\nPublic Enum DesiredCase\n Normal = 0\n UpperCase = 1\n LowerCase = 2\n ProperCase = 3\nEnd Enum\n\nPublic Enum ValidityProperty\n NoOne = 0\n vBorders = 1\n vBackColor = 2\n vForeColor = 3\nEnd Enum\n\n' constants\nPublic Const numbers As String = "0123456789"\nPublic Const letters As String = "abcdefghijklmnopqrstuvwxyz"\nPublic Const accented As String = "èéàòì"\nPublic Const numberPunctuation As String = ",."\nPublic Const otherPunctuation As String = " !?=_/|-@€+"\nPublic Const defaultInvalidColor As Long = &H5F5BDD\n\nPublic Function Create(ByVal obj As MSForms.TextBox, _\n ByVal txtType As TextBoxTypes) As IAdvTextBox\n \n Dim advTxtBox As IAdvTextBox\n \n Select Case txtType\n Case ShortText\n 'TODO\n Case Notes\n 'TODO\n Case Iban\n 'TODO\n Case ItalianVatNumber\n 'TODO\n Case Email\n Dim emTxtBox As EmailTextBox\n Set emTxtBox = New EmailTextBox\n emTxtBox.ConnectToTextBox obj\n Set advTxtBox = emTxtBox\n Case WholeNumber\n 'TODO\n Case Decimal1Digit, Decimal2Digit, Decimal3Digit, Decimal4Digit, Decimal5Digit, Decimal6Digit\n Dim ddTextBox As DecimalDigitTextBox\n Set ddTextBox = New DecimalDigitTextBox\n ddTextBox.SetupDecimalDigits txtType\n ddTextBox.ConnectToTextBox obj\n Set advTxtBox = ddTextBox\n Case Else\n 'throw an error\n End Select\n \n Select Case advTxtBox.ShowValidityThrough\n Case NoOne, vBackColor\n advTxtBox.ValidColor = obj.BackColor\n Case vBorders\n advTxtBox.ValidColor = obj.BorderColor\n Case vForeColor\n advTxtBox.ValidColor = obj.ForeColor\n End Select\n\n advTxtBox.InvalidColor = defaultInvalidColor\n\n Set Create = advTxtBox\nEnd Function\n</code></pre>\n<p><strong>DecimalDigitTextBox</strong></p>\n<pre><code>Option Explicit\n\nPrivate WithEvents txt As MSForms.TextBox\n\nImplements IAdvTextBox\n\nPrivate this As TAdvTextBox\n\nPrivate pDecimalDigitsDivisor As Long\n\nPrivate pAllowEvents As Boolean\n\nPrivate Sub Class_Initialize()\n pAllowEvents = True\n this.DecimalSeparator = Application.DecimalSeparator\n this.FixedFormat = True\n this.ShowValidityThrough = NoOne\n this.ToCase = Normal\n this.ValidColor = -1\n this.InvalidColor = -1\n \n 'factory updates with correct values in SetupDecimalDigits\n this.TextBoxType = Decimal1Digit\n this.outputFormat = "#,##0.0"\n pDecimalDigitsDivisor = 10\nEnd Sub\n\nPublic Sub ConnectToTextBox(txtBox As MSForms.TextBox)\n Set txt = txtBox\n \n this.AllowedCharacters = numbers & IIf(this.FixedFormat, vbNullString, numberPunctuation)\n txt.ControlTipText = "Press ""-"" to change the sign"\n txt.text = 0\nEnd Sub\n\nPublic Sub SetupDecimalDigits(ByVal txtType As TextBoxTypes)\n this.TextBoxType = txtType\n Select Case txtType\n Case Decimal1Digit\n this.outputFormat = "#,##0.0"\n pDecimalDigitsDivisor = 10\n Case Decimal2Digit\n this.outputFormat = "#,##0.00"\n pDecimalDigitsDivisor = 100\n Case Decimal3Digit\n this.outputFormat = "#,##0.000"\n pDecimalDigitsDivisor = 1000\n Case Decimal4Digit\n this.outputFormat = "#,##0.0000"\n pDecimalDigitsDivisor = 10000\n Case Decimal5Digit\n this.outputFormat = "#,##0.00000"\n pDecimalDigitsDivisor = 100000\n Case Decimal6Digit\n this.outputFormat = "#,##0.000000"\n pDecimalDigitsDivisor = 1000000\n Case Else\n 'throw an error\n End Select\nEnd Sub\n\nPrivate Sub txt_Change()\n \n If Not pAllowEvents Then Exit Sub\n \n pAllowEvents = False\n \n Dim valore As Variant\n valore = Replace(Replace(txt.text, ",", vbNullString), ".", vbNullString)\n \n If valore = vbNullString Then valore = 0\n \n valore = CDbl(valore) / pDecimalDigitsDivisor\n \n txt.text = CStr(valore)\n \n pAllowEvents = True\n \nEnd Sub\n\nPrivate Sub txt_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)\n If KeyAscii = 45 Then\n txt.text = CDbl(txt.text) * -1\n End If\n \n If Not KeyAscii = 8 Then\n If InStr(1, this.AllowedCharacters, Chr(KeyAscii), vbTextCompare) = 0 Then KeyAscii = 0\n End If\nEnd Sub\n\nPrivate Sub ColorTextBox(validity As Boolean)\n If (Not this.ShowValidityThrough = NoOne) And (Not txt Is Nothing) Then\n \n Dim color As Long\n color = IIf(validity, this.ValidColor, this.InvalidColor)\n \n Select Case this.ShowValidityThrough\n Case vBackColor\n txt.BackColor = color\n Case vBorders\n txt.BorderStyle = fmBorderStyleSingle\n txt.BorderColor = color\n txt.Width = txt.Width + IIf(this.Enlarged, -0.1, 0.1)\n this.Enlarged = Not this.Enlarged\n Case vForeColor\n txt.ForeColor = color\n End Select\n End If\nEnd Sub\n\nPrivate Function IAdvTextBox_Validate() As Boolean\n ColorTextBox this.IsValid\n If (Not this.IsValid) And (Not this.InvalidValueMessage = vbNullString) Then MsgBox this.InvalidValueMessage, vbInformation, "Invalid value"\n IAdvTextBox_Validate = this.IsValid\nEnd Function\n\nPrivate Property Get IAdvTextBox_TextBoxType() As TextBoxTypes\n IAdvTextBox_TextBoxType = this.TextBoxType\nEnd Property\n\nPrivate Property Get IAdvTextBox_MaxValue() As Double\n IAdvTextBox_MaxValue = this.MaxValue\nEnd Property\n\nPrivate Property Let IAdvTextBox_MaxValue(ByVal value As Double)\n this.MaxValue = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_MinValue() As Double\n IAdvTextBox_MinValue = this.MinValue\nEnd Property\n\nPrivate Property Let IAdvTextBox_MinValue(ByVal value As Double)\n this.MinValue = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_FixedFormat() As Boolean\n IAdvTextBox_FixedFormat = this.FixedFormat\nEnd Property\n\nPrivate Property Let IAdvTextBox_FixedFormat(ByVal value As Boolean)\n this.FixedFormat = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_ToCase() As DesiredCase\n IAdvTextBox_ToCase = this.ToCase\nEnd Property\n\nPrivate Property Let IAdvTextBox_ToCase(ByVal value As DesiredCase)\n this.ToCase = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_InvalidValueMessage() As String\n IAdvTextBox_InvalidValueMessage = this.InvalidValueMessage\nEnd Property\n\nPrivate Property Let IAdvTextBox_InvalidValueMessage(ByVal value As String)\n this.InvalidValueMessage = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_IsValid() As Boolean\n IAdvTextBox_IsValid = this.IsValid\nEnd Property\n\nPrivate Property Let IAdvTextBox_IsValid(ByVal value As Boolean)\n this.IsValid = value\n ColorTextBox this.IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_ShowValidityThrough() As ValidityProperty\n IAdvTextBox_ShowValidityThrough = this.ShowValidityThrough\nEnd Property\n\nPrivate Property Let IAdvTextBox_ShowValidityThrough(ByVal value As ValidityProperty)\n this.ShowValidityThrough = value\n ColorTextBox IAdvTextBox_IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_ValidColor() As Long\n IAdvTextBox_ValidColor = this.ValidColor\nEnd Property\n\nPrivate Property Let IAdvTextBox_ValidColor(ByVal value As Long)\n this.ValidColor = value\n ColorTextBox IAdvTextBox_IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_InvalidColor() As Long\n IAdvTextBox_InvalidColor = this.InvalidColor\nEnd Property\n\nPrivate Property Let IAdvTextBox_InvalidColor(ByVal value As Long)\n this.InvalidColor = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_Enlarged() As Boolean\n IAdvTextBox_Enlarged = this.Enlarged\nEnd Property\n\nPrivate Property Let IAdvTextBox_Enlarged(ByVal value As Boolean)\n this.Enlarged = value\n ColorTextBox IAdvTextBox_IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_AllowedCharacters() As String\n IAdvTextBox_AllowedCharacters = this.AllowedCharacters\nEnd Property\n\nPrivate Property Let IAdvTextBox_AllowedCharacters(ByVal value As String)\n this.AllowedCharacters = value\nEnd Property\n</code></pre>\n<p><strong>EmailTextBox</strong></p>\n<pre><code>Option Explicit\n\nImplements IAdvTextBox\n\nPrivate WithEvents txt As MSForms.TextBox\n\nPrivate this As TAdvTextBox\nPrivate pAllowEvents As Boolean\n\nPrivate Sub Class_Initialize()\n pAllowEvents = True\n this.DecimalSeparator = Application.DecimalSeparator\n this.FixedFormat = True\n this.ShowValidityThrough = NoOne\n this.ToCase = Normal\n this.ValidColor = -1\n this.InvalidColor = -1\n this.TextBoxType = Email\nEnd Sub\n\nPrivate Function IsValidEmail(ByVal emailAddress As String) As Boolean\n \n IsValidEmail = False\n \n Const emailPattern As String = "^([a-zA-Z0-9_\\-\\.]+)@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$"\n \n With CreateObject("VBScript.RegExp")\n .Global = True\n .IgnoreCase = True\n .Pattern = emailPattern\n IsValidEmail = .Test(emailAddress)\n End With\n \nEnd Function\n\nPublic Sub ConnectToTextBox(txtBox As MSForms.TextBox)\n Set txt = txtBox\nEnd Sub\n\nPrivate Sub txt_Change()\n \n If Not pAllowEvents Then Exit Sub\n \n pAllowEvents = False\n \n Dim valore As Variant\n valore = txt.text\n \n this.IsValid = IsValidEmail(valore)\n \n valore = LCase(valore)\n \n txt.text = valore\n \n pAllowEvents = True\n \nEnd Sub\n\nPrivate Sub txt_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)\n If Not KeyAscii = 8 Then\n If InStr(1, this.AllowedCharacters, Chr(KeyAscii), vbTextCompare) = 0 Then KeyAscii = 0\n End If\nEnd Sub\n\nPrivate Sub ColorTextBox(validity As Boolean)\n If (Not this.ShowValidityThrough = NoOne) And (Not txt Is Nothing) Then\n \n Dim color As Long\n color = IIf(validity, this.ValidColor, this.InvalidColor)\n \n Select Case this.ShowValidityThrough\n Case vBackColor\n txt.BackColor = color\n Case vBorders\n txt.BorderStyle = fmBorderStyleSingle\n txt.BorderColor = color\n txt.Width = txt.Width + IIf(this.Enlarged, -0.1, 0.1)\n this.Enlarged = Not this.Enlarged\n Case vForeColor\n txt.ForeColor = color\n End Select\n End If\nEnd Sub\n\nPrivate Function IAdvTextBox_Validate() As Boolean\n ColorTextBox this.IsValid\n If (Not this.IsValid) And (Not this.InvalidValueMessage = vbNullString) Then MsgBox this.InvalidValueMessage, vbInformation, "Invalid value"\n IAdvTextBox_Validate = this.IsValid\nEnd Function\n\nPrivate Property Get IAdvTextBox_TextBoxType() As TextBoxTypes\n IAdvTextBox_TextBoxType = this.TextBoxType\nEnd Property\n\nPrivate Property Get IAdvTextBox_MaxValue() As Double\n IAdvTextBox_MaxValue = this.MaxValue\nEnd Property\n\nPrivate Property Let IAdvTextBox_MaxValue(ByVal value As Double)\n this.MaxValue = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_MinValue() As Double\n IAdvTextBox_MinValue = this.MinValue\nEnd Property\n\nPrivate Property Let IAdvTextBox_MinValue(ByVal value As Double)\n this.MinValue = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_FixedFormat() As Boolean\n IAdvTextBox_FixedFormat = this.FixedFormat\nEnd Property\n\nPrivate Property Let IAdvTextBox_FixedFormat(ByVal value As Boolean)\n this.FixedFormat = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_ToCase() As DesiredCase\n IAdvTextBox_ToCase = this.ToCase\nEnd Property\n\nPrivate Property Let IAdvTextBox_ToCase(ByVal value As DesiredCase)\n this.ToCase = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_InvalidValueMessage() As String\n IAdvTextBox_InvalidValueMessage = this.InvalidValueMessage\nEnd Property\n\nPrivate Property Let IAdvTextBox_InvalidValueMessage(ByVal value As String)\n this.InvalidValueMessage = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_IsValid() As Boolean\n IAdvTextBox_IsValid = this.IsValid\nEnd Property\n\nPrivate Property Let IAdvTextBox_IsValid(ByVal value As Boolean)\n this.IsValid = value\n ColorTextBox this.IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_ShowValidityThrough() As ValidityProperty\n IAdvTextBox_ShowValidityThrough = this.ShowValidityThrough\nEnd Property\n\nPrivate Property Let IAdvTextBox_ShowValidityThrough(ByVal value As ValidityProperty)\n this.ShowValidityThrough = value\n ColorTextBox IAdvTextBox_IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_ValidColor() As Long\n IAdvTextBox_ValidColor = this.ValidColor\nEnd Property\n\nPrivate Property Let IAdvTextBox_ValidColor(ByVal value As Long)\n this.ValidColor = value\n ColorTextBox IAdvTextBox_IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_InvalidColor() As Long\n IAdvTextBox_InvalidColor = this.InvalidColor\nEnd Property\n\nPrivate Property Let IAdvTextBox_InvalidColor(ByVal value As Long)\n this.InvalidColor = value\nEnd Property\n\nPrivate Property Get IAdvTextBox_Enlarged() As Boolean\n IAdvTextBox_Enlarged = this.Enlarged\nEnd Property\n\nPrivate Property Let IAdvTextBox_Enlarged(ByVal value As Boolean)\n this.Enlarged = value\n ColorTextBox IAdvTextBox_IsValid\nEnd Property\n\nPrivate Property Get IAdvTextBox_AllowedCharacters() As String\n IAdvTextBox_AllowedCharacters = this.AllowedCharacters\nEnd Property\n\nPrivate Property Let IAdvTextBox_AllowedCharacters(ByVal value As String)\n this.AllowedCharacters = value\nEnd Property\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:26:19.830",
"Id": "478373",
"Score": "0",
"body": "Thanks for the answer and the effort! \nI'm not understanding how an interface works, but I found some articles.. I'll be back as soon as I can understand the logic behind.\nThank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T14:38:47.100",
"Id": "243716",
"ParentId": "243672",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:24:36.097",
"Id": "243672",
"Score": "2",
"Tags": [
"vba",
"excel",
"ms-access"
],
"Title": "Auto formatting and auto validating TextBox VBA"
}
|
243672
|
<p>Just a disclaimer this code <em>was</em> one of the last homework submission for my CSCI intro to C++ class and from my guess very rough around the edges. If any of you are bored during the quarantine and want to look at around 450 lines of a novices code, please, by all means, be brutally honest I can take it and I would actually be very appreciative of it!</p>
<p><strong>Given code:</strong></p>
<pre><code>class Name
{
private:
string first_;
string last_;
}
class Date
{
private:
int year_;
int month_;
int day_;
}
class Book
{
private:
Name author_;
string title_;
int year_;
}
class LibraryBook
{
private:
int id_;
Book book_;
Name borrower_;
Date borrowed_;
Date due_;
bool isLoaned_;
}
</code></pre>
<p>The Following were the <strong>instructions</strong> for me to follow</p>
<ul>
<li><p>constructors to create LibraryBook object</p>
</li>
<li><p>Accessors and mutators for each data member</p>
</li>
<li><p>neatly print all information about this library book</p>
<ul>
<li>print borrower and date information only if on loan</li>
</ul>
</li>
<li><p>loan the book:</p>
<ul>
<li>parameters include borrowing date, due date, and borrower</li>
<li>Ensure that the due date is after the borrowing date (else do nothing other than print an error message)</li>
<li>if already out on loan, do nothing other than printing a message to that effect (can include due date).</li>
</ul>
</li>
<li><p>Return the book:</p>
<ul>
<li>Expunge the borrower name information and set isLoaned to false (if not loaned do nothing and print a message to that effect)</li>
</ul>
</li>
<li><p>Renew the book:</p>
<ul>
<li>update the borrowing data and due date</li>
</ul>
</li>
</ul>
<p>Test drivers were given some details too but I don't think it is too important to put the specifics in this form (Correct me if you want/need it and I will happily add it). But to sum up the requirements for the drivers I needed to declare a vector from the class LibraryBook and from this add some starting books.</p>
<p><strong>Pseudocode:</strong></p>
<pre><code>include iostream
include vectors
include ctime // for getting current time
class Name
{
public:
get function
set function
private:
string first_;
string last_;
}
class Date
{
public:
set function
get function
private:
int year_;
int month_;
int day_;
}
class Book
{
public:
get function
set function
private:
Name author_;
string title_;
int year_;
}
class LibraryBook
{
public:
set function
get function
private:
int id_;
Book book_;
Name borrower_;
Date borrowed_;
Date due_;
bool isLoaned_;
}
void readbooks
void menu()
void bookReturn()
void BookCheckout()
main()
vector<libraryBook> library
do
menu()
if else if block to check what they want to do
while (x)
return
end main()
default constructor
main constructor
get functions for Librarybooks
void BookCheckout(vector<LibraryBook> &library)
get the author name
get the title
get the borrowers name
get the current day
get the book id
push back vector to add book
end void book checkout
book return function
get the users name
find all books under their name
print the option for what book they are returning
erase the book that they want to return
end book return gunction
readBooks function
read all of the current books that are on loan
end readBooks function
</code></pre>
<p><strong>Main Program:</strong></p>
<pre><code>// 5/3/2020, Homework 7
//This program will keep track of books and tell you
//weather they when they were borrowed, overdue, and
//who borrowed the book.
#include <iostream>
#include <vector>
#include <ctime> // for getting current time
#include <iomanip>
using namespace std;
class Name
{
public:
void setName(string first, string last)
{
first_ = first;
last_ = last;
}
string printName()
{
return first_ + " " + last_;
}
private:
string first_;
string last_;
};
class Date
{
public:
void setDate(int day, int month, int year)
{
day_ = day;
month_ = month;
year_ = year;
}
void setDueDate(int day, int month, int year)
{
day_ = day;
if (month == 12)
{
month_ = 1;
year_ = year + 1;
}
else
{
month_ = month + 1;
year_ = year;
}
}
string printDate()
{
return to_string(day_) + " / " + to_string(month_) + " / " + to_string(year_);
}
int day()
{
return day_;
}
int month()
{
return month_;
}
int year()
{
return year_;
}
private:
int year_;
int month_;
int day_;
};
class Book
{
public:
void setBook(string AuthorFirstName, string AuthorLastName, string Title, int Year)
{
author_.setName(AuthorFirstName, AuthorLastName);
title_ = Title;
year_ = Year;
}
string PrintBook()
{
return "AUTHOR:" + author_.printName() + "\nTITLE: " + title_ + "\nYEAR: " + to_string(year_);
}
private:
Name author_;
string title_;
int year_;
};
class LibraryBook
{
public:
LibraryBook(string AuthorFirstName, string AuthorLastName, string Title, int Year,
string BorrowerFirstName, string BorrowerLastName,
int BarrowdDay, int BarrowedMonth, int BarrowedYear,
int CurrentDay, int currentMonth, int currentYear,
int BookID)
{
due_.setDueDate(BarrowdDay, BarrowedMonth, BarrowedYear);
borrowed_.setDate(BarrowdDay, BarrowedMonth, BarrowedYear);
borrower_.setName(BorrowerFirstName, BorrowerLastName);
book_.setBook(AuthorFirstName, AuthorLastName, Title, Year);
today_.setDate(CurrentDay, currentMonth, currentYear);
setId(BookID);
setIsLoaned();
}
string getBook() // get function for book
{
return book_.PrintBook();
}
string getBorrower() // get function for borrower
{
return borrower_.printName();
}
int getID() // get function for ID
{
return id_;
}
string getBorrowedDate() // get function for borrowed date
{
return "Checked out on: " + borrowed_.printDate();
}
string getDueDate() // get function for due date
{
return "Due on: " + due_.printDate();
}
bool isOverDue() // get function for over due
{
if (today_.year() >= due_.year()){
if (today_.month() >= due_.month())
{
if (today_.day() > due_.day())
{
return true;
}
else
return false;
}
else
return false;
}
else
return false;
}
void setId(int id)
{
id_ = id;
}
void setIsLoaned(bool op = true)
{
isLoaned_ = op;
}
bool getIsLoaned()
{
return isLoaned_;
}
// string getBook();
// string getBorrower();
// int getID();
// string getBorrowedDate();
// string getDueDate();
// bool isOverDue();
// LibraryBook(
// string AuthorFirstName, string AuthorLastName, string Title, int Year,
// string BorrowerFirstName, string BorrowerLastName,
// int BarrowdDay, int BarrowedMonth, int BarrowdYear,
// int CurrentDay, int currentMonth, int currentYear,
// int BookId);
LibraryBook(); // default constructor
//~LibraryBook(); // deconstructor;
private:
int id_;
Book book_;
Name borrower_;
Date borrowed_;
Date due_;
Date today_;
bool isLoaned_;
};
void readBooks(vector<LibraryBook> Library); // prototype for reading the books
void menu(); // prototype for the menu
void BookReturn(vector<LibraryBook> &Library); // prototype for returning books
void BookCheckOut(vector<LibraryBook> &Library); // prototype for checking books out
void DefaultBook(vector<LibraryBook> &Library);
// -------------------------------------------------------------------------- //
// --------------- END OF PROTOTYPES AND CLASS DEFFINITION ------------------ //
// -------------------------------------------------------------------------- //
int main()
{
vector<LibraryBook> Library;
DefaultBook(Library);
int op;
bool logout = false;
do
{
menu();
cin >> op;
if (op == 1)
{
BookCheckOut(Library); // calls the checkout option
}
else if (op == 2)
{
BookReturn(Library); // calls the BookReturn Function
}
else if (op == 3)
{
readBooks(Library); // calls the readbook function
}
else if (op == 4)
logout = true; // logs out
else
cout << "The input " << op << " was not recognized" << endl << endl; // gives you an error message for a bad choice
} while (logout != true);
return 0;
}
// -------------------------------------------------------------------------- //
// -------------------------------- END OF MAIN ----------------------------- //
// -------------------------------------------------------------------------- //
void menu() // function to print the main option menu
{
cout << "Check out a book: 1" << endl;
cout << "Return book: 2" << endl;
cout << "Read books: 3" << endl;
cout << "logout: 4" << endl;
cout << "[*] ";
}
void BookCheckOut(vector<LibraryBook> &Library) // function to check out a book
{
string AuthorFirstName, AuthorLastName, Title, BorrowerFirstName, BorrowerLastName;
int Year, BarrowdDay, BarrowedMonth, BarrowdYear, BookId, CurrentDay, currentMonth, currentYear;
cout << endl;
cout << "Please enter the authors first name: ";
cin >> AuthorFirstName;
cout << endl;
cout << "Please enter the authors last name: ";
cin >> AuthorLastName;
cout << endl;
cout << "Please enter the title of the book: ";
getline(cin, Title);
cout << endl;
cout << "Please enter the year the book was published: ";
cin >> Year;
cout << "Please enter your first and last name: ";
cin >> BorrowerFirstName >> BorrowerLastName;
cout << endl;
cout << "Please enter todays date (Day Month Year) seperated with spaces: ";
cin >> BarrowdDay >> BarrowedMonth >> BarrowdYear;
cout << endl;
cout << "Please enter the book ID (If it starts with a zero don't enter the zero): ";
cin >> BookId;
cout << endl;
time_t t = time(NULL);
tm* timePtr = localtime(&t);
CurrentDay = timePtr->tm_mday;
currentMonth = timePtr->tm_mon;
currentYear = timePtr->tm_year + 1900;
Library.push_back(LibraryBook(
AuthorFirstName, AuthorLastName, Title, Year,
BorrowerFirstName, BorrowerLastName,
BarrowdDay, BarrowedMonth, BarrowdYear,
CurrentDay, currentMonth, currentYear,
BookId));
return;
}
void BookReturn(vector<LibraryBook> &Library)
{
string firstName, lastName;
vector<int> pos;
int op;
cout << "Please enter your first name and last name seperated with a space\n[*]";
cin >> firstName >> lastName;
for (int i = 0; i < Library.size(); i++)
{
if (firstName + " " + lastName == Library[i].getBorrower())
{
pos.push_back(i);
}
}
cout << "Please enter the option number you are returning... \nIf there are more than one options please do this multiple times" << endl;
for (int i = 0; i < pos.size(); i++)
{
cout << "Op: " << i << endl << Library[pos[i]].getBook() << endl;
}
cout << "\n[*]";
cin >> op;
cout << pos[op];
Library[pos[op]].setIsLoaned(false);
Library.erase(Library.begin() + op);
return;
}
void readBooks(vector<LibraryBook> Library)
{
cout << endl << endl;
for (int i = 0; i < Library.size(); i++)
{
cout << Library[i].getBook() << endl;
cout << "ID: " <<Library[i].getID() << endl;
cout << "Checked out by: " << Library[i].getBorrower() << endl;
cout << Library[i].getBorrowedDate() << endl;
cout << Library[i].getDueDate() << endl;
if (Library[i].isOverDue())
cout << setw(4) << ' ' << "This book is over due" << endl;
if (Library[i].getIsLoaned())
cout << setw(4) << ' ' << "This book is on loan" << endl;
else if (!Library[i].getIsLoaned())
cout << setw(4) << ' ' << "This book is not on loan" << endl;
cout << endl << endl << endl;
}
return;
}
void DefaultBook(vector<LibraryBook> &Library)
{
string AuthorFirstName, AuthorLastName, Title, BorrowerFirstName, BorrowerLastName;
int Year, BarrowdDay, BarrowedMonth, BarrowdYear, BookId, CurrentDay, currentMonth, currentYear;
{ // book one that will be automatically added to the books when you check out
AuthorFirstName = "Robert";
AuthorLastName = "Ludlum";
Title = "The Bourne Identity";
Year = 1980;
BorrowerFirstName = "Connor";
BorrowerLastName = "Jenson";
BarrowdDay = 3;
BarrowedMonth = 5;
BarrowdYear = 2020;
BookId = 399900705;
time_t t = time(NULL);
tm* timePtr = localtime(&t);
CurrentDay = timePtr->tm_mday;
currentMonth = timePtr->tm_mon;
currentYear = timePtr->tm_year + 1900;
Library.push_back(LibraryBook(
AuthorFirstName, AuthorLastName, Title, Year,
BorrowerFirstName, BorrowerLastName,
BarrowdDay, BarrowedMonth, BarrowdYear,
CurrentDay, currentMonth, currentYear,
BookId));
}
{ // book two that will be automatically added to the books when you check out
AuthorFirstName = "Dan";
AuthorLastName = "Brown";
Title = "The Da Vinci Code";
Year = 2003;
BorrowerFirstName = "John";
BorrowerLastName = "Doe";
time_t t = time(NULL);
tm* timePtr = localtime(&t);
BarrowdDay = timePtr->tm_mday;
BarrowedMonth = timePtr->tm_mon;
BarrowdYear = timePtr->tm_year + 1900;
BookId = 399900705;
CurrentDay = timePtr->tm_mday;
currentMonth = timePtr->tm_mon;
currentYear = timePtr->tm_year + 1900;
Library.push_back(LibraryBook(
AuthorFirstName, AuthorLastName, Title, Year,
BorrowerFirstName, BorrowerLastName,
BarrowdDay, BarrowedMonth, BarrowdYear,
CurrentDay, currentMonth, currentYear,
BookId));
}
{ // book two that will be automatically added to the books when you check out
AuthorFirstName = "Stephenie";
AuthorLastName = "Meyer";
Title = "Forks"; // this is the orrigional title (first book in twilight)
Year = 2005;
BorrowerFirstName = "James";
BorrowerLastName = "Christian";
time_t t = time(NULL);
tm* timePtr = localtime(&t);
BarrowdDay = 1;
BarrowedMonth = 3;
BarrowdYear = 2020;
BookId = 399900705;
CurrentDay = timePtr->tm_mday;
currentMonth = timePtr->tm_mon;
currentYear = timePtr->tm_year + 1900;
Library.push_back(LibraryBook(
AuthorFirstName, AuthorLastName, Title, Year,
BorrowerFirstName, BorrowerLastName,
BarrowdDay, BarrowedMonth, BarrowdYear,
CurrentDay, currentMonth, currentYear,
BookId));
}
return;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:18:14.037",
"Id": "478293",
"Score": "0",
"body": "@πάνταῥεῖ it seems like the part on the bottom is the working code. Perhaps pseudocode and real code (submission) should be separated into multiple sections to make it clear which functions were required to implement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:20:01.830",
"Id": "478294",
"Score": "1",
"body": "Since this is a homework solution, I suggest removing the name of the course so that people googling \"<name of course> solution\" won't discover this post. (Personally I'd also consider removing your IRL name so that future employers googling \"<your name>\" won't find this, but that's more of a personal decision.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:50:05.357",
"Id": "478296",
"Score": "0",
"body": "@Quuxplusone Thank you for the insight for that and I think that that is a good idea and I'll keep these in mind for the future!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T16:51:35.113",
"Id": "478297",
"Score": "0",
"body": "@πάνταῥεῖ I removed the pseudocode and I will also added a bit more detail for what I needed to do to create this!"
}
] |
[
{
"body": "<h1>Write real constructors for all your classes</h1>\n<p>You wrote a proper constructor for <code>LibraryBook</code>, but for the other classes you only wrote <code>setSomething()</code> functions. Try to convert those to proper constructors. The advantage of that is that it forces you to properly initialize instances of those classes. If I just write:</p>\n<pre><code>Date date;\n</code></pre>\n<p>This allows me to forget to call <code>setDate()</code>, and then if I access it later on it will have an undefined value that might cause bad things to happen.</p>\n<h1>Only write setter functions for variables that are allowed to be changed.</h1>\n<p>For example, you probably never want a library book's ID to be changed, so don't add <code>setId()</code>. If possible, I would make the member variable <code>id_</code> itself <code>const</code> as well.</p>\n<h1>Ensure there are getters and setters for all relevant member variables</h1>\n<p>Your <code>class Book</code> doesn't have getters to get the author, title or year from a book. While you might not use it right now, it would be helpful to have getters for all of those if for example you want to search the library for all books from a certain author.</p>\n<h1>Don't add unnecessary member variables</h1>\n<p>Why did you add <code>today_</code> to <code>LibraryBook</code>? You can always query the current day by using one of the time functions from the standard library, like <a href=\"https://en.cppreference.com/w/cpp/chrono/system_clock/now\" rel=\"nofollow noreferrer\"><code>std::chrono::system_clock::now()</code></a>. You don't need to store this in the book itself.</p>\n<h1>Write proper <code>std::ostream</code> formatters and/or <code>to_string()</code> functions</h1>\n<p>Your classes have <code>printSomething()</code> functions that don't print anything, but rather create strings. I would rename those functions <code>to_string()</code>, so it matches what the standard library does.</p>\n<p>Furthermore, you can also functions that make it easy to print in the C++ way, by writing so-called <code>std::ostream</code> formatters. It looks like this:</p>\n<pre><code>class Name {\npublic:\n ...\n friend std::ostream &operator<<(std::ostream &os, const Name &self) {\n return os << first_ << " " << last__;\n }\n};\n</code></pre>\n<p>You can then print a <code>Name</code> like so:</p>\n<pre><code>Name name("John", "Smith");\nstd::cout << "The name is: " << name << "\\n";\n</code></pre>\n<h1>Use <code>"\\n"</code> instead of <code>std::endl</code></h1>\n<p><code>std::endl</code> is equivalent to <code>"\\n"</code> plus a forced flush of the output stream, which might hurt performance. See <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">this StackOverflow question</a> for more the details.</p>\n<h1>Consider using a <code>std::chrono</code> class to store dates</h1>\n<p>If you are not allowed to change the way dates are stored, it's fine. But the standard library provides several ways to store times. Since C++11, there's <a href=\"https://en.cppreference.com/w/cpp/chrono/time_point\" rel=\"nofollow noreferrer\"><code>std::chrono::time_point</code></a> which represents arbitrary points in time, and in C++20 there will be <a href=\"https://en.cppreference.com/w/cpp/chrono/year_month_day\" rel=\"nofollow noreferrer\"><code>std::chrono::year_month_day</code></a> to represent calendar dates. The advantage of these classes is that they come with member function which allow easy manipulation of them, like checking if a given day comes before or after another day, and so on.</p>\n<h1>Check your spelling</h1>\n<p>You wrote <code>BarrowdDay</code>, which should be <code>BorrowedDay</code>. There are tools that can help you find and fix spelling errors in source code, like <a href=\"https://github.com/codespell-project/codespell\" rel=\"nofollow noreferrer\">codespell</a>.</p>\n<h1>Don't initialize things in a constructor that don't need initialization</h1>\n<p>Typically, when adding a book to a library, it will not be in a checked out state. Only when it is part of the library can it be checked out. It therefore makes sense to have the constructor of <code>LibraryBook</code> only take parameters necessary to inialize the <code>book</code> and the <code>id_</code> variables, and set <code>isLoaned_</code> to <code>false</code>.</p>\n<h1>Avoid <code>using namespace std</code></h1>\n<p>Writing <code>using namespace std</code> is considered <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad practice</a>, because it hides namespace conflicts. Just make it a habit to add <code>std::</code> where necessary. You have to use it less often than you think, especially if you make use of <code>auto</code>.</p>\n<h1>Pass strings using const references</h1>\n<p>Passing strings by value can cause unnecessary copying of the strings. Pass them by const reference instead. See the example below.</p>\n<h1>Use member initializer lists where possible</h1>\n<p>When writing a constructor, <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list\">it's preferable to use member initializer lists</a> instead of setting each member in the body of the constructor function. For example:</p>\n<pre><code>class Name {\n public:\n Name(const std::string &first, const std::string &last): first_(first), last_(last) {}\n ...\n};\n</code></pre>\n<h1>Consider passing a <code>Book</code> to the constructor of <code>LibraryBook</code></h1>\n<p>Instead of having the constructor take lots of parameters, that are then passed on to the construction of the <code>book_</code> member variable, take a const reference to a <code>Book</code> instead, like so:</p>\n<pre><code>class LibraryBook {\n public:\n LibraryBook(const Book &book, int BookID): book_(book), id_(BookID), isLoaned_(false) {}\n ...\n};\n</code></pre>\n<p>The copy constructor of <code>Book</code>, which will have been created implicitly in your case, will take care of copying the details from the parameter <code>book</code> into the member variable <code>book_</code>. You can use it like so:</p>\n<pre><code>Book book("Lewis", "Carrol", "Alice's Adventures in Wonderland", ...);\nLibraryBook libraryBook(book, 9780199558292);\n</code></pre>\n<p>You can also avoid creating a named <code>Book</code> variable, and create a <code>LibraryBook</code> like so:</p>\n<pre><code>LibraryBook libraryBook({"Lewis", "Carrol", ...}, 9780199558292);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T19:12:55.597",
"Id": "243679",
"ParentId": "243673",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243679",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T15:54:30.043",
"Id": "243673",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Library Book Program For Reworking and Optimizing"
}
|
243673
|
<p>Can anyone help me improve the performance of my code.</p>
<blockquote>
<p>Given a sorted array of distinct integers, write a function <code>indexEqualsValue</code> that returns the lowest index for which <code>array[index] == index</code>. Return -1 if there is no such index.</p>
</blockquote>
<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 indexEqualsValue(a) {
var arr =[]
a.forEach((el, i) => {
if( el==i){
arr.push(el)
}
})
if(arr.length==0){
return -1
}else{
return arr[0]
}
}</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T22:38:03.963",
"Id": "478398",
"Score": "0",
"body": "`can any one help me execution code time, please?` This is right where trouble starts: this sentence looks incorrect, and I can't confidently guess what is meant. Why collect values into an array to just return the first one?"
}
] |
[
{
"body": "<p>Assuming the input is sorted in ascending order, if <code>a[i] > i</code> then <code>a[j] > j</code> for any <code>j >= i</code>, because the numbers in the input are supposed to be distinct.</p>\n<p>There is also no reason to aggregate all values that satisfy the criterion to eventualy only return the first one. Just return the first one when encountered.</p>\n<pre><code>function indexEqualsValue(input)\n{\n const limit = input.length\n for (let i = 0; i < limit; ++i) {\n if (input[i] === i) {\n return i\n }\n \n if (input[i] > i) {\n return -1\n }\n }\n \n return -1\n}\n\nconsole.log(indexEqualsValue([0,1,2])) // 0\nconsole.log(indexEqualsValue([1,2,3])) // -1\nconsole.log(indexEqualsValue([-1,1,2])) // 1\n</code></pre>\n<p>A bit of complexity analysis:</p>\n<p>Your solution is O(n) in time and O(k) in space, where n is size of input, and k is number of elements that satisfy the criterion <code>a[i]==i</code>, <code>k <= n</code>.</p>\n<p>My solution is O(b) in time, and O(1) in space, where b is number of elements that satisfy a similar criterion: <code>a[i] < i</code>, in words, the number of elements that are less then their index, <code>b <= n</code>. If input does not contain negative numbers, it is O(1) in time (thats actually because in that case the result must be zero, or -1).</p>\n<p>PS: Next time, please, take your time to write a good quality question. Succint algorithm definition without any additional information makes up for a very poor question. You're lucky I'm in mood.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T19:33:03.980",
"Id": "243681",
"ParentId": "243676",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T18:10:56.820",
"Id": "243676",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "Find the first element that equals its index"
}
|
243676
|
<p>I recently began to learn Python and encountered this problem.</p>
<p><strong>The condition:</strong><br />
You and your friends are playing the next game. Friends write <code></code> natural numbers in a row on the board. Your task is to find as many consecutive numbers as possible that are divisible by the same number greater than <code>1</code>. Since it is difficult to find the answer manually, you decided to write a program that will do the job for you.</p>
<p><strong>Input:</strong><br />
The first line of the input contains the number <code></code> (<code>1 ≤ ≤ 100000</code>). The second line is separated by a space <code></code> integers <code>1</code>...<code> </code>(<code>1 ≤ ≤ 1000</code>, <code>1 ≤ ≤ </code>). These are the numbers that your friends wrote. They are given in the same order as they are placed on the board.</p>
<p><strong>Output:</strong><br />
Your program should output a single integer — the largest number of consecutive numbers in a given sequence that would be divisible by the same natural number greater than <code>1</code>.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>Python
from math import gcd
def func(n,a):
mx = 0
for i, cur_g in enumerate(a):
if n - i < mx:
break
p = 0
for j in range(i, n):
cur_g = gcd(cur_g, a[j])
if cur_g == 1:
break
p += 1
if mx < p:
mx = p
return mx
print(func(int(input()), [int(i) for i in input().split()]))
</code></pre>
<p>The problem is that I can't pass the time check: the program runs for longer than 0.5 seconds. And I can't think of any way to speed up the program. It may even be necessary to solve the problem itself in a different way. Please help me. Thanks in advance!</p>
|
[] |
[
{
"body": "<p>The way your loops are organized results in an unpleasant phenomenon. Namely, you process the same subsequence many times. Let's say, a long good range starts at the index <code>k</code> and has a length <code>n</code>. The inner loop finds it. Then the next iteration of the outer loop starts processing it again, this time from index <code>k + 1</code>. Then from index <code>k+2</code>, etc. It will take <span class=\"math-container\">\\$O(n^2)\\$</span> of unnecessary computations. In fact, each good range contributes a term quadratic to its length to the total complexity.</p>\n<p>The fix is, once the inner loop terminated, adjust <code>i</code> to continue from the number which broke the good range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T08:19:54.607",
"Id": "478343",
"Score": "0",
"body": "Thank you for your decision, I understand it, but I can't implement it. Please help me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T21:58:42.837",
"Id": "243685",
"ParentId": "243678",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T19:12:29.390",
"Id": "243678",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"array"
],
"Title": "The problem “Fun game” from a competition"
}
|
243678
|
<p>I have many users. Each time a user uses their smartphone it register them. I am determining the last time each user used their smartphone each day.
Additionally smartphone usages from 18:00 to 06:00, the next day, should be considered as an entry on the previous day. I have created a dummy example.</p>
<p>I did the following:</p>
<ol>
<li>First subtract the number of hours.</li>
<li>Sort the data frame based on user and date time.</li>
<li>Get the last row.</li>
</ol>
<p>Is there a more efficient approach to this? Are there other tips I can follow to improve my code?</p>
<pre><code>df_example = {'id': [1,1,1,1,1],
'activity': [datetime.datetime(2019, 12, 1, 19, 30, 1),
datetime.datetime(2019, 12, 1, 20, 22, 2),
datetime.datetime(2019, 12, 2, 2, 13, 2),
datetime.datetime(2019, 12, 3, 19, 12, 2),
datetime.datetime(2019, 12, 3, 21, 3, 1)
]}
df_example = pd.DataFrame(df_example, columns = ['id', 'activity'])
df_example['activity'] = df_example['activity'] - datetime.timedelta(hours=6, minutes=0)
df_example['date'] = df_example['activity'].apply(lambda x: x.date())
df_example.sort_values(by=['id', 'activity'])
df_example.groupby(['id', 'date']).tail(1)
</code></pre>
|
[] |
[
{
"body": "<p>Instead of using <code>tail</code>, if you only need one item there are the <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html\" rel=\"nofollow noreferrer\"><code>first</code></a> and <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.last.html\" rel=\"nofollow noreferrer\"><code>last</code></a> methods, which do exactly what you think they would do with grouped dataframes:</p>\n<pre><code>df_example.groupby(['id', 'date']).last()\n</code></pre>\n<p>I doubt there is a faster way to create the <code>activity</code> column. And you have to create a new one because of your requirement with what counts to which day.</p>\n<p>But you can speed up getting the date. Using <code>apply</code> with a <code>lambda</code> <a href=\"https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6\" rel=\"nofollow noreferrer\">is about the second slowest way</a> to work with <code>pandas</code> (manual Python <code>for</code> loops are slower). Instead use the <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html\" rel=\"nofollow noreferrer\">vectorized datetime functions</a>:</p>\n<pre><code>df_example['date'] = df_example['activity'].dt.date\n</code></pre>\n<hr />\n<p><strong>Potential bug</strong>:\nNote that <code>df_example.sort_values(by=['id', 'activity'])</code> returns the sorted dataframe, it does not modify it inplace. Either assign it back to <code>df_example</code>, or use <code>inplace=True</code>.</p>\n<p>The same is true for <code>groupby</code>, you probably want to assign the result to a variable as well in order to do something else with it afterwards.</p>\n<hr />\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. While it recommends using spaces around the <code>=</code> operator when using it for assignment, it recommends using no spaces when using it for keyword arguments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T08:37:46.267",
"Id": "243707",
"ParentId": "243680",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T19:19:28.790",
"Id": "243680",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"numpy",
"pandas"
],
"Title": "Get the last activity per user per day in a dataframe"
}
|
243680
|
<p>As a personal challenge I want to implement a C++ JSON Parser. As part of that I have implemented the following Types/Data-structures and a way of querying them.</p>
<p>To represent the type of an individual JSON attribute I defined the following std::variant and aliased it as JSONType. My thought behind using an std::variant is that when dealing with a JSON attribute I know that it must be one of the following types, but I can't exactly know which type before parsing the attribute.</p>
<p>Right now I am not concerned about "null" and "arrays with different types".</p>
<pre><code>using JSONType = std::variant
<
bool,
int,
float,
double,
std::string,
std::vector<bool>,
std::vector<int>,
std::vector<float>,
std::vector<double>,
std::vector<std::string>
>;
</code></pre>
<p>To represent a JSON object I defined the struct JSONObject. My reasoning behind the attributes member is that for every JSON attribute I have a string as it's key and the value is either a single JSONType (bool, int, ...) or another JSONObject that recursively repeats this structure.</p>
<p>The query function "getIf(keys)" expects a template type T, which is the type of data that the user expects to get out of the query. keys is a sequence of strings , where the first n-1 strings describe the path of nested JSONObjects down the tree to which the attribute resides that we want to return. So the nth string is the name of that attribute.</p>
<pre><code>struct JSONObject
{
std::unordered_map<std::string, std::variant<JSONType, JSONObject>> attributes;
template <class T>
T* getIf(std::vector<std::string> const& keys)
{
JSONObject* temp = this;
// Go to JSONObject where last keys attribute resides.
for (int i = 0; i < (keys.size() - 1); ++i)
{
temp = &std::get<JSONObject>(temp->attributes[keys[i]]);
}
// Find the attribute that we actually want to return,
// which is the attribute that is pointed to by
// the last given key.
JSONType& variant = std::get<JSONType>(temp->attributes[keys[keys.size() - 1]]);
// Check if the given template type T is the same type
// that the attribute that we want to return has.
if (auto* value = std::get_if<T>(&variant))
{
return value;
}
else
{
return nullptr;
}
}
};
</code></pre>
<p>The following is an example instatiation and query of a JSONObject that represents the following json file and should result in a tree-like structure like the diagram shows.</p>
<pre><code> JSONObject o
{ // Initialization brackets
{ // unordered_map brackets
{ "boolean", std::variant<JSONType, JSONObject>(true) }, // map entry brackets
{ "nested_object", std::variant<JSONType, JSONObject>(JSONObject
{
{
{ "float", std::variant<JSONType, JSONObject>(3.14123f)},
{ "nested_object_2", std::variant<JSONType, JSONObject>(JSONObject
{
{
{ "string", std::variant<JSONType, JSONObject>(std::string("Hello World"))}
}
}
)},
{ "numbers", std::variant<JSONType, JSONObject>(std::vector<int>{1, 2, 3, 4, 5}) }
}
}
)}
}
};
bool boolean = *o.getIf<bool>({ "boolean" });
float flo = *o.getIf<float>({ "nested_object", "float" });
std::string string = *o.getIf<std::string>({ "nested_object", "nested_object_2", "string" });
std::vector<int> numbers = *o.getIf<std::vector<int>>({ "nested_object", "numbers" });
{
"boolean": true,
"nested_object":
{
"float": 3.14123f,
"nested_object_2":
{
"string": "Hello World"
},
"numbers": [1, 2, 3, 4, 5]
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/PSGso.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PSGso.png" alt="Diagram" /></a></p>
<p>I am interested in the quality of this solution and alternative solutions.
Thanks !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T22:22:02.827",
"Id": "478309",
"Score": "0",
"body": "Here is an alternative: [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer/blob/master/doc/example1.md)"
}
] |
[
{
"body": "<p>Don't like this:</p>\n<pre><code>using JSONType = std::variant\n<\n bool,\n int,\n float,\n double,\n std::string,\n\n std::vector<bool>,\n std::vector<int>,\n std::vector<float>,\n std::vector<double>,\n std::vector<std::string>\n>;\n</code></pre>\n<p>That's not really what the type looks like. The array (Vector) can have any JSON type as a member. I think a better version would be:</p>\n<pre><code>#include <string>\n#include <unordered_map>\n#include <vector>\n#include <variant>\n\nenum JsonType {Null, Obj, Vec, Bool, Int, Double, String};\nclass Json;\nstruct JsonObj\n{\n std::unordered_map<std::string, Json> members;\n};\nusing JsonVec = std::vector<Json>;\nunion JsonUnion\n{\n JsonUnion() {null_ = nullptr;}\n ~JsonUnion(){}\n void* null_;\n JsonObj object_;\n JsonVec array_;\n bool bool_;\n int int_;\n double real_;\n std::string string_;\n};\nclass Json\n{\n\n JsonType type;\n JsonUnion data;\n public:\n Json()\n : type(Null)\n , data()\n {}\n};\n\nint main()\n{\n Json value;\n}\n</code></pre>\n<hr />\n<p>The get function assumes you only have objects. You should be able to handle de-referencing arrays. But that requires two types of get parameter (integer and string).</p>\n<pre><code>using Access = std::variant<int, std::string>;\n\ntemplate <class T>\nT* getIf(std::vector<Access> const& keys)\n</code></pre>\n<hr />\n<p>Also why are you returning a pointer?</p>\n<pre><code>T* getIf()\n</code></pre>\n<p>Memory management is hard. That is why C got such a bad reputation for being hard. Java tried to solve this with the garbage collector (which just caused more issues with runtime running). C++ solved the problem by introducing "Automated Fine Grain Deterministic Memory Management" also know as "Smart Pointers". This is how memory management is done consisely and reliabily in modern C++.</p>\n<pre><code>std::unqiue_ptr<T> getIf()\n</code></pre>\n<hr />\n<p>Using <code>class</code> in the template is a bit old school.</p>\n<pre><code>template <class T>\nT* getIf(\n</code></pre>\n<p>Sure it is technically valid. But most people use <code>typename</code>. It has exactly the same meaning to the compiler. But to the human it implies that <code>T</code> can be any type (not just a class Type).</p>\n<hr />\n<p>If you are "getting" something from an object then I would normally expect that this would not alter the object. I notice that your <code>getIf()</code> is not <code>const</code>. You probably did this because it does not compile with <code>const</code>. This is because you use <code>operator[]</code> on the unordered map.</p>\n<pre><code>temp = &std::get<JSONObject>(temp->attributes[keys[i]]);\n ^ ^\n</code></pre>\n<p>When looking a value in a unordered_map (or map) and you use the square braces then if the key does not exist it is added to the structure. This is probably not what you want.</p>\n<p>I would change this so it uses a <code>find</code>. If the object does not have the appropriate key then you have a serious issue and I would throw an exception:</p>\n<pre><code>auto find = temp->attributes.find(keys[i]);\nif (find == temp->attributes.end()) {\n throw "Bad Member Name";\n}\n\ntemp = &std::get<JSONObject>(find->second);\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T08:58:20.843",
"Id": "478344",
"Score": "0",
"body": "For clarification, by \"The get function assumes you only have objects. You should be able to handle de-referencing arrays. But that requires two types of get parameter (integer and string).\" you mean that if I have the attribute \n`\"numbers\": [1, 2, 3, 4, 5]`, I should be able to return an individual value of that array ? Maybe I misunderstand you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T18:09:40.410",
"Id": "478384",
"Score": "1",
"body": "@MoritzSchäfer: `getIf<int>(\"nested_object\", \"numbers\", 3)` should be able to return the 3 element in \"numbers\" that is in the member \"nested_object\" inside your object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:08:47.877",
"Id": "478446",
"Score": "0",
"body": "You are using a union for JSONUnion instead of an std::variant because you can't do null = nullptr; with std::variant ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:12:52.593",
"Id": "478461",
"Score": "0",
"body": "@MoritzSchäfer I used a `union` because I don't know how to use `std::variant` it's not something I have found the need for yet. Note: I don't use `union` often either (about twice in thirty years)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T22:55:45.977",
"Id": "243690",
"ParentId": "243683",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243690",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T21:37:15.713",
"Id": "243683",
"Score": "3",
"Tags": [
"c++",
"reinventing-the-wheel",
"json"
],
"Title": "JSON Data-structure in C++ and querying it"
}
|
243683
|
<pre><code>
#!/usr/bin/env stack
{- stack
--install-ghc
exec ghci
--package lens
-}
module Main where
import Control.Lens
import Data.List.Lens
import Debug.Trace
import Text.Printf
import Prelude hiding (Left, Right)
data Direction = Up | Left | Down | Right
data Location = Location Int Int
type Grid = [[Int]]
main = printClockwise 25
printClockwise :: Int -> IO ()
printClockwise n = putStrLn $ concatMap printRow grid
where
grid = walk directions center 1 emptyGrid
emptyGrid = replicate sq (take sq (repeat 0))
printRow row = concatMap (printf "%4s" . show) row ++ "\n"
-- Ex. for a 5x5 spiral the start location is (2,2)
center = Location half half
half = floor $ (fromIntegral sq) / 2
-- This will return all directions we should walk through the spiral in.
-- Something like [Right, Down, Left, Left, Up, Up, Right, Right, Right]
directions = concatMap (\(direction, steps) -> take steps $ repeat direction) (zip directionOrder steps)
directionOrder = cycle [Right, Down, Left, Up]
-- Ex. for a spiral up to 25, the steps are 1, 1, 2, 2, 3, 3, 4, 4, 5
steps = concatMap (take 2 . repeat) [1 .. sq - 1] <> [sq]
-- Assume the input is a perfect square of an odd number
sq = ceiling $ sqrt (fromIntegral n)
walk :: [Direction] -> Location -> Int -> Grid -> Grid
walk (dir : dirs) loc@(Location x y) current grid = do
let grid' = grid & (ix y . ix x) .~ current
let loc' = moveLocation dir loc
walk dirs loc' (current + 1) grid'
walk [] _ _ numbers = numbers
moveLocation Down (Location x y) = Location (x) (y + 1)
moveLocation Right (Location x y) = Location (x + 1) (y)
moveLocation Left (Location x y) = Location (x -1) (y)
moveLocation Up (Location x y) = Location (x) (y - 1)
</code></pre>
<p>I came across this problem on reddit and thought it'd be fun to try my hand at it in Haskell. The idea is to generate the grid before printing, and the insight to generate that grid was that the movement follows a predictable pattern, of right, down, left, up, and the # of steps taken in a given direction is 1, 1, 2, 2, 3, 3, 4, 4... , n - 1, n -1, n , where n is the square of the input number. So with that you can walk through the grid and fill in the numbers.</p>
<p>The function has no input checking, it assumes the input is a perfect square (of an odd number).</p>
|
[] |
[
{
"body": "<p>Not too advanced myself - so take with a grain of salt.</p>\n<ul>\n<li>Foremost I would separate the logic for constructing the grid and printing. Especially extract the function to construct the grid. Currently its wrapped in <code>printClockwise</code> IMHO it should be prominently its own function.</li>\n<li>There are a few definitions in <code>printClockwise</code> (<code>emptyGrid</code>, <code>directionOrder</code> and the printing) that I would consider reusable and would make them top level.</li>\n<li>You only use lens in one place. <code>lens</code> is quite an expensive import - there just was an <a href=\"https://dixonary.co.uk/blog/haskell/pain\" rel=\"nofollow noreferrer\">interesting post</a>. I suppose your intend was to learn lens and therefore it's used - but just for the code I would consider removing the dependency.</li>\n<li>the fixed <code>"%4s"</code> in printing - it's easy to estimate the required width for larger numbers. Or just make it that max <code>n</code> is <code>999</code>.</li>\n</ul>\n<p>Some stuff to consider that is really personal choice - no need to follow if you disagree:</p>\n<ul>\n<li>changing the data type to strict mutable array or similar.</li>\n<li>adding a <code>walk</code> that takes larger strides.</li>\n<li>split the <code>walk</code> function into one stream of positions in the spiral, and separately setting the values in a second step. This could solve the issue that the input needs to be a perfect square - just take the first <code>n</code> positions.</li>\n</ul>\n<p>As last remarks:</p>\n<ul>\n<li>whenever I see such a spiral I think <a href=\"https://en.wikipedia.org/wiki/Ulam_spiral\" rel=\"nofollow noreferrer\">Ulam spiral</a>. If you want to expand I would consider adding functionality to the printing to allow highlight - in this case for primes.</li>\n<li>I also checked whether the coordinates are on OEIS - they are <a href=\"https://oeis.org/A174344\" rel=\"nofollow noreferrer\">A174344</a>. And your algorithm agrees with the algorithm they post along side (the Julia implementation is almost the same, the other use some shenanigans with sin and cosine).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:00:10.717",
"Id": "243757",
"ParentId": "243686",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243757",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T22:23:31.720",
"Id": "243686",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Print numbers in a spiral from the center"
}
|
243686
|
<p>Puts and calls are two types of options. One parameter that they both share is called a strike price. The valuation of an option is related to the strike price, but the exact methodology is different depending on the type of option. All things being equal, a lower strike price is better when valuing a call, and vice versa when considering a put. I am considering the best way to model my code so that these comparisons could be performed as simply and intuitively as possible.</p>
<p>Ideally, I would like to be able assign optionInstance1.Strike = 5, and to evaluate if optionInstance1.Strike > optionInstance2.Strike while considering the rules of the particular type of option. I am trying to explore the best ways to accomplish this.</p>
<p>The first approach: attach an evaluator class to every option instance</p>
<pre><code>interface IOptionRules
{
bool GTE(decimal s1, decimal s2);
}
class CallRules : IOptionRules{ ... }
abstract class Option
{
public decimal strike;
public IOptionValuationRules rules;
public Option(decimal strike, IOptionRules rule){ this.strike = strike; rules = rule;}
}
class CallOption : Option
{
public CallOption(decimal strike) : base(strike, new CallRules()){}
}
</code></pre>
<p>this would allow for easy assignment => strike = 5m
but comparisons would be cumbersome and unintuitive => optionInstance1.Rules.GTE( optionInstance1.strike, optionInstance2.strike);
it would not preclude direct comparison operators => optionInstance1.strike >= optionInstance2.strike</p>
<p>The second approach: perform the evaluations in a completely different class</p>
<pre><code>class OptionEvaluator
{
public bool GTE(CallOption o1, CallOption o2){}
public bool GTE(PutOption o1, PutOption o2){}
}
</code></pre>
<p>It seems this approach invites maintenance issues in the future, for example if I were to create any sort of exotic options with special rules in the future, I would have to remember to update this separate class. Furthermore, I think with this approach I would have to upcast whenever I am working with Option Types.</p>
<p>The third approach: defining a strike type</p>
<pre><code>abstract class Option
{
public Strike strike;
public Option(Strike strike){ this.strike = strike;}
}
abstract class Strike
{
public decimal Amount{get; set;}
public abstract bool GTE(decimal otherStrike);
}
class CallStrike : Strike{...}
class PutStrike : Strike {...}
</code></pre>
<p>This seems to be a desirable approach, but the main issue I have is how cumbersome it would be to assign a strike amount as it would make more sense to type OptionInstance1.Strike = 4 rather than OptionInstance1.Strike.Amount = 4.</p>
<p>Also, I would potentially be able to assign a PutStrike to a CallOption at runtime since the type of the strike field is Strike, although I suppose this is easily fixable if I made it readonly.</p>
<p>Are there any other approachs for this particular issue? Are there particular issues that I am not considering with any of these approachs? Which is the best approach to take?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T22:31:31.397",
"Id": "243687",
"Score": "2",
"Tags": [
"c#"
],
"Title": "How to best structure an abstract class where a member field will depend on the deriving type?"
}
|
243687
|
<p>I think I can summarize the idea to the Producer-Consumer problem, with some modifications.
And I think I misused the term "Producer" (it depends from which point of view :))</p>
<ul>
<li>An infinite consumer/producer produces a result from a given input</li>
<li>The result is computed from another thread</li>
<li>Only one product can be producted at a time.</li>
</ul>
<p>That's it!</p>
<p>I was wondering if the code is OK, ESPECIALLY about thread-safety, and also about copy optimizations, C++ errors and so on.</p>
<pre><code>#pragma once
#include <mutex>
#include <thread>
#include <condition_variable>
/**
* Thread that infinitely make a task consuming each time a resource
* When there is no more resource to consume, the thread exit.
* When the thread is working, it cannot be canceled and wait the end of current operation to
* ask if there is a pending request and see that there is no more pending request and also can end.
*/
template<typename Input, typename Output>
class ThreadConsumer
{
public:
/**
* Ensure cleanup before destruction
*/
virtual ~ThreadConsumer()
{ stop(); }
/**
* Notify the consumer to shutdown and that no new input will be done.
* If a task is currently running, wait the running task to finish before returns.
* Used to join if a task is running before exiting, or free some output generated data.
*/
void stop()
{
std::unique_lock lock(m_mutex);
while(!m_waiting) {
m_condition.wait(lock);
}
if(m_done) { // if zero tasks were accomplished, do not join the empty constructed default thread.
m_thread.join(); // should returns immediately. Required & cleanup
}
}
/**
* @return true if the worker is waiting for an input resource to be processed.
*/
bool ready() const
{
std::lock_guard lock(m_mutex);
return m_waiting;
}
/**
* Give a resource to the Thread. There is no process queue, the thread calling this function will wait
* until the worker take the input. If the worker is waiting (that is ready() returned true in the current thread),
* for an incoming resource, returns immediately.
*/
void give(Input&& resource)
{
std::unique_lock lock(m_mutex);
while(!m_waiting) {
m_condition.wait(lock);
}
if(m_done) {
m_thread.join(); // should return immediately. Required & cleanup
}
m_waiting = false;
m_done = false;
std::thread thread([&] {
m_output = start(std::move(resource));
std::lock_guard<std::mutex> lock(m_mutex);
m_done = true;
m_waiting = true;
m_condition.notify_one();
});
m_thread = std::move(thread);
}
/**
* @return true if the worker has finished a task and can provide an output result.
* Not synonym for ready(): the only difference is just after construction of the consumer: at this time,
* ready() returns true and done() returns false. In others cases, the two functions returns the same value.
*/
bool done() const
{
std::lock_guard lock(m_mutex);
return m_done;
}
/**
* @return the output of the latest task. Do not check if the object is the one default-constructed with this
* object. After at least one task finished, the output is always the result of a preceding task (unless moved from
* caller).
*/
Output& output()
{ return m_output; }
const Output& output() const
{ return m_output; }
protected:
virtual Output start(Input &&input) = 0;
private:
/**
* Result of last computation. Default-constructed if the consumer has not be launched one time.
*/
Output m_output;
/**
* Protect all this class private fields except m_output that should be accessed only after a task finished,
* also without concurrency.
*/
mutable std::mutex m_mutex;
std::condition_variable m_condition;
/**
* Represents current operation thread (if any)
*/
std::thread m_thread;
bool m_waiting = true;
bool m_done = false;
};
template class ThreadConsumer<int, int>; // To debug syntax errors
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I am confused about the design. Normally one reuses the same thread instead of creating one for each minor task. Thread creation is not cheap on most platforms.</p>\n<p><strong>1.</strong> <code>void give(Input&& resource)</code> will be clunky to use as input is an r-value reference which is inconvenient. In many template functions you see <code>&&</code> used a lot but there it is most often interpreted as a universal/forwarding reference which accepts any input. In your case it will be r-values only, i.e., <code>int a = 5; producer.give(a);</code> will not compile and you'll have to write <code>producer.give(std::move(a));</code>. You should read more on r-values and forwarding references.</p>\n<p>For 99% of the cases in should be preferable to have <code>void give(Input resource)</code> instead of <code>void give(Input&& resource)</code>.</p>\n<p><strong>2.</strong> Okey,</p>\n<pre><code>std::thread thread([&] {\n m_output = start(std::move(resource)); // this is a bug\n\n std::lock_guard<std::mutex> lock(m_mutex);\n m_done = true;\n m_waiting = true;\n\n m_condition.notify_one();\n });\n</code></pre>\n<p>The operation might occur after leaving the function and destruction of <code>resource</code> which will make resource to be a dangling reference resulting in UB.</p>\n<p>To fix it you can write it like this:</p>\n<pre><code>std::thread thread([this](Input res) {\n m_output = start(std::move(res)); // this is a bug\n\n std::lock_guard<std::mutex> lock(m_mutex);\n m_done = true;\n m_waiting = true;\n\n m_condition.notify_one();\n }, std::move(resource));\n</code></pre>\n<p><strong>3.</strong> This isn't too good:</p>\n<pre><code> std::lock_guard<std::mutex> lock(m_mutex);\n m_done = true;\n m_waiting = true;\n\n m_condition.notify_one();\n</code></pre>\n<p>You have the <code>mutex</code> locked while notifying another thread so it might result in "hurry up and wait" as it tries to lock the mutex. One should unlock the mutex prior to notifying.</p>\n<p><strong>4.</strong> About stopping:</p>\n<pre><code>void stop()\n{\n std::unique_lock lock(m_mutex);\n\n while(!m_waiting) {\n m_condition.wait(lock);\n }\n\n if(m_done) { // if zero tasks were accomplished, do not join the empty constructed default thread.\n m_thread.join(); // should returns immediately. Required & cleanup\n }\n}\n</code></pre>\n<p>You have lots of unnecessary code here. Just write:</p>\n<pre><code>void stop()\n{\n if(m_thread.joinable()) m_thread.join();\n}\n</code></pre>\n<p>Also the stop, doesn't actually do what the name implies - for what it does should be named <code>wait()</code> or something. <code>stop</code> would have to set the general state to "I refuse to get any more input".</p>\n<p>P.S. don't know why you wrote C++20. There isn't any C++20 here.</p>\n<p><strong>Edit.</strong> also</p>\n<pre><code> virtual ~ThreadConsumer()\n { stop(); }\n</code></pre>\n<p>Is a bug in design. Whatever class that derives from <code>ThreadConsumer</code> will first destroy its members and only then will trigger <code>~ThreadConsumer</code> and subsequently <code>stop()</code> - leading to possible UB as members were likely destroyed before procedure finished.</p>\n<hr />\n<p>Overall, I don't see much use for this <code>ThreadConsumer</code> class. It can be hard to figure out useful abstractions for multithreading. For myself, I figured messaging concept to be both most flexible and efficient.</p>\n<p>What's messaging? You have a <code>transmitter</code> and <code>receiver</code> classes which act according to their names. So the whole <code>ThreadConsumer</code> can be trivially implemented via these two as:</p>\n<pre><code>std::thread([](receiver<Input> recv, transmitter<Output> trans, Func foo)\n{\n Input in;\n while(recv.Receive(in)) // Receive returns false when communication ended.\n {\n if(not trans.Send(foo(in))) // Send forwards data, and returns false when communication is terminated.\n {\n return;\n } \n }\n}, ....);\n</code></pre>\n<p>You only need to figure out how to implement the messaging classes. I made mine via an additional shared control block class that manages the internal logic of how data transmission is performed between <code>transmitter</code> and <code>receiver</code>. Normally, one just needs a safe-thread queue of data but sometimes it is preferable to limit the size of the queue or forward data in different order according to some priorities or whatever. Or perhaps apply some minor conversion in between the operations (so that input type differs from output type).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T04:56:32.393",
"Id": "243703",
"ParentId": "243688",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "243703",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T22:34:55.767",
"Id": "243688",
"Score": "6",
"Tags": [
"c++",
"multithreading",
"producer-consumer",
"c++20"
],
"Title": "C++20 sort of infinite \"Consumer-Producer\""
}
|
243688
|
<p>Imagine we have a custom dictionary class which is derived from <code>Dictionary<string, object></code>. Dictionary is <em><strong>case-insensitive</strong></em> about keys and elements arrange is not important.
So what is the most optimized way to compare two instance of this class, or in another word what is the best override of
<code>Equals</code> method in this class.</p>
<p>I tried to use these two ways to implement this class. But i'm not sure which way is better than the other.
Please help me to choose the best way or correct me if i made any mistake.</p>
<p><em>First implementation:</em></p>
<pre><code>public class CustomeDictionary : Dictionary<string, object>
{
public CustomeDictionary() :
base(StringComparer.InvariantCultureIgnoreCase)
{
}
public CustomeDictionary(CustomeDictionary CustomeDictionary) :
base(CustomeDictionary, StringComparer.InvariantCultureIgnoreCase)
{
}
public bool Equals(CustomeDictionary other)
{
if (other is null)
return false;
if (Count != other.Count)
return false;
foreach (var (key, value) in this)
if (!other.ContainsKey(key) || !value.Equals(other[key]))
return false;
return true;
}
public override bool Equals(object? obj)
{
return Equals(obj as CustomeDictionary);
}
public override int GetHashCode()
{
return this.Sum(i => (i.Key.ToLower(), i.Value).GetHashCode());
}
}
</code></pre>
<p><em>The second way</em> was to use another class which is an implementation of
<code>IEqualityComparer<KeyValuePair<string, object>></code> which can help to use some efficient Linq methods like
<code>Except</code> to override the <code>Equals</code> and overload <code>==</code>.</p>
<p>The EqualityComparer CustomClass</p>
<pre><code>public class CustomKeyValuePair : IEqualityComparer<KeyValuePair<string, object>>
{
public bool Equals(KeyValuePair<string, object> x, KeyValuePair<string, object> y)
=> x.Equals(y);
public int GetHashCode(KeyValuePair<string, object> obj)
{
var (key, value) = obj;
return (key.ToLower(), value).GetHashCode();
}
}
</code></pre>
<p>and I have used it like below in Equals:</p>
<pre><code> public bool Equals(CustomHashTable other)
{
return this.Except(other, new CustomKeyValuePair()).Any();
}
</code></pre>
<p>Please help me to improve and refactor the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T00:40:11.543",
"Id": "478315",
"Score": "0",
"body": "Welcome to Code Review. We can provide suggestions on how to improve the code, however, we can't help you refactor the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T01:50:43.517",
"Id": "478316",
"Score": "0",
"body": "Why not using the `Comparer` instead ? it's already implemented in the dictionary class, and your class inherited it already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T09:54:37.743",
"Id": "478346",
"Score": "0",
"body": "What benefit would either have over standard data-constructs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T14:16:22.840",
"Id": "478363",
"Score": "1",
"body": "@pacmaninbw\nthat would be very helpful for me, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T16:22:45.897",
"Id": "478379",
"Score": "1",
"body": "What not just use `var dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T20:23:35.350",
"Id": "478389",
"Score": "0",
"body": "@RickDavin because we need some kinda structure and we re not able to use it, we need a custom structure, please"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T22:41:04.243",
"Id": "243689",
"Score": "1",
"Tags": [
"c#",
"comparative-review",
"hash-map"
],
"Title": "What is the best implementation of a ignore case dictionary In C#"
}
|
243689
|
<p>I was using <a href="https://en.wikipedia.org/wiki/Karatsuba_algorithm" rel="nofollow noreferrer">Karatsuba algorithm</a> to multiply two polynomials and return the coefficients and I am using java, we are asked to use arraylists here, however, my code is too complicated and it takes much longer to run than I expected, can anyone help me with reducing the running time and simplify my code? Thanks a lot!</p>
<pre><code>public static List<Long> smellCosmos(List<Long> a, List<Long> b) {
int n = a.size();
int n1 = a.size() / 2;
List<Long>c = new ArrayList<Long>();
if (n == 1) {
c.add(0, a.get(0) * b.get(0));
return c;
};
List<Long>ahigh = new ArrayList<Long>(n1);
List<Long>alow = new ArrayList<Long>(n1);
List<Long>amed = new ArrayList<Long>(n1);
List<Long>bhigh = new ArrayList<Long>(n1);
List<Long>blow = new ArrayList<Long>(n1);
List<Long>bmed = new ArrayList<Long>(n1);
for (int i = 0; i < n1; i++) {
ahigh.add(a.get(i));
alow.add(a.get(i + n1));
amed.add(alow.get(i) + ahigh.get(i));
bhigh.add(b.get(i));
blow.add(b.get(i + n1));
bmed.add(blow.get(i) + bhigh.get(i));
}
List<Long>chigh = smellCosmos(ahigh, bhigh);
List<Long>clow = smellCosmos(alow, blow);
List<Long>cmed = smellCosmos(amed, bmed);
for (int j = 0; j < n1; j++)
c.add(chigh.get(j));
for (int m = 0; m < cmed.size(); m++)
c.add(cmed.get(m) - chigh.get(m) - clow.get(m));
for (int g = cmed.size() - n1; g < clow.size(); g++)
c.add(clow.get(g));
for (int i = n1; i < chigh.size(); i++)
c.set(i, c.get(i) + chigh.get(i));
for (int i = 0; i < cmed.size() - n1; i++)
c.set(n1 * 2 + i, c.get(n1 * 2 + i) + clow.get(i));
return c;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T00:35:50.350",
"Id": "478313",
"Score": "0",
"body": "@RolandIllig Title has been edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T00:38:06.833",
"Id": "478314",
"Score": "0",
"body": "What is the `Karatsuba` algorithm? It might help reviewers if you explained or added a link to a description of the algorithm. Otherwise I think it is a good question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T02:55:18.070",
"Id": "478317",
"Score": "2",
"body": "In case `a` is guaranteed to be no shorter than `b`: document it in the code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T03:07:01.870",
"Id": "478320",
"Score": "3",
"body": "(Can you please add/hyperlink test cases/input&expected output?) There is [`subList(int fromIndex, int toIndex)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/ArrayList.html#subList(int,int))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T12:35:27.473",
"Id": "478354",
"Score": "1",
"body": "https://en.wikipedia.org/wiki/Karatsuba_algorithm ;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:11:13.377",
"Id": "478371",
"Score": "0",
"body": "I did not look deeply into it, but you *don't* want to use `Long`s for this, they are objects and will be autoboxed to `long` and back. Also `ArrayList`s grow as needed, you want arrays of `long`. Also, your variable names could be better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:50:35.790",
"Id": "478375",
"Score": "1",
"body": "I tried with example from [wikipedia](https://en.wikipedia.org/wiki/Karatsuba_algorithm) and seems not working with it. I join greybeard's request : please provide test cases/input & expected output."
}
] |
[
{
"body": "<h2>Reduce running time</h2>\n<ul>\n<li>Maybe you can use <code>subList</code> to prevent new lists that are basically a copy of a part of the input? This saves a lot of autoboxing (which I assume is the bottle neck, if the algorithm is implemented correctly). You could <em>profile</em> your application to see where most time is spend.</li>\n</ul>\n<p>For example: <code>ahigh = a.subList(0,n1);</code></p>\n<ul>\n<li><p>You can initialize List <code>c</code> with a size, as you know the length it will be.</p>\n</li>\n<li><p>Use <code>addAll</code> whenever you can, it will use the faster <code>System.arrayCopy</code> internally if possible.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T12:46:59.803",
"Id": "243713",
"ParentId": "243692",
"Score": "1"
}
},
{
"body": "<p>As it happens, there is already an implementation of Karatsuba multiplication in the implementation of BigInteger. Of course that's integer multiplication instead of polynomial multiplication, but they're very similar, apart from how they handle carries. You can read the source <a href=\"https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/math/BigInteger.java\" rel=\"nofollow noreferrer\">here</a>, look for <code>multiplyKaratsuba</code>. It's more of a high-level implementation, delegating the details of extracting the high/low halves and addition and the base-case multiplication. There are some things to learn from it, for example:</p>\n<ul>\n<li>It uses <code>int[]</code>, not <code>ArrayList<Long></code>. <code>int[]</code> instead of <code>long[]</code> is used because multiplying two <code>long</code>s is actually difficult, the lowest 64 bits of the result are easy enough to get, but what about the upper 64 bits? That detail is not important for polynomial multiplication, as there is no carry propagation to worry about. You could use <code>long[]</code>, which is a flat array of data, whereas <code>ArrayList<Long></code> is an array of pointers to individually allocated <code>Long</code>s, that's a significant amount of size overhead (2x to 3x) and is also associated with hard-to-profile time overhead (the cost of loading more data and following more pointers and allocating/GC-ing more objects is <em>diffuse</em>, it does not show up as a hot spot during profiling).</li>\n<li>The base case is not "a single element". Karatsuba multiplication is asymptotically faster than standard quadratic-time multiplication, but also has more overhead. For small inputs Karatsuba is slower, so it should only be used above some size threshold (which can be found experimentally).</li>\n</ul>\n<h1>Bugs</h1>\n<p>The current implementation does not deal with different-sized <code>a</code> and <code>b</code>. If <code>b</code> is longer, the extra part is cut off. If <code>a</code> is longer, well, that's a problem.</p>\n<p>Even if the original input <code>a</code> and <code>b</code> were the same size, the algorithm would normally be able to create different sized inputs to its recursive calls: when the size is uneven that would naturally happen, unless you add padding. That does not happen here, if the size of <code>a</code> is uneven one element is <em>dropped</em>.</p>\n<h1>Unusual ordering</h1>\n<p>It seems that the name <code>high</code> is given to the start of the array/list. Normally the low part would be there, so that <code>polynomial[i]</code> corresponds to the coefficient of x<sup>i</sup>. That way it is for example easier to add two polynomials, because the coefficients at the same index in the array have the same index in the polynomials - that would not be true in the flipped order and all sorts of offset-arithmetic needs to happen, it's confusing and easy to get wrong. Also, "leading zero coefficients" appear at the end of the array where it would be easier to drop/ignore them. It's not necessarily <em>wrong</em> to flip it around, but normally less convenient.</p>\n<p>I expect there are bugs due to this, but it's hard to tell.</p>\n<p>Using the usual ordering, naive (quadratic time) polynomial multiplication would look like this:</p>\n<pre><code>static long[] multiplyPolynomials(long[] a, long[] b) {\n long[] c = new long[a.length + b.length - 1];\n for (int i = 0; i < a.length; i++)\n for (int j = 0; j < b.length; j++)\n c[i + j] += a[i] * b[j];\n return c;\n}\n</code></pre>\n<p>Which you can also use to test the more advanced implementations against.</p>\n<h1>Repeated in-line operations</h1>\n<p>Extracting the low and high parts, as well as creating the "low + high" polyomial, could be put in their own functions, to clean up the main function.</p>\n<p>Some of the loops can be written as <code>System.arrayCopy</code>.</p>\n<h1>Suggested implementation</h1>\n<p>Putting those things together, the code might end up like this:</p>\n<pre><code>static long[] getLow(long[] a, int half)\n{\n long[] low = new long[half];\n System.arraycopy(a, 0, low, 0, low.length);\n return low;\n}\n\nstatic long[] getHigh(long[] a, int half)\n{\n long[] high = new long[a.length - half];\n System.arraycopy(a, half, high, 0, high.length);\n return high;\n}\n\nstatic long[] addPolynomials(long[] a, long[] b) {\n if (a.length < b.length) {\n long[] t = a;\n a = b;\n b = t;\n }\n long[] result = new long[a.length];\n for (int i = 0; i < b.length; i++)\n result[i] = a[i] + b[i];\n System.arraycopy(a, b.length, result, b.length, a.length - b.length);\n return result;\n}\n\npublic static long[] multiplyPolynomialsKaratsuba(long[] a, long[] b) {\n \n long[] c = new long[a.length + b.length - 1];\n if (a.length * b.length < 1000) {\n \n for (int i = 0; i < a.length; i++)\n for (int j = 0; j < b.length; j++)\n c[i + j] += a[i] * b[j];\n return c;\n }\n\n int half = (Math.max(a.length, b.length) + 1) / 2;\n long[] alow = getLow(a, half);\n long[] blow = getLow(b, half);\n long[] ahigh = getHigh(a, half);\n long[] bhigh = getHigh(b, half);\n long[] amed = addPolynomials(alow, ahigh);\n long[] bmed = addPolynomials(blow, bhigh);\n\n long[] clow = multiplyPolynomialsKaratsuba(alow, blow);\n System.arraycopy(clow, 0, c, 0, clow.length);\n \n long[] chigh = multiplyPolynomialsKaratsuba(ahigh, bhigh);\n System.arraycopy(chigh, 0, c, 2 * half, chigh.length);\n \n long[] cmed = multiplyPolynomialsKaratsuba(amed, bmed);\n for (int j = 0; j < cmed.length; j++)\n c[j + half] += cmed[j] - (j < chigh.length ? chigh[j] : 0) - (j < clow.length ? clow[j] : 0);\n\n return c;\n}\n</code></pre>\n<p>I did some minor benchmarking, choosing both polynomials to be the same size, and a power of two size, which is the only case in which the old implementation does the right thing (or the right amount of work at least). The new code was tested with a threshold of 2 and with a threshold of 1000 (which looked like a good value to choose).</p>\n<pre><code> Old Thr2 Thr1000\n 256 2ms 0.7ms 0.1ms\n 512 5ms 1ms 0.5ms\n 1024 14ms 4ms 1ms\n 2048 40ms 11ms 3ms\n 4096 125ms 32ms 10ms\n 8192 360ms 100ms 29ms\n16384 1100ms 270ms 85ms\n</code></pre>\n<p>So I think we safely conclude that about a factor of 3 is thanks to not applying Karatsuba all the way down single elements, and about an other factor of 4 is thanks to everything else.</p>\n<p>The times are plotted below on a log-log plot so you can see the scaling is about right.</p>\n<p><a href=\"https://i.stack.imgur.com/R0cPs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/R0cPs.png\" alt=\"time plot\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T13:37:49.423",
"Id": "244165",
"ParentId": "243692",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T23:17:02.257",
"Id": "243692",
"Score": "5",
"Tags": [
"java",
"performance",
"beginner",
"algorithm",
"recursion"
],
"Title": "How to optimize Karatsuba algorithm (using arraylist and java)"
}
|
243692
|
<p>I am new to Rust, so I created a mini library/wrapper for creating multi-cliented Tcp Servers. This is a starter project for me to learn Rust.</p>
<p>How the module works is a user can pass in a function or closure to the start fn to use to handle each new client's connection, the function has to accept HandleClientType as a parameter, which is a type alias for (TcpStream, BubbleServer), so a tuple that contains the newly connected TcpStream and a reference to the server that is calling this function.</p>
<p>I'd like to know how I could improve it's performance and improving it's overall design (some details in the comments) and if there is anyways to simplify my code.</p>
<p>If you wanted to compile this for yourself, a full crate for the module and the main example (also a crate for the TCP client) is provided <a href="https://github.com/jessebadry/BubbleServer" rel="nofollow noreferrer">here</a></p>
<p>The Module in question:</p>
<p><strong>buble_host/mod.rs:</strong></p>
<pre><code>use std::io;
use std::io::{Error, ErrorKind};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::sync::*;
use std::thread;
use std::vec::Vec;
#[cfg(feature = "bubble_dbg")]
macro_rules! bubble_print{
($($args:expr), *)=> {println!($($args), *);}
}
#[cfg(not(feature = "bubble_dbg"))]
macro_rules! bubble_print {
($($args:expr), *) => {};
}
//Events for debugging and getting information from the server.
pub enum ServerEvent {
None,
Disconnection(SocketAddr),
}
type ErrorSender = Option<Sender<ServerEvent>>;
//Clients List Thread Safe
pub type ClientsListTS = Arc<Mutex<Vec<TcpStream>>>;
pub type ClientsVec = Vec<TcpStream>;
pub type HandleClientCallBack = dyn Fn(HandleClientType) + Send + Sync + 'static;
//Helper struct
struct ClientsList(ClientsListTS);
impl ClientsList {
pub fn new() -> ClientsListTS {
Arc::new(Mutex::new(Vec::<TcpStream>::new()))
}
}
///Data that is sent to user provided FnMut `set in fn start` when a client connects to a started(fn start) server
pub type HandleClientType<'a> = (&'a mut TcpStream, &'a mut BubbleServer);
#[derive(Clone)]
pub struct BubbleServer {
ip: String,
error_sender: ErrorSender,
clients: ClientsListTS,
}
impl BubbleServer {
pub fn new(ip: String) -> Self {
BubbleServer {
ip,
clients: ClientsList::new(),
error_sender: None,
}
}
fn get_sock_index(
clients: &ClientsVec,
socket_addr: &std::net::SocketAddr,
) -> io::Result<usize> {
clients
.iter()
.position(|x| &x.peer_addr().unwrap() == socket_addr)
.ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
format!("Could not find socket address: '{}' ", socket_addr),
)
})
}
/// used to retrieve socket from clients by ip address
/// # Example :
/// ```
/// let server = BubbleServer::new(String::from("localhost:25568"));
/// let addr_to_find: SocketAddr = "127.0.0.1:25565"
/// .parse()
/// .expect("Could not parse ip address!");
/// let socket = server.get_sock(&addr_to_find);
/// assert!(socket.is_none());
///
/// ```
///
#[allow(dead_code)]
pub fn get_sock(&self, socket_addr: &SocketAddr) -> Option<TcpStream> {
let clients = self.get_clients().ok()?;
let clients = clients.lock().ok()?;
if let Ok(index) = BubbleServer::get_sock_index(&clients, socket_addr) {
Some(clients[index].try_clone().unwrap())
} else {
None
}
}
///`handle_socket_disconnection` will shutdown the socket, then send a disconnection event to the error_sender.
fn handle_socket_disconnection(&self, socket_: &TcpStream) -> io::Result<()> {
self.remove_socket(&socket_)?;
let sock_addr = socket_.peer_addr().unwrap();
socket_
.shutdown(Shutdown::Both)
.expect("Could not shutdown stream..");
let event = ServerEvent::Disconnection(sock_addr);
let sender = self.error_sender.as_ref();
if let Some(sender) = sender {
sender
.send(event)
.unwrap_or_else(|e| println!("error sending to error_sender {}", e));
}
bubble_print!("Removed client {}", &sock_addr.to_string());
Ok(())
}
/// `get_clients` Returns clients list reference using Arc;
pub fn get_clients(&self) -> io::Result<ClientsListTS> {
Ok(Arc::clone(&self.clients))
}
#[allow(dead_code)]
pub fn set_on_event<F: Fn(ServerEvent) + Send + Sync + 'static>(&self, callback: F) {
let (err_send, err_rec) = channel::<ServerEvent>();
self.error_sender.as_ref().get_or_insert(&err_send);
let call = Arc::new(callback);
std::thread::spawn(move || loop {
let event = err_rec.recv().unwrap_or(ServerEvent::None);
call(event);
});
}
///
///####`remove_socket` Removes given TcpStream from server's `clients`
///
/// * Locks `clients` vec (Vec<TcpStream>)
/// * Removes `socket` from clients list.
fn remove_socket(&self, socket: &TcpStream) -> io::Result<()> {
//Is this the least verbose way to dereference this?
let clients = self.get_clients()?;
let mut clients = clients
.lock()
.map_err(|err| io::Error::new(ErrorKind::Other, err.to_string()))?;
//
let socket_addr = socket.peer_addr()?;
let index = BubbleServer::get_sock_index(&clients, &socket_addr)?;
clients.remove(index);
Ok(())
}
///Runs the user's defined function in a new thread passing in the newly connected socket.
fn handle_client(
&self,
socket: &mut TcpStream,
handle_client: &'static HandleClientCallBack,
) -> io::Result<()> {
let mut socket_ = socket.try_clone()?;
//Again, I hate this cloning
let mut _self = self.clone();
//Need to clone provided function
let handle_client_func = handle_client.clone();
thread::spawn(move || {
handle_client_func((&mut socket_, &mut _self));
_self
.handle_socket_disconnection(&socket_)
.unwrap_or_else(|e| {
println!("Error in handling socket disconnection, Err: '{}' ", e);
});
});
Ok(())
}
///Locks `clients` (Vec<TcpStream>) and adds `socket` to Vec
fn add_client(&self, socket: TcpStream) {
self.clients.lock().unwrap().push(socket);
}
/// Continously accepts incoming connections
/// * Is non blocking.
/// * Locks clients list when user connects
pub fn start(&self, handle_client_cb: &'static HandleClientCallBack) -> io::Result<()> {
let ip = &self.ip;
bubble_print!("server with ip of {} has started...", ip);
let socket_acceptor = TcpListener::bind(ip).expect("Failed to initialize server...");
//I'm not a fan of cloning the server struct, but I didn't want the user to have the potential to deadlock the server
//without explicitily locking mutex's in their own code.
//for example it should be obvious that this will deadlock when a user connects
// ```
// {
// let server = BubbleServer::new(String::from("localhost:25568"));
// let clients = server.get_clients().expect("could not get clients!");
// let clients = clients.lock().unwrap();
// server.start(&|data: HandleClientType| {
// println!("new connection! dropping now!");
// });
// thread::park();
// }
// ```
let self_ = self.clone();
// Accept new incoming connections
thread::spawn(move || loop {
let h_cb_clone = handle_client_cb.clone();
println!("waiting for next client..");
if let Ok((mut socket, _)) = socket_acceptor.accept() {
//Add Client to the clients vector
self_.add_client(
socket
.try_clone()
.expect("Could not clone socket before handling socket.."),
);
//Run user's implementation on how to deal with new client
self_
.handle_client(&mut socket, h_cb_clone)
.unwrap_or_else(|e| {
println!("Error in handle_client : {}", e);
});
}
// Could provide implementation for an erroneous accept, and send that to the error_sender.
// but if many clients were to make erroneous connections this might just clutter the error_sender's receive.
});
Ok(())
}
}
</code></pre>
<p><strong>main.rs</strong> shows an example of how I create a TextChat server with this module</p>
<p><strong>main.rs:</strong></p>
<pre><code>mod bubble_host;
use crate::bubble_host::{BubbleServer, HandleClientType, ServerEvent};
use std::io;
use std::io::prelude::*;
use std::io::{Error, ErrorKind};
use std::net::TcpStream;
use std::thread;
///Example implementation of BubbleServer
trait TextChatServer {
fn broad_cast_msg(&mut self, msg: &[u8]) -> Result<(), std::io::Error>;
}
impl TextChatServer for BubbleServer {
fn broad_cast_msg(&mut self, msg: &[u8]) -> Result<(), std::io::Error> {
let clients = self.get_clients()?;
let clients = clients
.lock()
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?;
for mut client in clients.iter() {
if let Err(e) = client.write_all(&msg) {
println!(
"Error {} for {}",
e,
client.peer_addr().unwrap().to_string()
)
}
}
Ok(())
}
}
fn read_stream(stream: &mut TcpStream, recv_buf: &mut [u8], read_bytes: &mut usize) -> usize {
*read_bytes = match stream.read(recv_buf) {
Ok(read_bytes) => read_bytes,
Err(_) => 0,
};
*read_bytes
}
trait TcpHelper {
fn send_str(&mut self, msg: &str) -> io::Result<()>;
}
impl TcpHelper for TcpStream {
fn send_str(&mut self, msg: &str) -> io::Result<()> {
let data = msg.as_bytes();
self.write_all(&data)?;
Ok(())
}
}
//This Function will be called and ran in a new thread every time a new user connects.
fn handle_new_text_client(client_data: HandleClientType) {
// HandleClientType provides the stream that is being handled and the server it's being called from so the user could access functions from the server
let buffer_size = 1000;
let (stream, server_reference) = client_data;
println!(
"Client connected!! ip {}",
stream.peer_addr().unwrap().to_string()
);
stream
.send_str(&stream.peer_addr().unwrap().to_string())
.unwrap_or_else(|err| {
println!(
"err writing ip to stream, ip {}, err :{}",
&stream.peer_addr().unwrap().to_string(),
err
)
});
let mut recv_buf = vec![0u8; buffer_size];
let mut bytes_read: usize = 0;
while read_stream(stream, &mut recv_buf, &mut bytes_read) > 0 {
if let Err(e) = server_reference.broad_cast_msg(&recv_buf[..bytes_read]) {
println!("Error: {}", e);
};
}
}
fn main() {
let server = BubbleServer::new(String::from("localhost:25568"));
//Receive events from Server
server.set_on_event(|event: ServerEvent| match event {
ServerEvent::Disconnection(socket_addr) => println!("Disconnection from {}", socket_addr),
_ => (),
});
if let Err(e) = server.start(&handle_new_text_client) {
println!("Error starting server: {}", e);
};
//Blocks this thread here as server.start runs in another thread
thread::park();
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code seems to be pretty solid and following best practices, so these are going to be fairly nit-picky.</p>\n<h1>Use consistent spacing</h1>\n<p>You seem to be using <code>rustfmt</code>, so that's good. However, main.rs appears to be using tabs and bubble_host is using tabs. It's fine to use either, but don't mix and match them.</p>\n<p>Additionally, markdown headings typically have spacing after them. So instead of:</p>\n<pre><code>///\n///####`remove_socket` Removes given TcpStream from server's `clients`\n///\n/// * Locks `clients` vec (Vec<TcpStream>)\n/// * Removes `socket` from clients list.\n</code></pre>\n<p>In fact, that doesn't even render correctly when using docs.rs: it shows a verbatim <code>####</code>. Instead, write:</p>\n<pre><code>/// #### `remove_socket` Removes given TcpStream from server's `clients`\n///\n/// * Locks `clients` vec (Vec<TcpStream>)\n/// * Removes `socket` from clients list.\n</code></pre>\n<p>However, typically, you don't begin with the function name in its own documentation.</p>\n<h1>Link in your docs</h1>\n<p>When building your documentation with a nightly compiler, as <a href=\"https://docs.rs\" rel=\"nofollow noreferrer\">docs.rs</a> does, simply placing code tags in brackets will automatically create a link to it. So if your docs look like:</p>\n<pre><code>This is a description that mentions `TcpStream`\n</code></pre>\n<p>You can change it to:</p>\n<pre><code>This is a description that mentions [`TcpStream`]\n</code></pre>\n<p>And a link will automatically be created in the generated docs. If the type isn't available locally, or you'd like to describe it with different words, you can do:</p>\n<pre><code>If `TcpStream` is at the root level:\n[`TcpStream`][crate::TcpStream]\nDescribe it with [other words][crate::TcpStream] that aren't code\n</code></pre>\n<h1>Use the <a href=\"https://docs.rs/log/\" rel=\"nofollow noreferrer\"><code>log</code></a> crate</h1>\n<p>Instead of</p>\n<pre><code>#[cfg(feature = "bubble_dbg")]\nmacro_rules! bubble_print{\n ($($args:expr), *)=> {println!($($args), *);}\n\n}\n#[cfg(not(feature = "bubble_dbg"))]\nmacro_rules! bubble_print {\n ($($args:expr), *) => {};\n}\n\nbubble_print!("Removed client {}", &sock_addr.to_string());\n</code></pre>\n<p>Use the <code>debug!</code> macro (or another macro corresponding to your log level):</p>\n<pre><code>debug!("Removed client {}", &sock_addr.to_string());\n</code></pre>\n<p>That way, end users can choose to change log levels and enable/disable logging at runtime in a standard manner.</p>\n<h1>Run <a href=\"https://github.com/rust-lang/rust-clippy\" rel=\"nofollow noreferrer\"><code>cargo clippy</code></a></h1>\n<p>clippy helps fix some problems in your code, so let's take a look at what it suggests.</p>\n<h2>methods called <code>new</code> usually return <code>Self</code></h2>\n<pre><code>warning: methods called `new` usually return `Self`\n --> src/bubble_host.rs:33:5\n |\n33 | / pub fn new() -> ClientsListTS {\n34 | | Arc::new(Mutex::new(Vec::<TcpStream>::new()))\n35 | | }\n | |_____^\n |\n = note: `#[warn(clippy::new_ret_no_self)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#new_ret_no_self\n</code></pre>\n<p>Looking at that code:</p>\n<pre><code>pub type ClientsListTS = Arc<Mutex<Vec<TcpStream>>>;\n\n//Helper struct\nstruct ClientsList(ClientsListTS);\nimpl ClientsList {\n pub fn new() -> ClientsListTS {\n Arc::new(Mutex::new(Vec::<TcpStream>::new()))\n }\n}\n</code></pre>\n<p>That's a bit unusual. In fact, you don't need that at all! The <a href=\"https://doc.rust-lang.org/nightly/core/default/trait.Default.html\" rel=\"nofollow noreferrer\"><code>Default</code></a> trait can be <code>derive</code>d manually, but many things derive it automatically. Specifically, <code>Arc</code> implements it if what it holds does. <code>Mutex</code> implements it if what it holds does. So, does <code>Vec</code> implement <code>Default</code>? <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-Default\" rel=\"nofollow noreferrer\">Sure does</a>! So instead of</p>\n<pre><code>BubbleServer {\n ip,\n clients: ClientsList::new(),\n error_sender: None,\n}\n</code></pre>\n<p>You can write</p>\n<pre><code>BubbleServer {\n ip,\n clients: Default::default(),\n error_sender: None,\n}\n</code></pre>\n<p>And get rid of <code>ClientsList</code> entirely. However, even if that wasn't available, you still shouldn't use that pattern—either make <code>ClientsList</code> a wrapper struct that you actually use, or create a new freestanding function that creates a new <code>ClientsListTS</code>.</p>\n<h2>writing <code>&Vec<_></code> instead of <code>&[_]</code> involves one more reference and cannot be used with non-Vec-based slices.</h2>\n<pre><code>warning: writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used with non-Vec-based slices.\n --> src/bubble_host.rs:58:18\n |\n58 | clients: &ClientsVec,\n | ^^^^^^^^^^^\n |\n = note: `#[warn(clippy::ptr_arg)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg\n</code></pre>\n<p>Here, you're forcing the caller to have a <code>Vec</code> of clients. <strong>Generally, you should never take a reference to a <code>Vec</code></strong>. Instead, just write <code>&[TcpStream]</code>.</p>\n<h2>using <code>clone</code> on a double-reference; this will copy the reference instead of cloning the inner type</h2>\n<pre><code>error: using `clone` on a double-reference; this will copy the reference instead of cloning the inner type\n --> src/bubble_host.rs:155:34\n |\n155 | let handle_client_func = handle_client.clone();\n | ^^^^^^^^^^^^^^^^^^^^^\n |\n = note: `#[deny(clippy::clone_double_ref)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#clone_double_ref\n</code></pre>\n<p>Why are you cloning the callback? Cloning a reference of a type that doesn't implement <code>Clone</code>, which you do, does nothing. However, you should generally use generics for this type of thing, as there could be issues if you want to use a closure—you currently require that you pass a <code>static</code> reference, which may not be possible. Instead, do:</p>\n<pre><code>fn handle_client(\n...,\nhandle_client: impl Fn(HandleClientType) + Send + 'static,\n)\n</code></pre>\n<p>There's also no need for it to be <code>Sync</code>, because it's only ever sent across a thread boundary, not shared.</p>\n<h1>Don't send to many clients one-after-another</h1>\n<pre><code>for mut client in clients.iter() {\n if let Err(e) = client.write_all(&msg) {\n println!(\n "Error {} for {}",\n e,\n client.peer_addr().unwrap().to_string()\n )\n }\n}\n</code></pre>\n<p>What if a client is on a 1 bit per second connection? That's still fast enough for the OS to still leave a connection open (default timeouts are generally in the hours), but they would slow stuff down for every client after them. <code>async</code>/<code>await</code> would fix that, but I understand that you're just learning and don't want to get into that just yet. So instead, the way it's typically done is to have one thread per connection, and then loop over a bunch of <code>mpsc</code>s to send to it. You should also move to a <code>RwLock</code> instead of a <code>Mutex</code>, as that would allow you to have many threads doing non-destructive reading and writing, although you'll need to put in some work in to make sure that you're not waiting forever to write to it.</p>\n<p>However, you could replace that entire thing with a concurrent hashmap, like <a href=\"https://docs.rs/dashmap/3/dashmap/struct.DashMap.html\" rel=\"nofollow noreferrer\"><code>DashMap</code></a>. You could store an <code>AtomicU64</code> that you increase every client, add that as the key and the <code>Sender</code> for the <code>mpsc</code> of the broadcast thread, then just remove the key when the client disconnects.</p>\n<h1>Final code</h1>\n<h2>main.rs</h2>\n<pre><code>mod bubble_host;\nuse crate::bubble_host::{BubbleServer, HandleClientType, ServerEvent};\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::{Error, ErrorKind};\nuse std::net::TcpStream;\nuse std::thread;\n\n///Example implementation of BubbleServer\n\ntrait TextChatServer {\n fn broad_cast_msg(&mut self, msg: &[u8]) -> Result<(), std::io::Error>;\n}\nimpl TextChatServer for BubbleServer {\n fn broad_cast_msg(&mut self, msg: &[u8]) -> Result<(), std::io::Error> {\n let clients = self.get_clients()?;\n let clients = clients\n .lock()\n .map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?;\n\n for mut client in clients.iter() {\n if let Err(e) = client.write_all(&msg) {\n println!(\n "Error {} for {}",\n e,\n client.peer_addr().unwrap().to_string()\n )\n }\n }\n Ok(())\n }\n}\nfn read_stream(stream: &mut TcpStream, recv_buf: &mut [u8], read_bytes: &mut usize) -> usize {\n *read_bytes = match stream.read(recv_buf) {\n Ok(read_bytes) => read_bytes,\n Err(_) => 0,\n };\n *read_bytes\n}\ntrait TcpHelper {\n fn send_str(&mut self, msg: &str) -> io::Result<()>;\n}\nimpl TcpHelper for TcpStream {\n fn send_str(&mut self, msg: &str) -> io::Result<()> {\n let data = msg.as_bytes();\n self.write_all(&data)?;\n Ok(())\n }\n}\n//This Function will be called and ran in a new thread every time a new user connects.\nfn handle_new_text_client(client_data: HandleClientType) {\n // HandleClientType provides the stream that is being handled and the server it's being called from so the user could access functions from the server\n let buffer_size = 1000;\n let (stream, server_reference) = client_data;\n println!(\n "Client connected!! ip {}",\n stream.peer_addr().unwrap().to_string()\n );\n stream\n .send_str(&stream.peer_addr().unwrap().to_string())\n .unwrap_or_else(|err| {\n println!(\n "err writing ip to stream, ip {}, err :{}",\n &stream.peer_addr().unwrap().to_string(),\n err\n )\n });\n let mut recv_buf = vec![0u8; buffer_size];\n let mut bytes_read: usize = 0;\n while read_stream(stream, &mut recv_buf, &mut bytes_read) > 0 {\n if let Err(e) = server_reference.broad_cast_msg(&recv_buf[..bytes_read]) {\n println!("Error: {}", e);\n };\n }\n}\n\nfn main() {\n env_logger::init();\n let server = BubbleServer::new(String::from("localhost:25568"));\n //Receive events from Server\n server.set_on_event(|event: ServerEvent| match event {\n ServerEvent::Disconnection(socket_addr) => println!("Disconnection from {}", socket_addr),\n _ => (),\n });\n if let Err(e) = server.start(&handle_new_text_client) {\n println!("Error starting server: {}", e);\n };\n //Blocks this thread here as server.start runs in another thread\n thread::park();\n}\n</code></pre>\n<h2>bubble_host.rs</h2>\n<pre><code>use std::io;\nuse std::io::{Error, ErrorKind};\nuse std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};\nuse std::sync::mpsc::{channel, Sender};\nuse std::sync::*;\nuse std::thread;\nuse std::vec::Vec;\nuse log::debug;\n\n/// Events for debugging and getting information from the server.\npub enum ServerEvent {\n None,\n Disconnection(SocketAddr),\n}\ntype ErrorSender = Option<Sender<ServerEvent>>;\n\n/// Clients List Thread Safe\npub type ClientsListTS = Arc<Mutex<Vec<TcpStream>>>;\n\n/// Data that is sent to user provided FnMut `set in fn start` when a client connects to a\n/// started(fn start) server\npub type HandleClientType<'a> = (&'a mut TcpStream, &'a mut BubbleServer);\n\n#[derive(Clone)]\npub struct BubbleServer {\n ip: String,\n error_sender: ErrorSender,\n clients: ClientsListTS,\n}\n\nimpl BubbleServer {\n pub fn new(ip: String) -> Self {\n BubbleServer {\n ip,\n clients: Default::default(),\n error_sender: None,\n }\n }\n\n fn get_sock_index(\n clients: &[TcpStream],\n socket_addr: &std::net::SocketAddr,\n ) -> io::Result<usize> {\n clients\n .iter()\n .position(|x| &x.peer_addr().unwrap() == socket_addr)\n .ok_or_else(|| {\n Error::new(\n ErrorKind::InvalidInput,\n format!("Could not find socket address: '{}' ", socket_addr),\n )\n })\n }\n /// used to retrieve socket from clients by ip address\n /// # Example:\n /// ```\n /// let server = BubbleServer::new(String::from("localhost:25568"));\n /// let addr_to_find: SocketAddr = "127.0.0.1:25565"\n /// .parse()\n /// .expect("Could not parse ip address!");\n /// let socket = server.get_sock(&addr_to_find);\n /// assert!(socket.is_none());\n /// ```\n #[allow(dead_code)]\n pub fn get_sock(&self, socket_addr: &SocketAddr) -> Option<TcpStream> {\n let clients = self.get_clients().ok()?;\n let clients = clients.lock().ok()?;\n if let Ok(index) = BubbleServer::get_sock_index(&clients, socket_addr) {\n Some(clients[index].try_clone().unwrap())\n } else {\n None\n }\n }\n\n /// Shutdown the socket, then send a disconnection event to the `error_sender`.\n fn handle_socket_disconnection(&self, socket: &TcpStream) -> io::Result<()> {\n self.remove_socket(&socket)?;\n let sock_addr = socket.peer_addr().unwrap();\n\n socket\n .shutdown(Shutdown::Both)\n .expect("Could not shutdown stream..");\n let event = ServerEvent::Disconnection(sock_addr);\n let sender = self.error_sender.as_ref();\n if let Some(sender) = sender {\n sender\n .send(event)\n .unwrap_or_else(|e| println!("error sending to error_sender {}", e));\n }\n debug!("Removed client {}", sock_addr);\n Ok(())\n }\n\n /// `get_clients` Returns clients list reference using [`Arc::clone`].\n pub fn get_clients(&self) -> io::Result<ClientsListTS> {\n Ok(Arc::clone(&self.clients))\n }\n #[allow(dead_code)]\n pub fn set_on_event<F: Fn(ServerEvent) + Send + Sync + 'static>(&self, callback: F) {\n let (err_send, err_rec) = channel::<ServerEvent>();\n self.error_sender.as_ref().get_or_insert(&err_send);\n let call = Arc::new(callback);\n std::thread::spawn(move || loop {\n let event = err_rec.recv().unwrap_or(ServerEvent::None);\n call(event);\n });\n }\n /// Removes given TcpStream from server's `clients`\n ///\n /// * Locks `clients` vec ([`Vec`]`<`[`TcpStream`]`>`)\n /// * Removes `socket` from clients list.\n fn remove_socket(&self, socket: &TcpStream) -> io::Result<()> {\n //Is this the least verbose way to dereference this?\n let clients = self.get_clients()?;\n let mut clients = clients\n .lock()\n .map_err(|err| io::Error::new(ErrorKind::Other, err.to_string()))?;\n\n let socket_addr = socket.peer_addr()?;\n\n let index = BubbleServer::get_sock_index(&clients, &socket_addr)?;\n clients.remove(index);\n Ok(())\n }\n /// Runs the user's defined function in a new thread passing in the newly connected socket.\n fn handle_client(\n &self,\n socket: &mut TcpStream,\n handle_client: impl Fn(HandleClientType) + Send + 'static,\n ) -> io::Result<()> {\n let mut socket = socket.try_clone()?;\n let mut _self = self.clone();\n thread::spawn(move || {\n handle_client((&mut socket, &mut _self));\n\n _self\n .handle_socket_disconnection(&socket)\n .unwrap_or_else(|e| {\n println!("Error in handling socket disconnection, Err: '{}' ", e);\n });\n });\n Ok(())\n }\n ///Locks `clients` ([`Vec`]`<`[`TcpStream`]`>`) and adds `socket` to Vec\n fn add_client(&self, socket: TcpStream) {\n self.clients.lock().unwrap().push(socket);\n }\n\n /// Continously accepts incoming connections\n /// * Is non blocking.\n /// * Locks clients list when user connects\n pub fn start(&self, handle_client_cb: impl Fn(HandleClientType) + Send + Clone + 'static) -> io::Result<()> {\n let ip = &self.ip;\n debug!("server with ip of {} has started...", ip);\n let socket_acceptor = TcpListener::bind(ip).expect("Failed to initialize server...");\n\n //I'm not a fan of cloning the server struct, but I didn't want the user to have the potential to deadlock the server\n //without explicitly locking mutex's in their own code.\n //for example it should be obvious that this will deadlock when a user connects\n // ```\n // {\n // let server = BubbleServer::new(String::from("localhost:25568"));\n // let clients = server.get_clients().expect("could not get clients!");\n // let clients = clients.lock().unwrap();\n // server.start(&|data: HandleClientType| {\n // println!("new connection! dropping now!");\n // });\n\n // thread::park();\n // }\n // ```\n let self_ = self.clone();\n\n // Accept new incoming connections\n thread::spawn(move || loop {\n println!("waiting for next client..");\n if let Ok((mut socket, _)) = socket_acceptor.accept() {\n //Add Client to the clients vector\n self_.add_client(\n socket\n .try_clone()\n .expect("Could not clone socket before handling socket.."),\n );\n //Run user's implementation on how to deal with new client\n self_\n .handle_client(&mut socket, handle_client_cb.clone())\n .unwrap_or_else(|e| {\n println!("Error in handle_client : {}", e);\n });\n }\n // Could provide implementation for an erroneous accept, and send that to the error_sender.\n // but if many clients were to make erroneous connections this might just clutter the error_sender's receive.\n });\n Ok(())\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T19:12:23.927",
"Id": "529963",
"Score": "0",
"body": "Great feedback that is very useful for others to learn!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T03:51:28.107",
"Id": "243700",
"ParentId": "243693",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243700",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T00:08:28.673",
"Id": "243693",
"Score": "3",
"Tags": [
"performance",
"multithreading",
"rust"
],
"Title": "Rust multi-cliented TCP Server library"
}
|
243693
|
<p>I have an implementation of depth first search, which I want to test using the <code>pytest</code> framework.</p>
<p>I would be making test cases for other graph algorithms, and would like to know if this approach is good enough to be replicated on similar programs.</p>
<p>Here is what it looks like currently:
(This may not be a very exhaustive set of test cases, but my goal is to separate simple checks that are done in the actual implementation)</p>
<pre><code>import pytest
from dfs import dfs_recursive, dfs_iterative
def test_data():
test_graph = {
'A' : ['B','S'],
'B' : ['A'],
'C' : ['D','E','F','S'],
'D' : ['C'],
'E' : ['C','H'],
'F' : ['C','G'],
'G' : ['F','S'],
'H' : ['E','G'],
'S' : ['A','C','G']
}
assert dfs_iterative(test_graph, 'A') is not None
assert len(dfs_iterative(test_graph, 'A')) == len(list(test_graph.keys()))
assert dfs_recursive(test_graph, 'A') is not None
assert len(dfs_recursive(test_graph, 'A')) == len(list(test_graph.keys()))
def test_graph():
test_graph = {
1: [2, 3]
}
if len(test_graph.keys()) < 2:
print("\nA graph has to have atleast 2 vertices")
def all_unique(x):
"""
Check if all elements in a list are unique; if not exit erly
"""
seen = set()
return not any(i in seen or seen.add(i) for i in x)
def test_unique():
test_graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
assert all_unique(dfs_iterative(test_graph, 'A')) is True
assert all_unique(dfs_recursive(test_graph, 'A')) is True
def test_vertex1():
test_graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
with pytest.raises(KeyError) as excinfo:
dfs_iterative(test_graph, 'Z')
assert 'Z' in str(excinfo.value)
assert 'KeyError' in str(excinfo.type)
print('\nVertex does not exist')
def test_vertex2():
test_graph = {
1: [2, 3],
2: [2, 3, 4],
3: [],
4: [],
}
for key, value in test_graph.items():
if key in value:
pytest.fail("A vertex cannot point to itself") # explicitly fails this test
</code></pre>
<p>Please suggest any changes, additions or improvements.</p>
|
[] |
[
{
"body": "<p>Three observations:</p>\n<ol>\n<li>There are two many <code>assert</code> statements in a single test function. Ideally each function should only test one thing. That way when the test fails you know exactly what is wrong.</li>\n<li>Instead of initializing test data in the test function, you can write <code>fixtures</code>. Each fixture can be used in multiple test functions.</li>\n<li>You don't need to <code>assert 'KeyError' in str(excinfo.type)</code> since you already has <code>with pytest.raises(KeyError)</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T01:55:54.720",
"Id": "243696",
"ParentId": "243695",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243696",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T01:23:06.917",
"Id": "243695",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"unit-testing"
],
"Title": "Testing Depth First Search Using Pytest"
}
|
243695
|
<p>I'm using the following handler to resolve assemblies in a specifically named subfolder of the main assembly's folder.</p>
<p>I am looking for improvements in:</p>
<ul>
<li>clarity</li>
<li>correctedness</li>
<li>flexibility, as long as it doesn't conflict with other goals of this code</li>
</ul>
<p>The code does not need to be thread-safe as the intended environment is single-threaded.</p>
<pre><code>using System;
using System.Linq;
using System.Reflection;
using static System.IO.Path;
using static System.StringComparison;
using static System.Reflection.Assembly;
using System.IO;
namespace Periscope.Debuggee {
public static class SubfolderAssemblyResolver {
public static void Hook(string subfolderKey) {
if (subfolderKey.IsNullOrWhiteSpace()) { return; }
if (subfolderPath.IsNullOrWhiteSpace()) { return; }
subfolderPath = Combine(
GetDirectoryName(GetCallingAssembly().Location),
subfolderKey
);
basePath = GetDirectoryName(subfolderPath);
AppDomain.CurrentDomain.AssemblyResolve += resolver;
}
private static bool IsNullOrWhitespace([NotNullWhen(false)]this string? s) => string.IsNullOrWhiteSpace(s);
private static bool EndsWithAny(this string s, StringComparison comparisonType, params string[] testStrings) => testStrings.Any(x => s.EndsWith(x, comparisonType));
private static readonly string[] exclusions = new[] { ".xmlserializers", ".resources" };
private static readonly string[] patterns = new[] { "*.dll", "*.exe" };
private static string? basePath;
private static string? subfolderPath;
private static Assembly? resolver(object sender, ResolveEventArgs e) {
var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == e.Name);
if (loadedAssembly is { }) { return loadedAssembly; }
var n = new AssemblyName(e.Name);
if (n.Name.EndsWithAny(OrdinalIgnoreCase, exclusions)) { return null; }
// search in basePath first, as it's probably the better dependency
var assemblyPath =
resolveFromFolder(basePath!) ??
resolveFromFolder(subfolderPath!) ??
null;
if (assemblyPath is null) { return null; }
return LoadFrom(assemblyPath);
string resolveFromFolder(string folder) =>
patterns
.SelectMany(pattern => Directory.EnumerateFiles(folder, pattern))
.FirstOrDefault(filePath => {
try {
return n.Name.Equals(AssemblyName.GetAssemblyName(filePath).Name, OrdinalIgnoreCase);
} catch {
return false;
}
});
}
}
}
</code></pre>
<p>It is called as follows:</p>
<pre><code>SubfolderAssemblyResolver.Hook("ExpressionTreeVisualizer");
</code></pre>
<hr />
<h3>Background</h3>
<p>It is possible to <a href="https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-visualizers-of-data?view=vs-2019" rel="nofollow noreferrer">write a custom debugging visualizer for Visual Studio</a>; when you place the compiled DLL into a <a href="https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-install-a-visualizer?view=vs-2019" rel="nofollow noreferrer">specific folder</a> (either <code>My Documents\%VisualStudioVersion%\Visualizers</code> or <code>%VisualStudioInstallPath%\Common7\Packages\Debugger\Visualizers</code>) the visualizer can provide a custom view of an object in the debug session.</p>
<p>Third-party DLLs can be used by the custom visualizer, as long as they are in the same folder as the visualizer DLL.</p>
<p>The problem with this is: if two visualizers use different versions of the same third-party dependency, one of them is liable to break. Also, when deleting the custom visualizer, deleting the dependencies risks breaking other visualizers.</p>
<p>This is compounded by the <a href="https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-install-a-visualizer?view=vs-2019" rel="nofollow noreferrer">architecture needed to apply the visualizer to other framework "families"</a>. The visualizer is split into two parts:</p>
<ol>
<li>the view DLL, targeting .NET Framework (because VS targets .NET Framework); and</li>
<li>the debuggee-side DLL, injected into the debugged process</li>
</ol>
<p>The debuggee-side code can be potentially multitargeted to three variants: <code>net2.0</code>, <code>netcoreapp</code> and <code>netstandard2.0</code>; which means potentially three additional DLLs in three additional subfolders, each of which has its own dependencies and the dependency management issues I've described.</p>
<p>The code in this post allows placing all the dependencies for a given visualizer in a named subfolder alongside the main DLL (either the debugger-side or the debuggee-side).</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T06:05:48.840",
"Id": "243705",
"Score": "1",
"Tags": [
"c#",
".net",
".net-core",
"visual-studio"
],
"Title": "Find assemblies in subfolder of primary assembly"
}
|
243705
|
<p>I made a calculator in C++. I wanted to ask is this code well written, understandable, and alright.</p>
<pre><code>#include <iostream>
using namespace std;
int main() {
// Declares the variable to store the asked value
int num1, num2;
char op;
// Asks the user for the input of numbers and the operation
cin >> num1;
cin >> op;
cin >> num2;
// Declares a variable for the answer
int result;
// Handles all the conditions of the operation
if(op == '+') {
result = num1 + num2;
} else if(op == '-'){
result = num1 - num2;
} else if(op == '*') {
result = num1 * num2;
} else if(op == '/') {
result = num1 / num2;
} else {
cout << "Invalid values";
cout<<endl<<endl;
}
// Outputs the result
cout << "Answer: ";
cout << result;
// Ouputs a thankyou message
cout<<endl<<endl;
cout << "THANKS FOR USING THIS";
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T14:57:36.400",
"Id": "478366",
"Score": "0",
"body": "You could use a switch instead of the if statements, I guess"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:08:59.740",
"Id": "478369",
"Score": "0",
"body": "@user Thanks for the reply bro but how does it make my code better is it faster than using If/else or something?g sorry If I might irritate you for a reason but I am newbie."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:25:33.180",
"Id": "478372",
"Score": "6",
"body": "Switch can be a bit faster sometimes (although it probably won't matter in such a small program). However, I meant that it might look a bit prettier that way. Also, you don't need to apologize for being a newbie. You're not irritating at all - this site is meant for questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T01:22:17.803",
"Id": "478414",
"Score": "15",
"body": "It is bad practice to use `using namespace std;`. See [this SO question](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) for more info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T03:52:08.823",
"Id": "478431",
"Score": "0",
"body": "You should look up the command pattern. Its a step beyond the switch statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:07:54.137",
"Id": "478473",
"Score": "0",
"body": "It's well-written and understandable, but wrong. It doesn't handle operator precedence or parentheses or unary operators, and to do any of that you wil need a complete rewrite using a standard eression parsing technique,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T12:03:23.197",
"Id": "478484",
"Score": "4",
"body": "@MarquisofLorne Well the guy is a newbie so for him, this stuff is a bit complex at least the program works and I think he has done pretty well as a beginner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T13:14:40.863",
"Id": "478489",
"Score": "0",
"body": "@NANO agreed -- the implicit \"documentation\" here is that it only handles simple `a + b` arithmetic. This could/should be added in code documentation or, more usefully for the user, as a kind of usage statement printed after / instead of `Invalid values`"
}
] |
[
{
"body": "<p><strong>Switch/Case over if/else</strong></p>\n<p>I think it would be great if you use switch/case instead of if/else it also makes you code look neat. Something like this</p>\n<pre><code>switch(op)\n {\n case '+': result = num1 + num2; break;\n case '-': result = num1 - num2; break;\n case '*': result = num1 * num2; break;\n case '/': result = num1 / num2; break;\n default:\n cout << "Please enter valid operation" ;\n }\n</code></pre>\n<p>Moreover, using switch/cases over if/else improves computational time when doing multiple iterations.</p>\n<p><strong>Add an OFF button</strong></p>\n<p>Also, the physical calculators that we use are always 'ON' unless they are turned off by pressing an 'OFF' button (or get turned off if no key is pressed for time <span class=\"math-container\">\\$t\\$</span>). You can also add that feature.</p>\n<p><strong>Instruction: type of input expected form user.</strong></p>\n<p>Say, a friend of yours wants to run the code, or you are an app developer and your client do not know anything about programming, and he just double-clicks on <code>calculator.exe</code> file, it would be great if you can also mention a short note when the program begins telling what logical operations and input format is expected from the user.</p>\n<p><strong>Showing error message</strong></p>\n<p>When someone types in <code>num1 / 0</code>. You can either show the error message</p>\n<pre><code>cout << DIVIDE_BY_ZERO_ERROR << endl;\n</code></pre>\n<p>Or simply say the answer in Infinity. And its value is</p>\n<pre><code>#include <limits>\n// ...\n\ndouble a = std::numeric_limits<double>::infinity();\n</code></pre>\n<p>You do not need to show this value, just in case if you want to take this code further and add some more features like 'memory' like our typical calculators.\nNote: this is not real infinity! It just a number such that <span class=\"math-container\">\\$a>b\\,\\,\\forall b\\$</span>. There is more about <a href=\"https://www.geeksforgeeks.org/handling-the-divide-by-zero-exception-in-c/\" rel=\"nofollow noreferrer\">Handling the Divide by Zero Exception in C++</a>. Perhaps, I have given only a short glimpse sticking with minimal code policy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T16:04:53.687",
"Id": "478377",
"Score": "1",
"body": "Oo Thank you very much for this wonderful example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T19:23:57.827",
"Id": "478633",
"Score": "0",
"body": "What do you mean by “this is not real infinity”? It is a bit configuration that means infinity, and is treated as such by all floating-point operations. Just like NaN is a bit configuration that indicates NaN, and 0 is a bit configuration that indicates 0, and 2.25 is a bit configuration that indicates 2.25, ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T00:20:41.497",
"Id": "478652",
"Score": "0",
"body": "@CrisLuengo some infinities are bigger than other infinities! The infinity defined here is same as other infinities. Check yourself `if(inf*inf > inf) std::cout << \"Hell yeah! Some infinities are greater than other infinities \\n\";` This is the reason I was critical about that note."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T00:31:57.160",
"Id": "478653",
"Score": "0",
"body": "@KartikChhajed: if that tests positive, it is a compiler-dependent result, maybe caused by some optimization? IEEE defines exactly one representation for infinity, and infinity should compare equal to itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T00:41:35.927",
"Id": "478655",
"Score": "0",
"body": "@CrisLuengo That is the problem! It never test positive. I am not sure if \\$\\infty\\times\\infty\\$ is greater than \\$\\infty\\$. But, I can't think of other infinity say `inf2` which is greater than `inf`. Because there must exist an `inf2` which is greater than `inf`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T01:02:11.470",
"Id": "478656",
"Score": "0",
"body": "[Why some infinities are bigger than other](https://aeon.co/essays/why-some-infinities-are-bigger-than-others). What I meant was, `inf` here has few mathematical property of \\$\\infty\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T01:15:21.677",
"Id": "478657",
"Score": "1",
"body": "Ah, I see what you mean now. Some set that has an infinite number more elements than another infinite set, like happens with real and natural numbers. But even in that case, both sets have an infinite number of elements, there’s only one symbol for infinity in mathematics. Given *x x = y*, if you fill out *x* = infty, then *y* = infty as well. There is no such notion as a larger infinity. The only awkward thing in IEEE floats is that infty==infty, whereas they should really not be comparable. But it’s convenient being able to compare them, and hence they’re comparable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:56:59.570",
"Id": "478702",
"Score": "0",
"body": "I'm **very intrigued** by the *OFF* button. Would you please elaborate on what you're getting at? It's a curious idea for a program I think at least if the program is only this functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:07:39.563",
"Id": "479075",
"Score": "0",
"body": "@Pryftan The code will depend on environment one is using: windows or linux. Either way it will require the use of a library outside iostreams, but on Linux at least you'll definitely have to turn off line buffering on the terminal which is a bit esoteric. For windows it is quite straightforward. One can use `GetAsyncKeyState(VK_ESCAPE)` with `#include <windows.h>`. (If one presses escape key, the program will exit.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:14:59.967",
"Id": "479081",
"Score": "0",
"body": "Other very bad way of doing would be, when taking entry of `num1` if someone presses Esc key, which has ASCII value `\\033`, a conditional statement will end the program. I have not tried it, but I think it is worst way of doing it. So, if someone has better answer I will delete this."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T16:03:35.653",
"Id": "243723",
"ParentId": "243715",
"Score": "4"
}
},
{
"body": "<p>I have some suggestions here:</p>\n<ol>\n<li><p>Using switch/case instead of if/else looks a little better and slightly faster as also mentioned in the comments.</p>\n</li>\n<li><p>You could definitely work on formatting your code it can be a lot better</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T02:19:54.760",
"Id": "478421",
"Score": "22",
"body": "If `switch` is faster than the equivalent `if`, you need to get yourself a new compiler. A good optimizer does not care, and will transform either construct into the most efficient code possible, whether that's a LUT, binary search, or whatever. Therefore, **do not choose between if/switch based on performance, but rather on readability**. Also, *strongly* prefer a switch when there is an exhaustive list of possibilities, and you aim to cover them all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:06:41.490",
"Id": "478457",
"Score": "0",
"body": "@CodyGray Ok alright"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T09:12:55.030",
"Id": "478465",
"Score": "0",
"body": "@CodyGray though I use the built-in compiler in visual studio but maybe my PC is slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T05:17:54.187",
"Id": "478558",
"Score": "0",
"body": "Unless you extract the computation of the result into a separate function, I advise against using `switch` here because the `break` statements add a lot of visual overhead, and it's too easy to forget a break. Sure, at one point you have to learn it, but in this early phase of programming just stay with the basics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:43:52.457",
"Id": "478571",
"Score": "0",
"body": "@RolandIllig Yes you are totally correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T11:52:29.343",
"Id": "478586",
"Score": "0",
"body": "The C++ compiler that comes with Visual Studio is outstanding and provides a solid optimizer. I've spent a lot of time looking at disassembly of object code generated by MSVC for various constructs, and I can't think of any cases where I've seen it fail to convert if statements into efficient object code when it would've done a better job with a switch-case statement. (Sometimes it does a poor job with either/both, but that's a different story.) Note that there is both a \"debug\" and \"release\" mode; only the latter has optimizations enabled. These modes should be used as the names suggest."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T17:51:27.487",
"Id": "243726",
"ParentId": "243715",
"Score": "12"
}
},
{
"body": "<p>A good next step in your code would be to test edge cases and account for them. A couple things you could improve:</p>\n<ol>\n<li><p>Your code does not handle division by zero. If someone puts in <code>1 / 0</code> your program will crash. You can check for this and give the user a nice error message</p>\n</li>\n<li><p>Your code does not handle integer overflow. You'll get interesting results if you try to do <code>2000000000 * 2000000000</code> because an <code>int</code> can only hold so large of a value.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:58:56.723",
"Id": "478703",
"Score": "0",
"body": "I thought div by 0 is UB? But maybe that's only C? Still should check it of course (though maybe not needed for floating point arithmetic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T20:58:26.683",
"Id": "478739",
"Score": "0",
"body": "@Pryftan It is UB but on any realistic platform today it will most likely crash. With floating-point numbers it's usually positive infinity."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:45:05.897",
"Id": "243776",
"ParentId": "243715",
"Score": "10"
}
},
{
"body": "<h2>Prefer <code>switch</code> over <code>else if</code>s</h2>\n<p>Switch will make your code easier to read.</p>\n<h2>The variable <code>result</code> could be uninitialized</h2>\n<p>Consider situation where user types in incorrect operator. In this case the result is uninitialized and your calculator crashes.</p>\n<h2>Division by zero crashes</h2>\n<h2>Prefer <code>\\n</code> over <code>endl</code></h2>\n<p>The <code>endl</code> forces the stream to flush. Instead of</p>\n<pre><code>cout << "Answer: ";\ncout << result;\n// Outputs a thankyou message\ncout << endl << endl;\ncout << "THANKS FOR USING THIS";\n</code></pre>\n<p>I would suggest something like</p>\n<pre><code>std::cout << "Answer: " << result \n << "\\n\\nTHANKS FOR USING THIS\\n";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T11:57:21.903",
"Id": "243816",
"ParentId": "243715",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243726",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T14:34:34.950",
"Id": "243715",
"Score": "14",
"Tags": [
"c++",
"beginner",
"mathematics",
"calculator"
],
"Title": "Calculator in C++"
}
|
243715
|
<p>I'd like to hear some reviews or tips where I can improve in my code - or better if you can post your own version of the code from somebody experienced where I can visually see to why you have coded it in your way rather than my way.</p>
<p>What this code does is simply loads data into the dataGridView using Windows Forms and I have multiple functions such as the search bar.</p>
<p>Function such as <code>Add new document</code>, <code>Update selected document</code> and <code>View File</code> code will not be seen as it is on a separate Form. But will ask a separate question for each when I have some reviews on this code.</p>
<p><strong>How the app looks</strong></p>
<p><a href="https://i.stack.imgur.com/qQ9hy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qQ9hy.png" alt="enter image description here" /></a></p>
<p><strong>FSQMMain.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI.Relational;
using Technical_Application.Classes;
using System.Diagnostics;
namespace Technical_Application.Forms.SubForm.FSQM
{
public partial class FSQMMain : Form
{
public FSQMMain()
{
InitializeComponent();
}
private void ChooseSection_Load(object sender, EventArgs e)
{
//Load data with MySQL values
LoadData();
//
//Only show buttons depending on the user access id, taken from MySQL column `access id`
if (UserDetails.accessId == 2 || UserDetails.accessId == 3)
{
addNewDocument.Visible = false;
bunifuFlatButton1.Visible = false;
}
//
//
}
//This is a function to load data to the Data Grid View
public void LoadData()
{
try
{
//Load data from MySQL table
//Connection string
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
//Creating a data adapter and filling the table with dataSet
using (var mySqlDataAdapter = new MySqlDataAdapter("SELECT f.id, " +
"f.Document_Reference," +
" f.document_name, " +
"f.path, " +
"f.version, " +
"f.section, " +
"date(f.last_review_date), " +
"date(f.review_date)," +
" u.username, " +
"f.date_modified " +
"from files f join users u on f.user_modified = u.id;", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
data.DataSource = DS.Tables[0];
//Assign Header Titile for each column loaded
data.Columns[0].HeaderText = "ID";
data.Columns[1].HeaderText = "Document Reference";
data.Columns[2].HeaderText = "Document Name";
data.Columns[3].HeaderText = "Path";
data.Columns[4].HeaderText = "Version Number";
data.Columns[5].HeaderText = "Section";
data.Columns[6].HeaderText = "Last Review Date";
data.Columns[7].HeaderText = "Next Review Date";
data.Columns[8].HeaderText = "User Last Modified";
data.Columns[9].HeaderText = "Modified Date";
//Hide Specific columns
data.Columns[0].Visible = false;
data.Columns[3].Visible = false;
}
}
}
}
//If any errors - then stop Execution
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
//Stop executing code
return;
}
}
//Search button
private void searchbtn_Click(object sender, EventArgs e)
{
//We use a string builder, becasue we have 3 different search boxes to use.
StringBuilder sb = new StringBuilder();
//Here we are seeing if the textboxes have any values
if (documentName.Text.Length > 0)
{
//If they do - add a search filter
sb.Append($"document_name like '%{documentName.Text}%'");
}
if (docRef.Text.Length > 0)
{
if (sb.Length > 0)
{
sb.Append(" and ");
}
sb.Append($"document_reference like '%{docRef.Text}%'");
}
if (section.Text.Length > 0)
{
if (sb.Length > 0)
{
sb.Append(" and ");
}
sb.Append($"section ={Int32.Parse(section.Text)}");
}
//Combine all filters together
(data.DataSource as DataTable).DefaultView.RowFilter = sb.ToString();
}
//Only allow numbers in `Section` text box
private void section_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(section.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.", "Integer - Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
section.Text = section.Text.Remove(section.Text.Length - 1);
}
}
//Clear search boxes
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
LoadData();
documentName.Clear();
section.Clear();
docRef.Clear();
docRef.Select();
}
//Open form add new document
private void addNewDocument_Click(object sender, EventArgs e)
{
//Open NewDocument Form
bool Isopen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == "New Document")
{
Isopen = true;
f.BringToFront();
if (f.WindowState == FormWindowState.Minimized)
{
f.WindowState = FormWindowState.Normal;
}
break;
}
}
if (Isopen == false)
{
var newDoc = new AddNewDocument(this);
newDoc.Show();
}
}
//Format cells to red, amber and green depending on the review date
private void data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//Set variable today to todays date
DateTime today = DateTime.Today.Date;
//Iterate through each row and check the review date
foreach (DataGridViewRow Myrow in data.Rows)
{
DateTime dt = DateTime.Parse(Myrow.Cells[7].Value.ToString());
//If today or past review date, show as red
if (dt <= today)
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
//If review date is within 30 days
else if ((dt - today).TotalDays <= 30)
{
Myrow.DefaultCellStyle.BackColor = Color.FromArgb(231, 202, 0);
}
//Else show green
else
{
Myrow.DefaultCellStyle.BackColor = Color.FromArgb(20, 205, 14);
}
}
}
//Update button
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
bool Isopen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == "Update")
{
Isopen = true;
f.BringToFront();
if (f.WindowState == FormWindowState.Minimized)
{
f.WindowState = FormWindowState.Normal;
}
break;
}
}
if (Isopen == false)
{
if (this.data.SelectedRows.Count > 0)
{
var update = new Update(this);
update.Show();
}
else
{
MessageBox.Show("No Records Selected", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
//View file Button
private void viewFile_Click(object sender, EventArgs e)
{
if (this.data.SelectedRows.Count > 0)
{
bool Isopen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == "File Viewer")
{
Isopen = true;
f.BringToFront();
if (f.WindowState == FormWindowState.Minimized)
{
f.WindowState = FormWindowState.Normal;
}
break;
}
}
if (Isopen == false)
{
if (this.data.SelectedRows.Count > 0)
{
var fileView = new File_Viewer(this);
fileView.Show();
}
else
{
MessageBox.Show("No Records Selected", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
{
MessageBox.Show("No Records Selected", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:41:35.977",
"Id": "478477",
"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": "<p><strong>Don't use <code>StringBuilder</code> in <code>searchbtn_Click</code>; use a <code>Join</code>ed <code>List<string></code></strong></p>\n<p>You're combining a small number of small strings, so there's likely no real performance benefits in using a <code>StringBuilder</code>.</p>\n<p>I would suggest creating a <code>List<string></code> and then calling <code>string.Join</code> on the list:</p>\n<pre><code>var parts = new List<string>();\nif (documentName.Text.Length > 0) {\n parts.Add($"document_name like '%{documentName.Text}%'");\n}\nif (docRef.Text.Length > 0) {\n parts.Add($"document_reference like '%{docRef.Text}%'");\n}\nif (section.Text.Length > 0) {\n parts.Add($"section ={Int32.Parse(section.Text)}");\n}\n(data.DataSource as DataTable).DefaultView.RowFilter = string.Join(" and ", parts);\n</code></pre>\n<p>I might go even further and build the controls and formatted parts into some kind of collection of pairs, which could then be filtered and the appropriate results passed into <code>Join</code>:</p>\n<pre><code>var parts = new (string text, string part)[] {\n (documentName.Text, $"document_name like '%{documentName.Text}%'"),\n (docRef.Text, $"document_reference like '%{docRef.Text}%'"),\n (section.Text, $"section = {Int32.Parse(section.Text)}")\n }\n .Where(x => x.text.Length > 0)\n .Select(x => x.part);\n(data.DataSource as DataTable).DefaultView.RowFilter = string.Join(" and ", parts);\n</code></pre>\n<hr />\n<p><strong>Refactor form-finding code into a separate method</strong></p>\n<p>You're searching in multiple places for a form based on the value of the form's <code>Text</code> property. I would suggest you refactor this code into a separate method; something like this:</p>\n<pre><code>private Form findForm(string text) {\n var found = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f.Text == text);\n\n // C# 8 syntax; for earlier versions use 'if (found != null) {\n if (found is {}) {\n found.BringToFront();\n if (found.WindowState == FormWindowState.Minimized) {\n found.WindowState = FormWindowState.Normal;\n }\n }\n return found;\n}\n</code></pre>\n<p>Then, for example in <code>addNewDocument_Click</code>, you could write:</p>\n<pre><code>var found = findForm("New Document");\nif (found is null) {\n var newDoc = new AddNewDocument(this);\n newDoc.Show();\n}\n</code></pre>\n<hr />\n<p>Consider putting the SQL statement in a separate <code>const</code>. This makes it easier to see what's going on at the start of your <code>using</code> block.</p>\n<p>Since you're not using the inner <code>dataSet</code> variable, you can remove the innermost <code>using</code>.</p>\n<p>I would also suggest making use of the new <code>using</code> statement in C# 8 if you can:</p>\n<pre><code>using var conn = new MySqlConnection(ConnectionString.ConnString);\nusing var mySqlDataAdapter = new MySqlDataAdapter(sql, conn);\nDataSet DS = new DataSet();\nmySqlDataAdapter.Fill(DS);\n...\n</code></pre>\n<p>Alternatively, use the single-statement <code>using</code> form for the outer <code>using</code>:</p>\n<pre><code>using (var conn = new MySqlConnection(ConnectionString.ConnString))\nusing (var mySqlDataAdapter = new MySqlDataAdapter(sql, conn)) {\n DataSet DS = new DataSet();\n mySqlDataAdapter.Fill(DS);\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:47:51.110",
"Id": "478452",
"Score": "0",
"body": "Thank you for this! - The `findForm` is really great, as it is short and in addition checks the `WindowState`! Also.. the suggestion to use `List`... is really great, I appreciate it. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:54:51.753",
"Id": "478453",
"Score": "0",
"body": "Regarding the `findForm` - I have an error `Feature 'recursive patterns' is not available in C# 7.3 Please use language version 8.0 or greater`, any idea how to change this? I'll do some research in the meantime"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:01:34.173",
"Id": "478455",
"Score": "0",
"body": "@LV98 `if (found != null) {` should work. I've noted this in a comment on the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:05:21.043",
"Id": "478456",
"Score": "0",
"body": "Thank you - and one more error `The name 'f' does not exist in the current context`. Should it be `found..BringToFront()`.. instead of `f.BringToFront()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:07:19.723",
"Id": "478458",
"Score": "1",
"body": "@LV98 Fixed, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:08:32.630",
"Id": "478459",
"Score": "0",
"body": "Legendary! - Thanks for your help :) do you have any recommendations in terms of areas to study for C#? I am aiming to build Enterprise applications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:59:01.793",
"Id": "478463",
"Score": "0",
"body": "Two points come to mind. 1. Be familiar with the C# language, because the constructs and concepts of the programming language are the most fundamental of your tools. The [C# Programming Guide](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/) is an excellent place to start. 2. Your aim should be that your code expresses your intent (as much as possible). For example, replacing 3 `if` blocks each with its own nested `if`, with a single call to `string.Join`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T12:02:31.133",
"Id": "478483",
"Score": "0",
"body": "@LV98 Ping previous comment,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T12:08:29.267",
"Id": "478485",
"Score": "0",
"body": "Not sure what you mean by that,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T19:32:51.450",
"Id": "478640",
"Score": "0",
"body": "@LV98 I'd forgotten to @ mention you in my [previous comment](https://codereview.stackexchange.com/questions/243717/c-window-form-application-loading-data-into-datagrid-and-highlight-specific-val/243724?noredirect=1#comment478483_243724)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T17:15:50.053",
"Id": "243724",
"ParentId": "243717",
"Score": "2"
}
},
{
"body": "<p>This:</p>\n<pre><code>if (UserDetails.accessId == 2 || UserDetails.accessId == 3)\n</code></pre>\n<p>Consider using an Enum instead of hardcoding integer values eg:</p>\n<pre><code>enum AccessLevel : int\n{\n None = 0,\n Manager = 2,\n SuperUser = 3\n}\n</code></pre>\n<hr />\n<p>You can use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim\" rel=\"nofollow noreferrer\">verbatim strings</a> for your SQL statements:</p>\n<pre><code>string sql = @"SELECT f.id, f.Document_Reference, f.document_name,\nf.path, f.version, f.section,\ndate(f.last_review_date), date(f.review_date),\nu.username, f.date_modified\nfrom files f join users u on f.user_modified = u.id;";\n</code></pre>\n<hr />\n<p>There is <strong>repetitive code</strong>: <code>bunifuFlatButton1_Click</code> and <code>viewFile_Click</code> are almost the same. Surely you can merge both into one function and pass the control name as argument. Then your code becomes and shorter and easier to maintain.</p>\n<hr />\n<p>Here you set the header titles for your DGV:</p>\n<pre><code> //Assign Header Titile for each column loaded\n data.Columns[0].HeaderText = "ID";\n data.Columns[1].HeaderText = "Document Reference";\n data.Columns[2].HeaderText = "Document Name";\n data.Columns[3].HeaderText = "Path";\n data.Columns[4].HeaderText = "Version Number";\n data.Columns[5].HeaderText = "Section";\n data.Columns[6].HeaderText = "Last Review Date";\n data.Columns[7].HeaderText = "Next Review Date";\n data.Columns[8].HeaderText = "User Last Modified";\n data.Columns[9].HeaderText = "Modified Date";\n\n //Hide Specific columns\n data.Columns[0].Visible = false;\n data.Columns[3].Visible = false;\n</code></pre>\n<p>There is nothing wrong with that but personally I prefer to separate design from programming logic as much as possible. So I would just edit the DGV in design mode and put the header titles directly in it. You can also hide some columns by default. That makes the code shorter (less scrolling).\nThe one thing that I change at runtime is the column width so that it fits the cell contents. Most attributes are otherwise static.</p>\n<hr />\n<p>I think you can can simplify this part:</p>\n<pre><code> //Open NewDocument Form\n bool Isopen = false;\n\n foreach (Form f in Application.OpenForms)\n {\n if (f.Text == "New Document")\n {\n Isopen = true;\n f.BringToFront();\n if (f.WindowState == FormWindowState.Minimized)\n {\n f.WindowState = FormWindowState.Normal;\n }\n break;\n }\n }\n \n if (Isopen == false)\n {\n var newDoc = new AddNewDocument(this);\n newDoc.Show();\n }\n</code></pre>\n<p>Basically you can check if a form is open or not in a more concise fashion:</p>\n<pre><code>public bool CheckIfFormIsOpen(string formname)\n{\n bool formOpen= Application.OpenForms.Cast<Form>().Any(form => form.Name == formname);\n\n return formOpen;\n}\n</code></pre>\n<p>Have a look <a href=\"https://stackoverflow.com/a/21215534/6843158\">here</a></p>\n<hr />\n<p>The good thing is that there are adequate <strong>comments</strong> and the code is quite clear to understand.</p>\n<hr />\n<p>You can probably declutter the code further by removing <strong>unused imports</strong> unless you have more code in this form that relies on those imports.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:41:18.233",
"Id": "478448",
"Score": "0",
"body": "Really appreciate your honest comments! Also thank you for `CheckIfFormIsOpen` - that is very short and simple!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:43:55.753",
"Id": "478449",
"Score": "0",
"body": "@LV98 Except it doesn't handle bringing the form to the foreground or setting the `WindowState` to `FormWindowState.Normal`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:46:55.823",
"Id": "478451",
"Score": "0",
"body": "@ZevSpitz I have seen your version of this too - which includes setting the `Window State` :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T23:05:36.273",
"Id": "243739",
"ParentId": "243717",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243724",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T14:39:30.977",
"Id": "243717",
"Score": "3",
"Tags": [
"c#",
"winforms"
],
"Title": "C# Window Form Application Loading data into DataGrid and highlight specific values based on their values"
}
|
243717
|
<p>Given a floating-point number, which is representing a dollar value, I'm aiming to return a rounded, human-readable string. Here are the rules for numbers equal to or greater than 1 million, equal to or greater than 1 but less than 1 million, and, finally, less than 1:</p>
<ul>
<li>one decimal place for million, two places for billions and three places for trillions</li>
<li>numbers over 999 trillion are displayed in trillions, e.g. <code>1,000 trillion</code> not <code>1 quadrillion</code></li>
<li><strong>if less than 1 million</strong>, two decimal places (cents)</li>
<li><strong>if less than 1</strong>, then as cents (multiplied by 100)
<ul>
<li>numbers which don't round up to at least 1 cent count as 0 cents</li>
</ul>
</li>
</ul>
<p>Also, for numbers greater than 1, there's no display of precision if mantissa is all zeros (e.g. <code>1.000 trillion</code> becomes <code>1 trillion</code> and <code>1.00</code> becomes <code>1</code>.)</p>
<pre><code>import math
def convert_float_to_value(number):
if number == 0.0:
return "0 cents"
digits = 1 + math.floor(math.log10(number))
if digits > 12:
return f"${round(number / 10**12, 3):,.3f} trillion".replace(".000", "")
elif digits > 9:
return f"${round(number / 10**9, 2):,.2f} billion".replace(".00", "")
elif digits > 6:
return f"${round(number / 10**6, 1):,.1f} million".replace(".0", "")
elif digits > 0:
return f"${round(number, 2):,.2f}".replace(".00","")
else:
return f"{round(number * 100):,} cents".replace("1 cents", "1 cent")
</code></pre>
<p>I already sense some improvements, like perhaps I should be checking this really is a floating-point value and not an integer, or just turning whatever I get into a float. But what do you think of this approach? There are a number of pretty-printing libraries but these are some very specific rules.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T09:36:47.017",
"Id": "478472",
"Score": "1",
"body": "I suspect the replace in your final line isn't doing what you want: e.g. `convert_float_to_value(.51)` returns `'51 cent'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:49:00.027",
"Id": "478479",
"Score": "0",
"body": "@Energya that's a good point. I could use a regular expression `return re.sub(r\"^1 cents$\", \"1 cent\", f\"{round(number * 100):,} cents\")` or perhaps some logic that checks the output string is exactly `1 cents` and then returns `1 cent`."
}
] |
[
{
"body": "<p>To me your code looks very WET. Everything is using the same core but with minor tweeks here and there. And so we can convert your code to a for loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>TRANSFORMS = [\n ( 12, "$", 10**12, 3, ".3f", " trillion", ".000", ""),\n ( 9, "$", 10** 9, 2, ".2f", " billion", ".00", ""),\n ( 6, "$", 10** 6, 1, ".1f", " million", ".0", ""),\n ( 0, "$", 10** 0, 2, ".2f", "", ".00", ""),\n (float("-inf"), "", 10**-2, None, "", " cents", "1 cents", "1 cent"),\n]\n\n\ndef convert_float_to_value(number):\n if number == 0.0:\n return "0 cents"\n digits = 1 + math.floor(math.log10(number))\n for d, *t in TRANSFORMS:\n if digits > d:\n return f"{t[0]}{round(number / t[1], t[2]):,{t[3]}}{t[4]}".replace(t[5], t[6])\n</code></pre>\n<p>From here we can start to see patterns and other improvements.</p>\n<ol>\n<li><p>Excluding cents; <code>t[2]</code>, <code>t[3]</code> and <code>t[5]</code> all have the same size.\nThis means we can build them all from one value.</p>\n<pre class=\"lang-py prettyprint-override\"><code>v = ...\nt[2] = v\nt[3] = f".{v}f"\nt[4] = "." + "0"*v\n</code></pre>\n</li>\n<li><p>It makes little sense to use <code>.2f</code> for billions. I've never, until this day, seen "$1.10 billion". It's almost like you've used the wrong word and meant to say "dollars".</p>\n<p>To fix this I'd stop using <code>.2f</code>. However this will break how <code>.replace</code> works, and can add some hard to fix bugs.\n(Converting 10.01 to 101)\nTo fix this I'd convert integers to <code>int</code>s and keeps floats as floats.</p>\n</li>\n<li><p>We haven't built <code>t[3]</code> and <code>t[5]</code> from <code>t[2]</code> for plain dollars as it still requires <code>.2f</code> to make sense.\nTo deal with this we can make a function <code>pretty_round</code> that takes a number, a number of digets to round to, an option for the output to be a fixed amount of decimal places and any additional formatting. The only thing is that the output has return a string and a float.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pretty_round(number, ndigits=None, fixed=False, format_spec=""):\n number = round(number, ndigits)\n if number % 1 == 0:\n return number, format(int(number), format_spec)\n return number, format(number, format_spec + (f".{ndigits}f" if fixed else ""))\n</code></pre>\n</li>\n<li><p>With the above changes we can see <code>t[5]</code> and <code>t[6]</code> are only there to convert cents from plural to singular.\nAnd so why not just check if the output is singular or plural and append the correct term?</p>\n</li>\n<li><p>By changing the method of finding <code>digits</code> to use <code>len</code> we can replace <code>float('-inf')</code> with <code>-2</code> and build <code>t[1]</code> from <code>d</code>.</p>\n</li>\n<li><p>I am going to reorder the table so that they're grouped better. <code>t[0]</code> should be near <code>t[5]</code> and <code>t[6]</code>.\nAnd we can now give them easy to understand names.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>TRANSFORMS = [\n (12, 3, False, " trillion", "$", "", ""),\n ( 9, 2, False, " billion", "$", "", ""),\n ( 6, 1, False, " million", "$", "", ""),\n ( 0, 2, True, "", "$", "", ""),\n (-2, None, False, "", "", " cents", " cent"),\n]\n\n\ndef pretty_round(number, ndigits=None, fixed=False, format_spec=""):\n number = round(number, ndigits)\n if number % 1 == 0:\n return number, format(int(number), format_spec)\n return number, format(number, format_spec + (f".{ndigits}f" if fixed else ""))\n\n\ndef convert_float_to_value(number):\n digits = len(str(int(number)).lstrip('0-'))\n for exp, dp, fixed, magnitude, prefix, plural, singular in TRANSFORMS:\n if digits > exp:\n number_f, number_s = pretty_round(number / 10**exp, dp, fixed, ",")\n name = singular if number_f == 1 and exp <= 0 else plural\n return f"{prefix}{number_s}{magnitude}{name}"\n</code></pre>\n<ol start=\"7\">\n<li><p>We can see that <code>TRANSFORMS</code> is not <a href=\"https://en.wikipedia.org/wiki/Database_normalization\" rel=\"nofollow noreferrer\">normalized</a>.</p>\n<ol>\n<li><p>All of <code>prefix</code>, <code>plural</code> and <code>singular</code> are refering to dollers and cents.\nThis can be extracted out into it's own table.\nNot only does it reduce how WET your code is it allows us to replace dollars with other monetary notations.\nAdditionally it allows making changes easier if you want to change from using "$" to "dollars"</p>\n</li>\n<li><p>The magnitude can change even in English. This is as 1 trillion can equal 1 billion, depending on which <a href=\"https://en.wikipedia.org/wiki/Long_and_short_scales\" rel=\"nofollow noreferrer\">scale</a> you use.\nHaving this baked into the <code>TRANSFORMS</code> table can be problematic in the future.</p>\n</li>\n</ol>\n</li>\n<li><p>With your values <code>fixed</code> is the same as <code>not exp</code>.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>SHORT_SCALE = [\n "",\n " thousand",\n " million",\n " billion",\n " trillion",\n]\nUSD = [\n ("$", "", ""),\n ("", " cents", " cent"),\n]\nTRANSFORMS = [\n (12, 3),\n ( 9, 2),\n ( 6, 1),\n ( 0, 2),\n (-2, 0),\n]\n\n\ndef pretty_round(number, ndigits=None, fixed=False, format_spec=""):\n number = round(number, ndigits)\n if number % 1 == 0:\n return number, format(int(number), format_spec)\n return number, format(number, format_spec + (f".{ndigits}f" if fixed else ""))\n\n\ndef convert_float_to_value(number, *, scale=SHORT_SCALE, currency=USD):\n digits = len(str(int(number)).lstrip('0-'))\n for exp, dp in TRANSFORMS:\n if digits > exp:\n number_f, number_s = pretty_round(number / 10**exp, dp, not exp, ",")\n prefix, plural, singular = currency[exp < 0]\n name = singular if number_f == 1 and exp <= 0 else plural\n return f"{prefix}{number_s}{scale[int(exp / 3)]}{name}"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T19:16:14.640",
"Id": "243789",
"ParentId": "243721",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>But what do you think of this approach?</p>\n</blockquote>\n<p>Comments below are less about Python and more about design and test.</p>\n<p><strong>Negatives</strong></p>\n<p>I suggest using the absolute value of <code>number</code> rather than <code>math.log10(number)</code>.</p>\n<p><strong>Lack of edge case testing</strong></p>\n<p>I'd expect code to have been tested with various edge cases as they are specified in the requirements.</p>\n<pre><code> 999000000000.0, 100000000000.0, 1000000000.0, 1000000.0, 1.0, 0.01, 0.005, math.nextafter(0.0,1.0)\n</code></pre>\n<p>And importantly the above values' next smallest value.</p>\n<pre><code>smaller= math.nextafter(x, 0.0)\n</code></pre>\n<p>Also test with negatives and very large values like <span class=\"math-container\">\\$10^{20}\\$</span>.</p>\n<p>IMO, I think OP will find unacceptable results.</p>\n<p><strong>Conceptual alternative code</strong></p>\n<p>Rather than adding 1 and using <code>></code>, I would use <code>>=</code>. This works even if <code>math.floor()</code> is omitted.</p>\n<pre><code># digits = 1 + math.floor(math.log10(number))\n# if digits > 12:\n\ndigits = math.floor(math.log10(number))\nif digits >= 12:\n</code></pre>\n<p>This better matches the coding goal.</p>\n<p><strong>Pedantic</strong></p>\n<p><code>number / 10**12</code> will impart a rounding error in the quotient before printing, which is in effect a 2nd rounding. When output is abc.def, values near abc.def +/- 0.0005 (scaled to <span class=\"math-container\">\\$10^{12}\\$</span>) may exhibit an incorrect rounding of the original <code>number</code>. A solution is to round once converting the <code>number</code> to text, which is later manipulated. Rarely is this degree of correctness needed.</p>\n<p><strong>Money</strong></p>\n<p>For <em>money</em>, I'd expect using <a href=\"https://docs.python.org/3/library/decimal.html\" rel=\"nofollow noreferrer\"><code>Decimal</code> floating point</a>. Unclear to me what OP is using given my scant Python experiences.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T17:01:22.123",
"Id": "480695",
"Score": "0",
"body": "This is such a good answer, thanks! Could you update the link to Decimal floating point to Python 3 docs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T17:09:44.193",
"Id": "480698",
"Score": "1",
"body": "@MartinBurch Link updated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:50:32.607",
"Id": "244342",
"ParentId": "243721",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244342",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:51:04.273",
"Id": "243721",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"strings",
"formatting",
"floating-point"
],
"Title": "Pretty-print dollar amounts using custom precision for large amounts"
}
|
243721
|
<p>I always read questions about a Windows solution to find a <a href="https://stackoverflow.com/q/8066679">file in a directory structure</a> like find and grep.</p>
<p>I created this working c++ program, where you give the program a path and a file name to find.</p>
<pre><code>#include <iostream>
#include <string>
#include <sys/stat.h>
#include <windows.h>
#ifndef INVALID_FILE_ATTRIBUTES
constexpr INVALID_FILE_ATTRIBUTES((DWORD) - 1)
#endif
BOOL IsDir(const std::string &path)
{
DWORD Attr;
Attr = GetFileAttributes(path.c_str());
if (Attr == INVALID_FILE_ATTRIBUTES)
return FALSE;
return (BOOL)(Attr & FILE_ATTRIBUTE_DIRECTORY);
}
std::string sanitizePath(const std::string &path)
{
std::string fspath = path;
while (*(fspath.rbegin()) == '/' || *(fspath.rbegin()) == '\\')
fspath.pop_back();
return fspath;
}
int findFiles(std::string &fspath, const std::string &fs)
{
static size_t i = 0;
WIN32_FIND_DATA FindFileData;
std::string destpath = fspath + std::string("\\*.*");
HANDLE hFind = FindFirstFile(destpath.c_str(), &FindFileData);
if (hFind != INVALID_HANDLE_VALUE)
do {
std::string fullpath = std::string(fspath) + std::string("\\") + std::string(FindFileData.cFileName);
if (*(fullpath.rbegin()) == '.')
continue;
else if (FindFileData.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
findFiles(fullpath, fs);
else
{
if (FindFileData.cFileName == fs)
{
std::cout << fs << " was found in -> " << fspath << std::endl;
i++;
}
}
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
return i;
}
int main(int argc, char **argv)
{
if (argc <= 2)
{
std::cerr << "No path or filename provided" << std::endl;
return EXIT_FAILURE;
}
const char *path = argv[1];
const char *fileSearched = argv[2];
if (!IsDir(path))
{
std::cerr << "Path doesn't exist" << std::endl;
return EXIT_FAILURE;
}
std::string fspath = sanitizePath(path);
std::string fs = fileSearched;
std::cout << "Searching " << fspath << " and its subdirectories" << std::endl;
int i = findFiles(fspath, fs);
if (i == 0)
std::cout << fs << " was not found in " << fspath << " or its subdirectories" << std::endl;
else if (i == 1)
std::cout << fs << " was found once";
else
{
std::cout << fs << " was found " << i << " times" << std::endl;
std::cout << "Beware same filename does NOT automatically mean same file content." << std::endl;
}
return EXIT_SUCCESS;
}
</code></pre>
<p>it is used like this</p>
<pre><code>find <path> <filename>
</code></pre>
<p>It is case sensitive and gives you whether and where the file was found and how many times.
I used an online code beautifier for indentation.
The sanitize method is for removing trailing "/" or "\".
It compiled and ran to multiple tests.
Please give me you opinions especially about its professionalism aka do code in big companies look like that?
Keep in mind, I graduated some time and failed so far in getting internship or a job in programming in my country.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T20:22:18.263",
"Id": "478388",
"Score": "0",
"body": "Based on the 8 compiler errors I get when I try to build the program in Visual Studio 2019 and this [stackoverflow.com question](https://stackoverflow.com/questions/1198672/how-to-convert-string-to-lpwstr-in-c) I strongly doubt that this program works as suggested. You also might want to add an indent to all the code within a function, maybe a different setting on the pretty printer you found."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T06:17:41.807",
"Id": "478442",
"Score": "2",
"body": "@pacmaninbw: Not sure exactly what problems you encountered, but I just compiled and tested it. It seems to work as advertised."
}
] |
[
{
"body": "<ol>\n<li><p>As a general rule, I'd tend to prefer the built in C++ <code>bool</code> over the Windows-specific <code>BOOL</code>.</p>\n</li>\n<li><p>Your <code>sanitizePath</code> seems less than ideal, at least to me. Passing them parameter by reference, then creating a local copy from the reference seems like kind of a waste. If you want a local copy, just pass by value. Regardless of that, <code>std::string</code> already provides a function to search for the position you want, so I'd probably use that.</p>\n<pre><code> std::string sanitizePath(std::string const &input) {\n auto pos = input.find_last_not_of("/\\\\");\n return input.substr(0, pos+1);\n }\n</code></pre>\n</li>\n<li><p>After a few decades of using C++, I've gotten to the point that almost any time I see an <code>open</code> and matching <code>close</code> operation, my immediate reaction is to use RAII--define a class that does the <code>open</code> in its ctor, and the matching close in its dtor. It looks to me like file searching fits this pattern, and probably benefits from the RAII treatment.</p>\n</li>\n<li><p>Likewise, if I'm going to iterate through a collection of objects, my reaction is to think about whether I can define an actual iterator, so I can off-load as much work as possible onto standard algorithms (and such).</p>\n</li>\n<li><p>I'd avoid using <code>std::endl</code>. In this case, it probably doesn't make a huge difference, but I'd still form the habit of using <code>'\\n'</code> when you want a <code>new-line</code>.</p>\n</li>\n<li><p>You might want to consider using a <code>std::filesystem::recursive_directory_iterator</code>, which already implements an iterator interface for file searching. Using it, the code for <code>findFiles</code> would reduce down to something like this:</p>\n<pre><code> int findFiles(std::filesystem::path const& fspath, const std::string& fs)\n {\n std::filesystem::recursive_directory_iterator di { fspath };\n int count = 0;\n\n for (auto const& file : di) {\n if (file.path().filename() == fs) {\n std::cout << file.path().string() << "\\n";\n ++count;\n }\n }\n return count;\n }\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T14:15:46.897",
"Id": "478596",
"Score": "0",
"body": "Thanks! especially about the sanitizePath and notes taken. RAII's problem is always explained using advanced concepts for a beginner."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:47:52.860",
"Id": "243756",
"ParentId": "243722",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243756",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T15:53:39.740",
"Id": "243722",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Find-like script for windows"
}
|
243722
|
<p>Suppose I have 3 classes, Animal, Dog, and Cat</p>
<pre><code>public abstract class Animal {
private static final List<Animal> allObjects = new ArrayList<>();
public Animal(){
allObjects.add(this);
}
// Returns immutable list of all Animal objects
public static List<? extends Animal> getInstantiatedObjects(){
return allObjects;
}
}
</code></pre>
<pre><code>public class Cat extends Animal {
private static final List<Cat> allObjects = new ArrayList<>();
public Cat(){
super();
allObjects.add(this);
}
// Returns immutable list of all Cat objects
public static List<? extends Cat> getInstantiatedObjects(){
return allObjects;
}
}
</code></pre>
<p>While this works, I can't help but think that this is poor design, and it would be better if either the static method would be inheritable and "adapt" to the class (? extends thisClass), or it raised an implementation error if the method wasn't implemented. For instance,</p>
<pre><code>public class Dog extends Animal {
private static final List<Dog> allObjects = new ArrayList<>();
public Dog(){
super();
allObjects.add(this);
}
/* Returns immutable list of all Dog objects
public static List<? extends Dog> getInstantiatedObjects(){
return allObjects;
} */
}
</code></pre>
<p>returns no errors and simply uses the static method of the superclass, but that doesn't allow the code to store only objects of its class or lower. Any help would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T17:39:55.260",
"Id": "478382",
"Score": "0",
"body": "I tried using an interface, but it won't let me use a static method without a declaration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T17:47:00.340",
"Id": "478383",
"Score": "0",
"body": "You can't inherit static methods (or really override them). It'd be better to just write `Dog.allObjects.add(this)` specifically, I guess"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T01:21:53.290",
"Id": "478413",
"Score": "2",
"body": "I have a question, it really need to be done in each class ? I mean, each class has to have a collection of their instances ? because this problem would be simpler if you used a Singleton with a map of `<Class Type, Collection Of Instances>` don't you think ? I had made my \"mini lab\" and wow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T03:35:16.553",
"Id": "478430",
"Score": "2",
"body": "Why is it static? Can't a factory maintain those lists?"
}
] |
[
{
"body": "<p>From time to time one sees this wish. I never needed it, but the way is to have one global repository in the base class:</p>\n<pre><code>public abstract class Animal {\n private static final Map<Class<? extends Animal>, List<Animal>> all =\n new HashMap<>();\n\n protected Animal() {\n List<Animal> species = all.computeIfAbsent(getClass(),\n type -> new ArrayList<>());\n species.add(this);\n }\n\n public static Stream<T extends Animal> all(Class<T> type) {\n return all.computeIfAbsent(getClass(), \n type -> new ArrayList<>()).stream().map(type::cast);\n }\n</code></pre>\n<p>Instead of storing the <code>Animal</code> child instance one could use a <code>WeakReference<Animal></code> to let animals disappear when not used.</p>\n<p>A call to <code>Animal.all(Dog.class)</code> needs no Animal instance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T21:23:35.513",
"Id": "243735",
"ParentId": "243725",
"Score": "3"
}
},
{
"body": "<p>Do not load your Cat with responsibilities of tracking all cats in the universe. That is way too much for a tiny little feline to handle and it breaks the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. Instead implement a cat factory that keeps track of the cats it breeds. Set cat constructor visibility so that it can only be called from the factory method.</p>\n<pre><code>public class Cat {\n Cat() {\n // Package private prevents construction by unauthorized sources.\n }\n}\n\npublic class CatFactory {\n public static Cat create() {\n // Instantiate cat, keep record, return.\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:23:59.107",
"Id": "243758",
"ParentId": "243725",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243735",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T17:38:07.030",
"Id": "243725",
"Score": "1",
"Tags": [
"java",
"static"
],
"Title": "Overriding static method with different static variable in java"
}
|
243725
|
<p>I created a script to automate the task of uploading a CSV file to Box. I have a couple of files a Box client and a MySQL client. I create an instance of both on the function.rb file which is the one below. I wonder if there is anything to improve? if there are principles I'm not following or if I'm breaking best practices.</p>
<p>Is there anything that can be improved?</p>
<pre><code>require 'json'
require 'date'
require 'dotenv/load'
require 'fileutils'
require 'csv'
require 'logger'
require './my_sql'
require './box_api'
require 'pry'
begin
year = ARGV[0]
month = ARGV[1]
day = ARGV[2]
search_timestamp = Time.new(year, month, day).utc
db_client = MySQL.new(search_timestamp)
emails = db_client.get_emails_from_db
return 'No new emails found' if emails.entries.empty?
box = BoxApi.new(ENV['BOX_USER_ID'])
date = DateTime.now.strftime("%m-%d-%Y").to_s
file_name = "access-emails-#{date}"
CSV.open("./tmp/#{file_name}.csv", "wb") do |csv|
emails.entries.each do |entrie|
csv << [entrie.values[0], entrie.values[1]]
end
end
box.upload_file_to_box("./tmp/#{file_name}.csv", file_name, ENV['BOX_FOLDER_ID'])
FileUtils.rm("./tmp/#{file_name}.csv")
puts "successfully uploaded CSV file to Box"
rescue StandardError => e
logger = Logger.new(STDOUT)
logger.level = ENV.fetch('LOG_LEVEL', Logger::INFO)
logger.datetime_format = '%Y-%m-%d %H:%M:%S '
logger.error("msg: #{e}, trace: #{e.backtrace.join("\n")}")
end
</code></pre>
|
[] |
[
{
"body": "<p>I think your script would benefit from some object oriented composition. Basically you have three different concerns.</p>\n<ul>\n<li>Config</li>\n<li>File backup (select from database and storage in CSV)</li>\n<li>File upload</li>\n</ul>\n<p>A few things could change now, for instance backup from a different source (different database, cloud etc), upload to a different remote service (e.g. dropbox). Additionally, having small composable objects would make it easier to test this.</p>\n<p>Here are some examples how to compose your script more object oriented.</p>\n<h2>Config</h2>\n<p>We could use an OpenStruct to store our config data. This way we only need to write our environment variables once, if we want to change them later there is only one place to update them.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>require 'ostruct'\n\nconfig = OpenStruct.new(\n year: ARGV[0],\n month: ARGV[1],\n day: ARGV[2],\n box_user_id: ENV['BOX_USER_ID'],\n box_folder_id: ENV['BOX_FOLDER_ID']\n)\n</code></pre>\n<h2>FileBackup</h2>\n<p>We can extract a backup file which just excepts rows and writes them to a CSV file. The dependency injection makes it also easier to test this (e.g. inject the data to write and the test directory)</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class BackupFile\n def initialize(rows:, date: DateTime.now.strftime("%m-%d-%Y").to_s, directory: "./tmp")\n @rows = rows\n @date = date\n end\n\n def save\n CSV.open(full_path, "wb") do |csv|\n rows.each do |entry|\n csv << [entry.values[0], entry.values[1]]\n end\n end\n end\n\n def full_path\n File.join(directory, filename)\n end\n\n def delete\n FileUtils.rm(full_path)\n end\n\n private\n\n attr_reader :rows, :date\n\n def file_name\n "access-emails-#{date}"\n end\nend\n\n\ndb_client = MySQL.new(search_timestamp)\nemails = db_client.get_emails_from_db\nreturn 'No new emails found' if emails.entries.empty?\n\nfile = BackupFile.new(emails.entries)\nfile.save\n</code></pre>\n<h2>Upload</h2>\n<p>The uploader accepts a client, path and remote folder. Also notice that we have an adapter around the <code>BoxApi</code> to implement a common interface <code>upload</code>. If we want to swap it out to upload to <code>Dropbox</code>, we only need to write a <code>DropboxClient</code> adapter which we can inject into the uploader. To test, we can write even a <code>TestClient</code>.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Uploader\n def initialize(client:, path:, remote_folder:)\n @client = client\n @path = path\n @remote_folder = remote_folder\n end\n\n def upload\n client.upload(path, file_name, remote_folder)\n end\n\n private\n\n attr_reader :client, :path, :remote_folder\n\n def file_name\n File.basename(path)\n end\nend\n\nclass BoxClient\n def initialize(client:, box_user_id:)\n @client = client.new(box_user_id)\n end\n\n def upload(path, file_name, remote_folder)\n client.upload_file_to_box(path, file_name, remote_folder)\n end\n\n private\n\n attr_reader :client\nend\n</code></pre>\n<h2>Error handling</h2>\n<p>I would move the error handling into the classes directly and also inject the logger. Something like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class BoxClient\n def initialize(client:, box_user_id:, logger: Logger.new)\n @client = client.new(box_user_id)\n end\n\n def upload(path, file_name, remote_folder)\n client.upload_file_to_box(path, file_name, remote_folder)\n rescue BoxError =>\n logger.error("Upload failed: #{e.message}")\n end\n\n private\n\n attr_reader :client\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T20:26:18.597",
"Id": "243731",
"ParentId": "243727",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243731",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T18:16:25.030",
"Id": "243727",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Ruby script implementation"
}
|
243727
|
<p>I have written a code for data management and parallel arrays but it has to be broken into methods/subroutines. Whenever I try to do so, some aspect of my code stops working. Would it be possible for anyone to roughly outline how and what I can break into subroutines without it causing problems in my code?</p>
<pre><code> Scanner keyedInput = new Scanner(System.in); // input
// variables
String userInput;
int numberOfBooks = 0; // setting to 0
int userChoice = 0; // setting to 0
final double taxAmount = 1.13;
boolean valid = false;
double total = 0; // setting to 0
double taxedTotal;
// while loop for number of books
while (valid == false)
{
// user enters info
System.out.print("Please enter the number of books you have purchased: ");
userInput = keyedInput.nextLine();
System.out.println();
// try catch statements for invalid input/exceptions
try
{
numberOfBooks = Integer.parseInt(userInput); // converting to int
valid = true; // setting to true so loop won't repeat
} // end of try
// outputting invalid input message
catch (NumberFormatException e)
{
System.out.println("Your input is not valid");
System.out.println();
} // end of catch
} // end of valid == false while loop
// arrays to hold info user will input
String bookName [ ] = new String [numberOfBooks];
double price [ ] = new double [numberOfBooks];
// user enters all data required
System.out.println("* * * * DATA ENTRY * * * *");
// for loop that prompts for and stores name of books purchases
for (int i = 0; i < numberOfBooks; i = i + 1)
{
System.out.println();
System.out.print("Please enter the name of book " + (i + 1) + ": ");
bookName[i] = keyedInput.nextLine(); // stores the name of each book in the array
// set valid to false again for loop below
valid = false;
// while loop for price of books
while (valid == false)
{
System.out.println();
System.out.print("Please enter the price of '" + (bookName[i] + "': "));
userInput = keyedInput.nextLine();
// try catch statements for invalid input/exceptions
try
{
price[i] = Double.parseDouble(userInput); // converting to double
valid = true; // setting to true so loop won't repeat
} // end of try
// outputting invalid input message
catch (NumberFormatException e)
{
System.out.println("Your input is not valid");
} // end of catch
} // end of valid == false while loop
} // end of for loop
// while loop to output data
while (userChoice != 3)
{
// set valid to false for loop below
valid = false;
while (valid == false)
{
// outputting choices menu
System.out.println();
System.out.println("* * * *\n" + "1. Output original data \n" + "2. Output calculated data \n" + "3. Exit \n" + "* * * *\n");
// user enters their choice
System.out.print("Please enter the number in front of your choice: ");
userInput = keyedInput.nextLine();
System.out.println();
// try catch statements for invalid input/exceptions
try
{
userChoice = Integer.parseInt(userInput); // converting to int
valid = true; // setting to true so loop won't repeat
} // end of try
// outputting invalid input message
catch (NumberFormatException e)
{
System.out.println("Your input is not valid");
System.out.println();
} // end of catch
} // end of valid == false while loop
// switch statements for each option
switch (userChoice)
{
// option 1
case 1:
{
// for loop to output existing data
for (int i = 0; i < numberOfBooks; i = i + 1)
{
System.out.println("'" + bookName[i] + "'" + " cost: " + price[i]);
} // end of for loop
break;
} // end of case 1
// option 2
case 2:
{
// calculations for total + taxed total
for (double value : price)
{
total = total + value;
total = Math.round(total * 100.0) / 100.0; // rounding
//totalAmount = totalAmount + total;
} // end of for loop
taxedTotal = (total * taxAmount); // calculating total with taxes
taxedTotal = Math.round(taxedTotal * 100.0) / 100.0; // rounding
System.out.println("Total: $" + total);
System.out.println("Taxed total: $" + taxedTotal);
break;
} // end of case 2
// option 3
case 3:
{
System.out.println("Goodbye!");
} // end of case 3
} // end of switch statements
} // end of userChoice while loop
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:42:34.673",
"Id": "478478",
"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": "<h3>How to broke your code into sub rutines</h3>\n<p>Well, there I see some util things you could do in order to separate the code:</p>\n<ul>\n<li>First, you could create some functions which job is to request the data to the user and until that data is correctly entered, the function continues requesting data, Example:</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> //let this be a static field so you can call it in any other new static function\n private static Scanner scanner = new Scanner(System.in);\n\n private static readInt(String requirement) {\n System.out.print(requirement + " : ");\n int input;\n boolean correctInput = false;\n do {\n try {\n input = scanner.nextInt();\n } catch (Exception ignored) {\n System.out.println("An error has occurred, introduce the number again");\n }\n } while(!correctInput);\n //equivalent to correctInput != true or correctInput == false\n return input;\n }\n</code></pre>\n<p>(I suppose you're working with only a main class which has the <code>public static void main</code>)</p>\n<p>I would recommend you to create two more functions <code>readString</code> and <code>readDouble</code> so that you are simplifying the data gathering process and not repeat code.</p>\n<ul>\n<li><p>Now, you use the <code>readString</code> function to request the user the book name and the <code>readDouble</code> for the book price. and so you are saving more code.</p>\n</li>\n<li><p>Finally, each case in a switch can be turned into a function.</p>\n</li>\n</ul>\n<h3>Referent to your code style</h3>\n<ul>\n<li>Do not use comparisons of type <code>if ([booleanVariable] == true)</code> or <code>if ([booleanVariable] == false)</code>, until I have knowledge it is also a comparison that your machine has to do in runtime, if you are coding a <em>very large system part</em> the effect will be more notorious. Instead use <code>if ([booleanVariable])</code> or <code>if (![booleanVariable])</code> the ! symbol means not.</li>\n</ul>\n<p>It doesn't apply only to Java, it works for many other languages (Python, C++, C, C#, GO, JS, PHP, ...), syntax may variate but still applies.</p>\n<ul>\n<li><p>Do not over-comment, it is good to have documentation about your code, but writting a lot of comments where it is intuitive what the code does, is bad, it consumes your time and the code gets messy.</p>\n</li>\n<li><p>Last, it perhaps is not the big deal, but most Java programmers uses</p>\n</li>\n</ul>\n<pre><code>[expression] { //this brace opening\n}\n\n[expression]\n{//rather than this.\n //I may say, it is more likely to be done for someone who comes from C#, C++ or C\n}\n</code></pre>\n<p>it doesn't matter at the end, but you know, some people care about it and well, it is better to work under the same language, using a common terminology.</p>\n<p>Note: certainly it is better to use <code>read</code> instead of <code>get</code> according to <a href=\"https://codereview.stackexchange.com/users/6499/roland-illig\">Roland Illig</a>'s comment.</p>\n<p><strong>Hope it helped you, cheers.</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T06:02:50.643",
"Id": "478440",
"Score": "0",
"body": "The method `getInt` is missing the return type. Instead of `get`, these method names should rather start with `read` since they have side effects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T00:22:34.133",
"Id": "243742",
"ParentId": "243730",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T20:00:08.910",
"Id": "243730",
"Score": "1",
"Tags": [
"java",
"subroutine"
],
"Title": "How to break my code into subroutines? - Java"
}
|
243730
|
<p>I solved this question on <a href="https://leetcode.com/problems/hand-of-straights/" rel="nofollow noreferrer">LeetCode.com</a>:</p>
<blockquote>
<p>Alice has a hand of cards, given as an array of integers. Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards. Return true if and only if she can. For e.g., for <code>hand=[1,2,3,6,2,3,4,7,8]</code> and <code>W=3</code>, the answer should be <code>true</code>.</p>
</blockquote>
<p>as:</p>
<pre>class Solution {
public:
bool isNStraightHand(vector<int>& nums, int k) {
if(nums.size()%k!=0) return false;
map<int, int> _m;
for(int num: nums) _m[num]++;
while(_m.size()) {
auto it=_m.begin();
int count=1;
int prev=it->first;
while(count<=k) {
it->second--;
if(count>1 && it->first-prev!=1) return false;
else prev=it->first;
count++;
if(it->second==0) {
auto backupIt=it;
_m.erase(backupIt); //am I causing UB here?
}
it++;
}
}
return true;
}
};
</pre>
<p>This works, but it doesn't look like a sturdy solution. I am curious to know if I am causing Undefined Behavior (UB) when erasing the element above. Earlier, I just had <code>_m.erase(it);</code>, but that wasn't good either. I think so, since the <a href="https://en.cppreference.com/w/cpp/container/map/erase" rel="nofollow noreferrer">official website</a> says:</p>
<blockquote>
<p>References and iterators to the erased elements are invalidated.</p>
</blockquote>
<p>so, when I do a <code>it++</code> in the following line, isn't that invalid? That part in particular can probably be improved.</p>
|
[] |
[
{
"body": "<p>The answer is "yes" it is UB. To fix it just rewrite the part as:</p>\n<pre><code>if(it->second==0) \n{\n it = _m.erase(it);\n}\nelse\n{\n it++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T01:59:12.177",
"Id": "478419",
"Score": "0",
"body": "@ALX23z, I am not sure it helps. If I don't `it++` after erasing the element, I wouldn't be pointing to the next one in the next iteration of the inner `while` loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T07:19:24.887",
"Id": "478447",
"Score": "1",
"body": "@J.Doe lookup reference for map::erase https://en.cppreference.com/w/cpp/container/map/erase it returns following iterator. What I wrote is basically from their example of use of erase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:00:15.567",
"Id": "478628",
"Score": "0",
"body": "good point! Thank you! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T00:02:39.730",
"Id": "243741",
"ParentId": "243740",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243741",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T23:47:53.163",
"Id": "243740",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"hash-map"
],
"Title": "Return whether the cards can be rearranged"
}
|
243740
|
<p>I implemented the intersection of two (convex) polygons in C++. It finds the polygon in the intersection like in this <a href="https://www.swtestacademy.com/wp-content/uploads/2017/05/convex-polygons-logo.png" rel="nofollow noreferrer">image</a>.</p>
<p>Looking for any and all feedback. I left the logic for line intersection and point containment out.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <cmath>
#include <iostream>
#include <optional>
using std::atan2;
using std::move;
using std::optional;
using std::vector;
using std::sort;
struct Point {
double x;
double y;
};
struct LineSegment {
Point u;
Point v;
};
// Returns the intersection point of l1 and l2 if it exists, nullopt otherwise.
// Unimplemented.
optional<Point> lineIntersection(const LineSegment& l1, const LineSegment& l2);
class Polygon {
public:
Polygon(const vector<Point>& points) : points_{points} {};
Polygon(const vector<Point>&& points) : points_{move(points)} {};
// Returns true if point is in Polygon, false otherwise.
// Unimplemented.
bool contains(const Point& point) const;
static Polygon intersect(const Polygon& p1, const Polygon& p2) {
vector<Point> points;
for (size_t i = 0; i < p1.points_.size(); ++i) {
// Add points of p1 contained in p2.
if (p2.contains(p1.points_[i])) {
points.emplace_back(p1.points_[i]);
}
for (size_t j = 0; j < p2.points_.size(); ++j) {
// Add points of intersection.
auto intersection = lineIntersection(
LineSegment{p1.points_[i], p1.points_[(i+1) % p1.points_.size()]},
LineSegment{p2.points_[j], p2.points_[(j+1) % p2.points_.size()]});
if (intersection != nullopt) {
points.emplace_back(move(intersection.value()));
}
}
}
// Add points of p2 contained in p1.
for (size_t i = 0; i < p2.points_.size(); ++i) {
if (p1.contains(p2.points_[i])) {
points.emplace_back(p2.points_[i]);
}
}
// Sort into counter-clockwise order.
sort(points.begin(), points.end(), [](Point a, Point b){ return atan2(a.y, a.x) > atan2(b.y, b.x); });
return Polygon{points};
}
private:
vector<Point> points_;
};
</code></pre>
|
[] |
[
{
"body": "<h1>Avoid <code>using</code> in header files</h1>\n<p>It looks like the code you have written is in a header file, which is to be included in an actual application that needs to intersect polygons. If you include this file, it also means you pull in all the <code>using</code> declarations, which could result in unexpected behavior. It might be safe to move the <code>using</code> declarations into <code>class Polygon</code>, but I'd rather avoid doing it altogether.</p>\n<p>You also forgot <code>using std::nullopt</code>.</p>\n<h1>The move constructor should take a non-<code>const</code> reference</h1>\n<p>Since you want to move things from an object, that object might have to be modified, so <a href=\"https://stackoverflow.com/questions/10770181/should-a-move-constructor-take-a-const-or-non-const-rvalue-reference\">move constructors should take non-<code>const</code> references</a>.</p>\n<h1>Consider adding <code>operator&()</code></h1>\n<p>Polygon intersection shares a lot of similarities with bitwise AND operations. It makes sense to add an <code>operator&()</code> to your class, so you can write:</p>\n<pre><code>Polygon a{...}, b{...};\nPolygon c = a & b;\n</code></pre>\n<h1>Your sorting function is wrong</h1>\n<p>You can't sort polygons into counter-clockwise order the way you did. The angles you calculate are relative to coordinate (0, 0), but the polygons themselves can be anywhere. You have to calculate the angles relative to a point inside the intersection.</p>\n<p>See <a href=\"https://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order\">this StackOverflow question</a> for a possible algorithm.</p>\n<p>Alternatively, since the points of the input polygons are already sorted, and the intersection of two convex polygons is just two pieces of each polygon concatenated, you should not need to sort at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T09:55:48.033",
"Id": "243762",
"ParentId": "243743",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243762",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T01:23:19.303",
"Id": "243743",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"interview-questions",
"c++17",
"computational-geometry"
],
"Title": "The intersection of two polygons in C++"
}
|
243743
|
<p>I created a simple enum macro that creates a <code>to_string</code> method for the enum. This has been done before, but my version is designed to compile quickly. From what I can tell, existing libraries use deep preprocessor macros and lots of template instantiations which is taxing for large enums.</p>
<p>Here is the code:</p>
<pre><code>#include <array>
#include <string_view>
#define EnumWithUnderlying(Name, NTy, ... )\
enum class Name : NTy {__VA_ARGS__, End };\
namespace std {\
std::string_view to_string(enum Name enumIn) noexcept {\
constexpr static string_view fullstr = #__VA_ARGS__ ", End ";\
struct BeginLen {\
std::size_t begin;\
std::size_t len;\
};\
using ArrIdxTy = std::array<BeginLen, NTy(Name::End)+1>;\
constexpr static ArrIdxTy begins = [&]() {\
ArrIdxTy ret = {};\
std::size_t jbegin = 0;\
std::size_t jend = 0;\
enum ParserState {Before,In,After};\
ParserState state = Before;\
for (std::size_t i = 0; i < fullstr.size(); ++i) {\
auto isSpace = [](char ch) -> bool {\
return ch == ' ' || ch == '\t' || ch == '\n';\
};\
switch (state) {\
case Before:\
if (!isSpace(fullstr[i])) {\
ret[jbegin].begin = i;\
jbegin++;\
state = In;\
} else {\
break;\
}\
case In:\
if (isSpace(fullstr[i]) || fullstr[i] == ',') {\
ret[jend].len = i - ret[jend].begin;\
jend++;\
state = fullstr[i] == ',' ? Before : After;\
} else {\
break;\
}\
break;\
case After:\
if (fullstr[i] == ',') {\
state = Before;\
}\
break;\
}\
}\
return ret;\
}();\
using ArrStrTy = std::array<std::string_view, NTy(Name::End)+1>;\
constexpr static ArrStrTy strs = [&]() {\
ArrStrTy ret = {};\
for (std::size_t i = 0; i < begins.size(); ++i) {\
ret[i] = std::string_view(fullstr.begin() + begins[i].begin, begins[i].len);\
}\
return ret;\
}();\
return strs[NTy(enumIn)];\
};\
}
#define Enum(Name,...) EnumWithUnderlying(Name, int, __VA_ARGS__)
</code></pre>
<p>Example usage:</p>
<pre><code>#include <iostream>
#include "enum.h"
EnumWithUnderlying(Move, char,
UP,
DOWN,
LEFT,
RIGHT
);
Enum(Letter, A, B);
int main() {
std::cout <<
std::to_string(Move::UP) << " " <<
std::to_string(Move::DOWN) << " " <<
std::to_string(Move::LEFT) << " " <<
std::to_string(Move::RIGHT) << " " <<
int(Move::End) << " " <<
std::to_string(Letter::A) << " " <<
std::to_string(Letter::B) << " " <<
std::endl;
}
</code></pre>
<p>I'm open to any comments, but I don't want to do anything that makes it take longer to compile.</p>
<p>Also, I noticed that making <code>to_string</code> constexpr/getting rid of the static members seems to generate worse code. I don't fully understand why that is since I'd expect a constexpr version to be strictly faster.</p>
<p>For the record this is also on <a href="https://raw.githubusercontent.com/joemalle/yet-another-enum/master/enum.h" rel="nofollow noreferrer">github</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T02:54:34.060",
"Id": "478427",
"Score": "0",
"body": "Just realized https://codereview.stackexchange.com/questions/38703/variadic-macro-enum-class-reflection-in-c11?rq=1 is very similar. Feel free to answer but I'lm also going to read thru that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T03:56:19.513",
"Id": "478433",
"Score": "1",
"body": "Why did you include all those extraneous backslashes? Frankly, imho, it make your code look like a jumbled mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T04:18:07.113",
"Id": "478435",
"Score": "0",
"body": "The backslashes allow the macro to be written on mutliple lines. I suppose I could factor out most of it into a function outside of the macro"
}
] |
[
{
"body": "<p>I’m really not a fan of this idea, on a lot of levels. First of all, it’s extremely limited; it only works for the most basic <code>enum</code> definitions. As soon as you add initializers or attributes, chaos ensues. Second, it’s just <em>absurdly</em> overcomplicated for what should be trivial code. The fact that you’re having problems with code gen should be a warning sign. There is no way I could justify the debugging effort if I tried to use this and something went sideways.</p>\n<p>In my opinion, manually rolling out a <code>to_string()</code> function for an enum isn’t <em>that</em> much extra work. Certainly not enough to justify the level of complexity of this macro. And if your primary concern is compile time (really? <em>that’s</em> the most important thing? how many enums do you have, and how big are they that this is even <em>measurable</em>, let alone the most crucial issue?), then a manually rolled function will compile <em>MUCH</em> faster than the code in that macro. Yeah, sure, you have to repeat yourself a little bit… but not <em>that</em> much. Certainly not enough to justify a state machine parser for a string (that also only works in the simplest cases).</p>\n<p>But okay, let me set aside my qualms about the overall idea, and focus on the code itself.</p>\n<pre><code>#define EnumWithUnderlying(Name, NTy, ... )\\\nenum class Name : NTy {__VA_ARGS__, End };\\\n</code></pre>\n<p>You don’t include any comments or documentation to explain the logic of the macro, so I don’t know if this extra <code>End</code> enumerator is a feature or a bug. In other words, I don’t know if there is a reason someone might <em>want</em> <code>End</code> added to their enumerators, or if you just added it to make your code work.</p>\n<p>Assuming it’s just there to make things work… the only purpose I can make out for it is that you use it to figure out the size of your enumerator arrays, such as in:</p>\n<pre><code>using ArrIdxTy = std::array<BeginLen, NTy(Name::End)+1>;\n</code></pre>\n<p>This “works” only so long as none of the enumerators have any initializers (that don’t happen to equal what their default values would be), but aside from being brittle, it’s also unnecessary. If all you need is the count of initializers, then all you need is something as simple as:</p>\n<pre><code>template <typename... Args>\nconstexpr auto count_args(Args&&...) noexcept\n{\n return sizeof...(Args);\n}\n\nusing ArrIdxTy = std::array<BeginLen, count_args(__VA_ARGS__) + 1>;\n</code></pre>\n<p>If <code>End</code> serves some other purpose, then fine, there’s no need to remove it… but in that case you <em>still</em> might want to get the number of enumerators using a count function like the one above. That way your macro won’t break if any enumerators have initialzers. (Well, it won’t break in that particular way, anyway.)</p>\n<pre><code>namespace std {\\\n std::string_view to_string(enum Name enumIn) noexcept {\\\n</code></pre>\n<p>There are a <em>very</em> limited number of cases where you are allowed to add stuff to <code>std</code>—really just a few templates that you are allowed to specialize in fairly restricted ways. Adding a completely new function? Definitely not allowed. No, not even if it’s an overload of an existing function.</p>\n<p>To make matters worse, the function lies. When I call <code>to_string()</code>… I expect to get a string. Not a <em>view</em> to a string.</p>\n<p>I figure that your goal is to be able to write <code>std::to_string(enum_value)</code>… but that goal is misguided. When I see <code>std::some_func()</code> that I’ve never seen before, the very first thing I do is go straight to my favourite standard library reference (<a href=\"https://en.cppreference.com/\" rel=\"nofollow noreferrer\">cppreference</a>) and read the docs. But I won’t find this function there, now will I?</p>\n<p>You might respond: “But it does the same thing <code>std::to_string()</code> does for all the types it is defined for!” Does it, though? If I do <code>auto x = Move::UP; std::cout << std::to_string(x);</code>, it will print “UP”. But if I do <code>auto x = SOME_INT_CONSTANT; std::to_string(x);</code> it will not print “SOME_INT_CONSTANT”. <code>std::to_string(int)</code> prints the (locale-flavoured) <em>value</em> of an int… not its name… yet your enumerator-specific <code>std::to_string()</code> functions print the <em>name</em>. Not the same thing, now is it?</p>\n<p>You might respond: “But what it does is so obvious!” Is it, though? I mean, ignoring that it actually <em>doesn’t</em> do what it claims to (it returns a <code>std::string_view</code>, not a <code>std::string</code>), converting an enumerator value to a string doesn’t necessarily mean returning the enumerator’s name. It might actually make more sense to return the enumerator’s numeric value as a string in some cases.</p>\n<p>So in summary:</p>\n<ul>\n<li><code>std::to_string()</code> is the wrong name for this function; and</li>\n<li>even if it weren’t, you can’t use it.</li>\n</ul>\n<p>So what’s the right name? Well, why not just <code>to_string()</code> in the same namespace as the enum? (Well, better would be <code>to_string_view()</code>, but one thing at a time.) ADL would find the function when you need it, so you’d only have to call <code>to_string(enum_value)</code>… which is actually <em>shorter</em> than <code>std::to_string(enum_value)</code>.</p>\n<p>(It might also make sense to define a <code>to_string()</code> function in terms of a <code>to_string_view()</code> function. That’s actually how I usually do it.)</p>\n<p>Now to get into the meat of the code… what this does (as I understand it) is take the variadic macro arguments, translate the bunch of them into a single string, then use a state machine to parse out the enumerator names into an array. As I mentioned above, your parser is too simplistic—it can’t handle initializers or attributes—but let’s ignore that issue for now.</p>\n<p>The biggest problem with your strategy is the assumption that all the enumerators in an enumeration have their default “natural” values. If they don’t, you probably have UB, because your enumerator values won’t be valid indexes into the array.</p>\n<p>A less critical issue is that if you really only want to support trivial enumerations (that is, no initializers), that’s fine… but in that case, this seems wildly over-complicated. All you need to do to find the Nth enumerator is find the (N−1)th comma and the Nth comma, take everything between them, then trim the whitespace. Special case the first and last enumerators (or don’t! add a leading and trailing comma to the string to simplify the algorithm!), and you’re done.</p>\n<p>If you intend to support general enumerations, then this design just won’t work: you can’t simply cast the enumerator to a number and use that as an index. You need a map. No, not a <code>std::map</code>; that would be overkill. <code>std::array<std::tuple<Name, std::string_view>></code> would suffice. To actually implement this, all you’d need is some kind of preprocessor for-each—either roll your own or use one from a library—then you could just do something like this:</p>\n<pre><code>// Takes an arbitrary enumerator string with arbitrary whitespace:\n// * "foo"\n// * "foo = N"\n// * "foo [[attribute]]"\n// * "foo [[attribute]] = N"\n// and extracts just the enumerator ("foo").\nconstexpr auto extract_enumerator(std::string_view) -> std::string_view;\n\n#define ENUM_STR_MAP_ITEM(enumerator) std::tuple{enumerator, extract_enumerator(#enumerator)},\n\nconstexpr auto enumerator_string_map = std::array{\n FOREACH(ENUM_STR_MAP_ITEM, __VA_ARGS__)\n};\n</code></pre>\n<p>And <code>to_string_view()</code> could use that map.</p>\n<pre><code>struct BeginLen {\\\n std::size_t begin;\\\n std::size_t len;\\\n};\\\n</code></pre>\n<p>So, your strategy is to parse the string into an array of <code>BeginLen</code> objects, then transform that into an array of <code>std::string_view</code>. But… why? A <code>std::string_view</code> is <em>literally</em> just a “begin” and a “len” <em>already</em>. The entire last quarter of your function is literally just a transform that does <code>std::string_view{begin, len}</code> for each <code>BeginLen</code>. Why not parse the enumerator strings directly into <code>std::string_view</code>s and skip that last bit?</p>\n<pre><code>std::size_t jbegin = 0;\\\nstd::size_t jend = 0;\\\n</code></pre>\n<p>Why do you need <em>two</em> indexes to keep track of which enumerator you’re currently parsing? (I mean, I <em>assume</em> that’s what those variables are for, in lieu of any comments or even clear names.) Couldn’t you drop <code>jend</code>, remove the <code>jbegin++;</code>, and replace <code>jend</code> with <code>jbegin</code> in the <code>In</code> case?</p>\n<h1>Summary</h1>\n<p>You have a number of critical bugs and conformance issues:</p>\n<ul>\n<li>You are not allowed to add new functions to namespace <code>std</code>. (An overload of an existing function is still a new function.)</li>\n<li>Your method for determining the number of enumerators is broken. (It only works for trivial enums, and it adds a new enumerator, which is not ideal (unless there’s another reason for it?).)</li>\n<li>Your method for mapping enumerators to their strings is broken. (You assume a trivial enum, where you can cast the enumerator value to an index.)</li>\n<li>Your method for parsing enumerator strings will only work properly for trivial enums. (For non-trivial enums it will return weird results, but technically (so far as I can tell) won’t actually trigger UB.)</li>\n</ul>\n<p>I know your primary performance concern is the compile time, but just in case you do care about run time performance… this code is extremely inefficient for what it actually does. It sounds like you don’t care; you figure it will all be <code>constexpr</code>ed away. Well, maybe, maybe not. There doesn’t seem to be any real reason not to make it more efficient in either case.</p>\n<p>Style-wise, my biggest complaint would have to be the complete lack of any commenting or documentation. I know commenting a macro isn’t the easiest thing to do. But it’s still worth it; especially for a macro as complicated as this.</p>\n<p>It also doesn’t help that most of your identifiers are terrible. <code>jbegin</code>? What’s “j”? <code>ArrStrTy</code>? Whut? A struct that contains only the members <code>begin</code> and <code>len</code> being called <code>BeginLen</code>? That’s really not helpful at all. A function called <code>to_string()</code> that doesn’t actually convert to a string?</p>\n<p>The other thing that raises my hackles is that your macros are mixed-case. That’s just <em>BEGGING</em> for trouble. (Even more alarming is that you use mixed-case macros <em>WHILE ALSO USING MIXED-CASE IDENTIFIERS</em>!!! There’s a point where you’ve loaded a gun, pointed it at your foot, taken the safety off, and started feathering the trigger, and if you end up blowing your foot off, no one can possibly take you seriously for being surprised.)</p>\n<p>(I’d also raise complaints about the header file being named “<code>enum.h</code>”. “<code>.h</code>” is for C header files. For C++ header files, you should use “<code>.hpp</code>”, “<code>.hxx</code>”, “<code>.hh</code>”, or something similar.)</p>\n<p>Overall design-wise… I might be convinced of the utility of a make-an-<code>enum</code>-with-a-built-in-<code>to_string</code> macro. But not if that macro is as complex as this. A macro should make my code <em>easier</em>… if a macro makes things harder (to understand, to debug), then it’s not worth it. If you could make this macro much, <em>MUCH</em> simpler (I have to figure out an ad hoc <em>state machine</em> just to get enumerator strings?!), then it might be worthwhile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T18:34:40.897",
"Id": "478534",
"Score": "0",
"body": "You make good points. I’ll accept if there are no other answers. I am still hoping to get feedback on constexpr-ness and compilation speed especially compared to other enum macros. FWIW I agree that using a regular enum is the best option but macros like this are prevalent and can be a bottle neck in compilation (according to clang’s trace at least)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:10:35.260",
"Id": "243778",
"ParentId": "243744",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243778",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T01:54:09.080",
"Id": "243744",
"Score": "2",
"Tags": [
"c++",
"c++17",
"enum",
"macros"
],
"Title": "C++17 enum macro with to_string operator"
}
|
243744
|
<p>While learning JavaScript I thought it was a good idea to make a digital clock program. I followed a youtube tutorial (with some tweaks to my preference) and came up with my final code that I have. I came to CodeReview to get the script reviewed, and to ask is there anything wrong with the script and/or any way to improve it as a whole. Ways to make the script shorter (yet also high in performance) are also accepted. I am also curious on if I have any 'red flags' currently. I will be giving the best answers the green checkmark. Thanks!</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 showTime() {
const date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
let session = (hours < 12) ? "AM" : "PM";
if (hours === 0) {
hours = 12;
} else if (hours > 12) {
hours -= 12;
}
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
const time = `${hours} : ${minutes} : ${seconds} ${session}`;
document.querySelector('div').innerHTML = time;
setTimeout(showTime,1000)
}
showTime()</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
</head>
<body>
<div></div>
<script src = "script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>TL;DR: I am a JavaScript programmer, and CSS currently isn't my suite, therefore I know that the clock can use some styling. How can the JavaScript code be improved?</p>
|
[] |
[
{
"body": "<h2>1</h2>\n<p>You are repeating <code>condition ? '0' + integer : integer</code> 3 times.</p>\n<p>This can be reduced with <a href=\"https://stackoverflow.com/a/2998874\"><code>const zeroPad = (num, places) => String(num).padStart(places, '0')</code></a></p>\n<p>and doing</p>\n<pre><code> hours = zeroPad(hours, 2);\n minutes = zeroPad(minutes, 2);\n seconds = zeroPad(seconds, 2);\n</code></pre>\n<p>The 2 is now a repeated magic number and you may wish to store it in a variable with a descriptive name.</p>\n<h2>2</h2>\n<p><code><script src = "script.js"></script></code></p>\n<p>Usually, there are no spaces around the equals sign:</p>\n<p><code><script src="script.js"></script></code></p>\n<h2>3</h2>\n<p>I'm not familiar with JavaScript, but I would replace the nested <code>setTimeout</code>:</p>\n<pre><code>function showTime() {\n // ...\n setTimeout(showTime, 1000)\n}\n</code></pre>\n<p>with a <code>setInterval</code>:</p>\n<p><code>setInterval(showTime, 1000);</code></p>\n<p>I would also place a space after the comma.</p>\n<h2>4</h2>\n<p>For formatting the time, take a look at this <a href=\"https://stackoverflow.com/a/8888498\">answer</a> which suggests using:</p>\n<pre><code>hours = hours % 12;\nhours = hours ? hours : 12;\n</code></pre>\n<h2>5</h2>\n<p>You use <code>document.querySelector('div')</code> but this <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\" rel=\"nofollow noreferrer\">"returns the first Element within the document that matches the specified selector"</a>.</p>\n<p>I would suggest using <code><div id="..."></div></code> and <code>document.getElementById</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T06:26:14.493",
"Id": "243753",
"ParentId": "243748",
"Score": "3"
}
},
{
"body": "<p>Some repeated code, i.e. <code>(<X> < 10) ? '0' + <X> : <X>;</code>, this can be factored into a utility in order to be more DRY. Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart\" rel=\"nofollow noreferrer\">string::padStart</a> you can ensure a string of minimum length is returned, padding the beginning of the string until it achieves the length.</p>\n<blockquote>\n<p>The <code>padStart()</code> method pads the current string with another string\n(multiple times, if needed) until the resulting string reaches the\ngiven length. The padding is applied from the start of the current\nstring.</p>\n</blockquote>\n<p>When <code>hours</code>/<code>minutes</code>/<code>seconds</code> is small enough a value to become a single digit this pads it back to "two digits". We run it through the <code>String</code> constructor to make it a string and able to use string functions.</p>\n<pre><code>const padTime = value => String(value).padStart(2, '0');\n</code></pre>\n<p>You can also precompute the hours into the range [0, 11] by taking a modulus 12. The <code>hours === 0</code> check will shift the hours to be in the range [1, 12].</p>\n<p>Use a <code>setInterval</code> instead of <code>setTimeout</code> and move it <em>outside</em> the function body. You'll need to invoke the function once initially, but the interval will handle each subsequent invocation to update display. By moving out of the body you'll avoid clock skew, i.e. the time between 1000 timeout expiration and the <em>next</em> timeout instantiation.</p>\n<p>Give the <code>div</code> you want to inject the time into a specific <code>id</code> so you can deterministically know where it'll be. I used an id of <code>time</code>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function showTime() {\n const date = new Date();\n let hours = date.getHours();\n let minutes = date.getMinutes();\n let seconds = date.getSeconds();\n let session = (hours < 12) ? \"AM\" : \"PM\";\n\n // Modulus 12 \"places\" the hours into 1 of 12 \"bins\" [0-11]\n // Checking for 0 and setting to 12 shifts \"bins\" to [1-12]\n // hours = hours % 12 || 12; is more succinct using the fact\n // that `0` is a falsey value.\n hours = hours % 12; // hours one of [0,1,2,3,4,5,6,7,8,9,10,11]\n if (hours === 0) {\n hours = 12; // hours one of [1,2,3,4,5,6,7,8,9,10,11,12]\n }\n \n const padTime = value => String(value).padStart(2, '0');\n\n const time = `${padTime(hours)} : ${padTime(minutes)} : ${padTime(seconds)} ${session}`;\n document.querySelector('#time').innerHTML = time;\n}\n\nshowTime();\nsetInterval(showTime, 1000);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n <html>\n <head>\n <title>Digital Clock</title>\n </head>\n <body>\n <div id=\"time\"></div>\n <script src=\"script.js\"></script>\n </body>\n </html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:55:34.410",
"Id": "478520",
"Score": "0",
"body": "I liked your solution to get rid of the down vote. One question, can you explain more of what the `pad` means?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:51:50.667",
"Id": "478530",
"Score": "0",
"body": "@DanielP533 Thanks. Updated answer with a bit more explanation around padding the start of the string."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T06:31:55.410",
"Id": "243754",
"ParentId": "243748",
"Score": "2"
}
},
{
"body": "<p>It's looking good and it works. A few remarks within the code</p>\n<pre><code>function showTime() {\n const date = new Date();\n let hours = date.getHours();\n let minutes = date.getMinutes();\n let seconds = date.getSeconds();\n let session = (hours < 12) ? "AM" : "PM";\n // You can stringify the minutes and seconds using a template string, \n // for later zero padding (see snippet).\n\n if (hours === 0) {\n hours = 12;\n } else if (hours > 12) {\n hours -= 12;\n }\n // ^ this can be a bit shorter using a ternary operator\n // or you can even do without it using hours % 12 (see snippet)\n hours = (hours < 10) ? '0' + hours : hours;\n minutes = (minutes < 10) ? '0' + minutes : minutes;\n seconds = (seconds < 10) ? '0' + seconds : seconds;\n // ^ modern es20xx knows a native string method called 'padStart'\n\n const time = `${hours} : ${minutes} : ${seconds} ${session}`;\n document.querySelector('div').innerHTML = time;\n // ^ you may want to use textContent \n // ^ if there's more in your document you may want to use an identifier \n // (e.g. id or a data-attribute)\n\n setTimeout(showTime,1000)\n // ^ do not forget semicolons\n}\n\nshowTime()\n// ^ do not forget semicolons\n</code></pre>\n<p>A note for the html within the snippet: you do not need a complete html document in code review snippets, your html will be automatically wrapped in a document.</p>\n<p>For the rationale to use semicolons, see <a href=\"https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/\" rel=\"nofollow noreferrer\">this article</a>.</p>\n<p>Why <code>textContent</code>? From <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML\" rel=\"nofollow noreferrer\">MDN</a></p>\n<blockquote>\n<p>It is not uncommon to see innerHTML used to insert text into a web\npage. There is potential for this to become an attack vector on a\nsite, creating a potential security risk.</p>\n</blockquote>\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>function showTime() {\n const date = new Date();\n // converting hour/minutes/seconds to zero padded strings right away\n const hours = `${(date.getHours() % 12) || 12}`.padStart(2, 0);\n // ^ hours: if the value is 0, js considers it to be 'falsy'\n // that's why we can use this 'short-circuit evaluation`\n const minutes = `${date.getMinutes()}`.padStart(2, 0);\n const seconds = `${date.getSeconds()}`.padStart(2, 0);\n const session = date.getHours() < 12 ? \"AM\" : \"PM\";\n // ^ because hours now is a string (and < 12)\n const time = `${hours} : ${minutes} : ${seconds} ${session}`;\n \n // use an identifier (data-attribute), and use textContent\n document.querySelector('div[data-isclock]').textContent = time;\n\n setTimeout(showTime,1000);\n}\n\nshowTime();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- added data-isclock -->\n<div data-isclock=\"1\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The clock method may even be shorter:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const currentTime = date => \n `${`${(date.getHours() % 12) || 12}`.padStart(2, 0)} : ${\n `${date.getMinutes()}`.padStart(2, 0)} : ${\n `${date.getSeconds()}`.padStart(2, 0)} ${\n date.getHours() < 12 ? \"AM\" : \"PM\"}`;\nsetInterval(() => \n document.querySelector(\"div[data-isclock]\")\n .textContent = currentTime(new Date()), 1000);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div data-isclock></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T06:55:43.087",
"Id": "243755",
"ParentId": "243748",
"Score": "1"
}
},
{
"body": "<p>I assume, that you are exercising formatting and handling time correctly, so I won't mention, that you could do it in a "oneliner" using the existing <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString\" rel=\"nofollow noreferrer\">api</a> (for the options see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat\" rel=\"nofollow noreferrer\">here</a>):</p>\n<pre><code> let options = {\n hour12: true,\n hour: "2-digit",\n minute: "2-digit",\n second: "2-digit"\n };\n\n function showTime() {\n container.textContent = (new Date()).toLocaleTimeString("en-US", options);\n }\nsetInterval(showTime, 1000);\n</code></pre>\n<hr />\n<p>Another way to format a number by is again to use the existing api instead of <code>String.padStart()</code>:</p>\n<pre><code> let x = 42;\n console.log(x.toLocaleString("en-US", { minimumIntegerDigits: 3 }));\n</code></pre>\n<p>Here the option speaks for itself, and the output is <code>"042"</code>.</p>\n<hr />\n<p>The other answers address the most to be said about your code. One thing not mentioned is, that your watch potentially can be as much as nearly one second behind the actual time,\nif it is started somewhere in between two seconds. To align with the system time, you could do the following:</p>\n<p><code>setTimeout(() => setInterval(showTime, 1000), 1000 - (new Date()).getMilliseconds());</code></p>\n<p>Here <code>setTimeout()</code> is waiting for the next system's second to occur, and then starting the watch by calling <code>setInterval()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:33:40.547",
"Id": "478513",
"Score": "0",
"body": "For now, you're the best answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:45:04.713",
"Id": "478516",
"Score": "0",
"body": "Nevermind, your code has an error and does not work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:47:53.537",
"Id": "478517",
"Score": "0",
"body": "@DanielP533: OK, so what is the error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:49:19.140",
"Id": "478518",
"Score": "0",
"body": "Nevermind, fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:52:44.847",
"Id": "478519",
"Score": "0",
"body": "Does IE and \"firefox for andrioid\" support this method though? The first one? Mozilla docs says \"IANA time zone names in timeZone option \" then gives it an X in both of the browsers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:55:45.433",
"Id": "478521",
"Score": "0",
"body": "@DanielP533: You can see the browser compatibility at the bottom of the link (api) above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T15:57:27.617",
"Id": "478522",
"Score": "0",
"body": "...well that's what I did and it given me an X for \"IANA time zone names in timeZone option\" which is why I am curious if your first solution works for those browsers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T03:23:16.250",
"Id": "478551",
"Score": "0",
"body": "@DanielP533: I can't give you any better advise than the documentation, so if your requirements are full support for IANA time zones, then you probably shouldn't use my suggestion. But from your own solution, I don't see that, that is the case as it produces a fixed en-US-format."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T14:56:47.543",
"Id": "243773",
"ParentId": "243748",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243754",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T04:23:34.383",
"Id": "243748",
"Score": "3",
"Tags": [
"javascript",
"html",
"ecmascript-6",
"dom"
],
"Title": "Digital Clock Script"
}
|
243748
|
<p>I'm going through books and various questions to improve my algorithm knowledge. I solved each NxN matrix first by hand and applied that process to build the code from that. I have done my best to break each task into its own step and keep them encapsulated. Below is the class followed by its accompanying unit tests. Having finished most of a unit testing book I also followed Test Driven Design (TDD) to write the tests before implementing the logic so I would know I'd achieved the correct answer.</p>
<p>Is there anything I can improve on my logic or naming to make readability clearer?</p>
<pre><code>public class Question7
{
public void RotateImage(ref uint[,] img, RotationDirection direction)
{
int elementsPerRow = ElementsPerRow(img);
int inflectionPoint = (elementsPerRow - 1) / 2;
for (int rowIndex = 0; rowIndex <= inflectionPoint; rowIndex++)
{
int lastColumnIndexToEdit = elementsPerRow - 1 - rowIndex;
for (int columnIndex = rowIndex; columnIndex < lastColumnIndexToEdit; columnIndex++)
{
if (direction == RotationDirection.Clockwise)
{
RotateClockwise(ref img, new Indices(rowIndex, columnIndex), elementsPerRow);
}
else
{
RotateCounterClockwise(ref img, new Indices(rowIndex, columnIndex), elementsPerRow);
}
}
}
}
private int ElementsPerRow(uint[,] img)
{
for (int i = 1; i * i <= img.Length; i++)
{
if (i * i == img.Length)
{
return i;
}
}
return -1;
}
private void RotateClockwise(ref uint[,] img, Indices topLeft, int elementsPerRow)
{
int lastIndex = elementsPerRow - 1;
Indices topRight = new Indices(topLeft.Column, lastIndex - topLeft.Row);
Indices botRight = new Indices(lastIndex - topLeft.Row, lastIndex - topLeft.Column);
Indices botLeft = new Indices(lastIndex - topLeft.Column, topLeft.Row);
uint toInsert = img[topLeft.Row, topLeft.Column];
//Insert into TopRight
uint justStored = img[topRight.Row, topRight.Column];
img[topRight.Row, topRight.Column] = toInsert;
toInsert = justStored;
//Insert into BotRight
justStored = img[botRight.Row, botRight.Column];
img[botRight.Row, botRight.Column] = toInsert;
toInsert = justStored;
//Insert into BotLeft
justStored = img[botLeft.Row, botLeft.Column];
img[botLeft.Row, botLeft.Column] = toInsert;
toInsert = justStored;
//Insert into TopLeft
img[topLeft.Row, topLeft.Column] = toInsert;
}
private void RotateCounterClockwise(ref uint[,] img, Indices topLeft, int elementsPerRow)
{
int lastIndex = elementsPerRow - 1;
Indices topRight = new Indices(topLeft.Column, lastIndex - topLeft.Row);
Indices botRight = new Indices(lastIndex - topLeft.Row, lastIndex - topLeft.Column);
Indices botLeft = new Indices(lastIndex - topLeft.Column, topLeft.Row);
uint toInsert = img[topLeft.Row, topLeft.Column];
//Insert into TopRight
uint justStored = img[botLeft.Row, botLeft.Column];
img[botLeft.Row, botLeft.Column] = toInsert;
toInsert = justStored;
//Insert into BotRight
justStored = img[botRight.Row, botRight.Column];
img[botRight.Row, botRight.Column] = toInsert;
toInsert = justStored;
//Insert into BotLeft
justStored = img[topRight.Row, topRight.Column];
img[topRight.Row, topRight.Column] = toInsert;
toInsert = justStored;
//Insert into TopLeft
img[topLeft.Row, topLeft.Column] = toInsert;
}
}
struct Indices
{
public int Row { get; }
public int Column { get; }
public Indices(int rowIndex, int columnIndex)
{
Row = rowIndex;
Column = columnIndex;
}
}
public enum RotationDirection
{
Clockwise = 0,
CounterClockwise = 1
}
</code></pre>
<p>I'm including the 4 most helpful tests to ensure I was producing correct results.</p>
<pre><code>[Fact]
public void A_2x2_matrix_rotated_clockwise()
{
uint[,] expected = new uint[2, 2]{ { 30, 10 }, { 40, 20 } };
uint[,] img = new uint[2, 2] { { 10, 20 }, { 30, 40 } };
var sut = new Question7();
sut.RotateImage(ref img, RotationDirection.Clockwise);
Assert.Equal(expected, img);
}
[Fact]
public void A_2x2_matrix_rotated_counterclockwise()
{
uint[,] expected = new uint[2, 2] { { 20, 40 }, { 10, 30 } };
uint[,] img = new uint[2, 2] { { 10, 20 }, { 30, 40 } };
var sut = new Question7();
sut.RotateImage(ref img, RotationDirection.CounterClockwise);
Assert.Equal(expected, img);
}
[Fact]
public void A_5x5_matrix_rotated_clockwise()
{
uint[,] expected = new uint[5, 5] { { 210, 160, 110, 60, 10 },
{ 220, 170, 120, 70, 20 },
{ 230, 180, 130, 80, 30 },
{ 240, 190, 140, 90, 40 },
{ 250, 200, 150, 100, 50 } };
uint[,] img = new uint[5, 5] { { 10, 20, 30, 40, 50},
{ 60, 70, 80, 90, 100 },
{ 110, 120, 130, 140, 150 },
{ 160, 170, 180, 190, 200 },
{ 210, 220, 230 , 240, 250 } };
var sut = new Question7();
sut.RotateImage(ref img, RotationDirection.Clockwise);
Assert.Equal(expected, img);
}
[Fact]
public void A_5x5_matrix_rotated_counterclockwise()
{
uint[,] expected = new uint[5, 5] { { 50, 100, 150, 200, 250 },
{ 40, 90, 140, 190, 240 },
{ 30, 80, 130, 180, 230 },
{ 20, 70, 120, 170, 220 },
{ 10, 60, 110, 160, 210 } };
uint[,] img = new uint[5, 5] { { 10, 20, 30, 40, 50},
{ 60, 70, 80, 90, 100 },
{ 110, 120, 130, 140, 150 },
{ 160, 170, 180, 190, 200 },
{ 210, 220, 230 , 240, 250 } };
var sut = new Question7();
sut.RotateImage(ref img, RotationDirection.CounterClockwise);
Assert.Equal(expected, img);
}
</code></pre>
<hr />
<p>Once confident in the rotation, I continued and implemented a method to generate an NxN matrix.</p>
<pre><code>public uint[,] GenererateNxNMatrix(int N, uint startValue, uint stepValue)
{
var img = new uint[N, N];
int row = 0;
int column = 0;
int counter = 0;
int totalElements = N * N;
for (uint i = startValue; counter < totalElements; i+= stepValue)
{
img[row, column] = i;
counter++;
if (counter % N == 0)
{
column = 0;
row++;
}
else
{
column++;
}
}
return img;
}
</code></pre>
<p>Along its accompanying unit test.</p>
<pre><code>[Fact]
public void Generate_3x3_matrix()
{
var expected = new uint[,] { { 1, 3, 5 }, { 7, 9, 11 }, { 13, 15, 17 } };
var sut = new Question7();
var actual = sut.GenererateNxNMatrix(3, 1, 2);
Assert.Equal(expected, actual);
}
</code></pre>
<p>Lastly I created method to generate a matrix that is already rotated.</p>
<pre><code>public uint[,] GenerateRotatedNxNMatrix(int N, RotationDirection rotationDirection, uint startValue, uint stepValue)
{
if (rotationDirection == RotationDirection.Clockwise)
{
return GenerateClockwiseRotatedNxNMatrix(N, startValue, stepValue);
}
else
{
return GenerateCounterClockwiseRotatedNxNMatrix(N, startValue, stepValue);
}
}
public uint[,] GenerateClockwiseRotatedNxNMatrix(int N, uint startValue, uint stepValue)
{
int row = 0;
int column = N - 1;
uint[,] img = new uint[N, N];
for (uint i = startValue; i <= N * N; i += stepValue)
{
img[row, column] = i;
if (i % N == 0)
{
row = 0;
column--;
}
else
{
row++;
}
}
return img;
}
public uint[,] GenerateCounterClockwiseRotatedNxNMatrix(int N, uint startValue, uint stepValue)
{
int row = N - 1;
int column = 0;
uint[,] img = new uint[N, N];
for (uint i = startValue; i <= N * N; i += stepValue)
{
img[row, column] = i;
if (i % N == 0)
{
row = N - 1;
column++;
}
else
{
row--;
}
}
return img;
}
</code></pre>
<p>With its accompanying unit tests.</p>
<pre><code>[Fact]
public void Generate_3x3_matrix_rotated_clockwise()
{
var expected = new uint[,] { { 7, 4, 1 }, { 8, 5, 2 }, { 9, 6, 3 } };
var sut = new Question7();
var actual = sut.GenerateRotatedNxNMatrix(3, RotationDirection.Clockwise, 1, 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Generate_3x3_matrix_rotated_counterclockwise()
{
var expected = new uint[,] { { 3, 6, 9 }, { 2, 5, 8 }, { 1, 4, 7 } };
var sut = new Question7();
var actual = sut.GenerateRotatedNxNMatrix(3, RotationDirection.CounterClockwise, 1, 1);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(3, RotationDirection.Clockwise, 1, 1)]
[InlineData(7, RotationDirection.Clockwise, 1, 1)]
[InlineData(99, RotationDirection.Clockwise, 1, 1)]
public void Rotated_matrix_matches_matrix_that_was_generated_already_rotated(int N, RotationDirection rotationDirection, uint startValue, uint stepValue)
{
var expected = new Question7().GenerateRotatedNxNMatrix(N, rotationDirection, startValue, stepValue);
var img = new Question7().GenererateNxNMatrix(N, startValue, stepValue);
var sut = new Question7();
sut.RotateImage(ref img, rotationDirection);
Assert.Equal(expected, img);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:09:21.543",
"Id": "478566",
"Score": "0",
"body": "(Anybody want to comment on Intels's `ipp(i)Transpose`?)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T06:02:12.937",
"Id": "243751",
"Score": "1",
"Tags": [
"c#",
"algorithm",
"array",
"matrix"
],
"Title": "Rotating a matrix by 90 degrees"
}
|
243751
|
<p>I'd like to see and hear some reviews on my current WinForms Login and Dashboard code.<br />
It's a desktop application to be used only internally and not over the web.</p>
<p>If you have any code suggestions - I'd be more than happy to see it and see where I can improve.</p>
<p><strong>LoginScreen.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Technical_Application.Classes;
using Technical_Application.Forms;
namespace Technical_Application
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
if (Properties.Settings.Default.username != string.Empty)
{
usernameTextBox.Text = Properties.Settings.Default.username;
}
}
//Login Button
private void loginBtn_Click_1(object sender, EventArgs e)
{
//MySQL connection to retrive user details into a class on succesfull log in
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
conn.Open();
//Get count, username, id, and their access id
using (var cmd = new MySqlCommand("select count(*), username, id, access from users where username = @username and password = MD5(@password)", conn))
{
cmd.Parameters.AddWithValue("@username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("password", passwordTextBox.Text);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
//Check whether user exists
if (dt.Rows[0][0].ToString() == "1")
{
//If the user exist - allow to log in
//Store the infrmation from the query to UserDetails class to be used in other forms
UserDetails.Username = dt.Rows[0][1].ToString();
UserDetails.userId = (int)dt.Rows[0][2];
UserDetails.accessId = (int)dt.Rows[0][3];
//Save the username details - for future logins
Properties.Settings.Default.username = dt.Rows[0][1].ToString();
Properties.Settings.Default.Save();
//Hide this form and open the main Dashboard Form
this.Hide();
var dashboard = new Dashboard();
dashboard.Closed += (s, args) => this.Close();
dashboard.Show();
}
//If failed login - show message
else
{
MessageBox.Show("Login failed", "Technical - Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
}
}
</code></pre>
<p><strong>UserDetails.cs</strong></p>
<pre><code>namespace Technical_Application.Classes
{
public class UserDetails
{
private static string _username;
private static int _userId;
private static int _accessId;
public static string Username
{
get
{
return _username;
}
set
{
_username = value;
}
}
public static int userId
{
get
{
return _userId;
}
set
{
_userId = value;
}
}
public static int accessId
{
get
{
return _accessId;
}
set
{
_accessId = value;
}
}
}
}
</code></pre>
<p><strong>Dashboard.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Technical_Application.Classes;
using Technical_Application.Forms.Settings.Admin;
using Tulpep.NotificationWindow;
using MySql.Data.MySqlClient;
using Technical_Application.Forms.SubForm.FSQM;
namespace Technical_Application.Forms
{
public partial class Dashboard : Form
{
public Dashboard()
{
InitializeComponent();
//Show welcome message
welcomeText.Text = $"Hello {UserDetails.Username}!";
//Depending on the users accessID load specific content only
if (UserDetails.accessId == 1)
{
}
if (UserDetails.accessId == 2)
{
viewRequestedDocumentsToolStripMenuItem.Visible = false;
adminControlToolStripMenuItem.Visible = false;
}
if (UserDetails.accessId == 3)
{
requestDocumentAmendmentToolStripMenuItem.Visible = false;
viewRequestedDocumentsToolStripMenuItem.Visible = false;
labelRoom.Visible = false;
adminControlToolStripMenuItem.Visible = false;
}
if (UserDetails.accessId == 4)
{
technical.Visible = false;
labelRoom.Visible = false;
production.Visible = false;
settings.Visible = false;
welcomeText.Text = $"Hello {UserDetails.Username}! \n Your account is set as inactive.";
}
}
//Check if form is already open
private Form findForm(string text)
{
var found = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f.Text == text);
if (!(found is null))
{
found.BringToFront();
if (found.WindowState == FormWindowState.Minimized)
{
found.WindowState = FormWindowState.Normal;
}
}
return found;
}
private void requestDocumentAmendmentToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Request Document Amendment");
if (found is null)
{
var newDoc = new Request_Document_Amendment();
newDoc.Show();
}
}
private void viewRequestedDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("View Requested Documents");
if (found is null)
{
var viewDoc = new ViewRequestedDocuments();
viewDoc.Show();
}
}
private void labelFormToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Label Room");
if (found is null)
{
var labelForm = new Technical_Application.Forms.Label_Form___Label_Room.Main();
labelForm.Show();
}
}
private void requestLabelSignOffToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Request Label Sign Off");
if (found is null)
{
var request_Label = new Request_Label_Sign_Off();
request_Label.Show();
}
}
private void labelSignOffSheetsToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Sign Off");
if (found is null)
{
var labelSignOff = new LabelSignOff();
labelSignOff.Show();
}
}
private void requestLabelsToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Production");
if (found is null)
{
var request_labels = new Technical_Application.Forms.Label_Form___Production.Main();
request_labels.Show();
}
}
private void adminControlToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Admin Control");
if (found is null)
{
var adminControl = new Admin_Control();
adminControl.Show();
}
}
private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
{
var found = findForm("Change Password - User");
if (found is null)
{
var changePassword = new Technical_Application.Forms.Settings.User.changePassword();
changePassword.Show();
}
}
private void FoodSafetyQM_Click(object sender, EventArgs e)
{
var found = findForm("FSQM");
if (found is null)
{
var FSQM = new FSQMMain();
FSQM.Show();
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Before I begin, I want to call out something really positive. It's great that you're using parameters when reading data from the database; it's very easy to fall into the trap of using plain string concatenation, and there are liable to be severe consequences in doing so.</p>\n<h3>Capitalize public property names in <code>UserDetails</code></h3>\n<p>Since these are all public properties, the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members#names-of-properties\" rel=\"nofollow noreferrer\">general guidelines from Microsoft</a> say they should be <code>UserId</code> and <code>AccessId</code>, not <code>userId</code> and <code>accessId</code></p>\n<h3>Mark <code>UserDetails</code> as <code>static</code></h3>\n<p>Because all the members are <code>static</code>.</p>\n<h3>Use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties\" rel=\"nofollow noreferrer\">auto-implemented properties</a> in <code>UserDetails</code></h3>\n<p>Since your fields are all private, and there's nothing special in either the getters or the setters, you should use auto-implemented properties. Auto-implemented properties can be used for <code>static</code> properties, and in a <code>static</code> class:</p>\n<pre><code>public static class UserDetails {\n public static string UserName {get;set;}\n public static int UserId {get;set;}\n public static int AccessId {get;set;}\n}\n</code></pre>\n<h3>Replace multiple <code>if</code> blocks which test on the same expression (<code>accessId</code>) with a <code>switch</code> in the <code>Dashboard</code> constructor</h3>\n<pre><code>switch (userDetails.AccessId) {\n case 2:\n viewRequestedDocumentsToolStripMenuItem.Visible = false;\n adminControlToolStripMenuItem.Visible = false;\n break;\n case 3:\n requestDocumentAmendmentToolStripMenuItem.Visible = false;\n viewRequestedDocumentsToolStripMenuItem.Visible = false;\n labelRoom.Visible = false;\n adminControlToolStripMenuItem.Visible = false;\n break;\n case 4:\n technical.Visible = false;\n labelRoom.Visible = false;\n production.Visible = false;\n settings.Visible = false;\n welcomeText.Text = $"Hello {UserDetails.Username}! \\n Your account is set as inactive.";\n break;\n}\n</code></pre>\n<h3>Refactor repetitive "find form or open new" code in <code>Dashboard</code></h3>\n<p>You have code like the following multiple times in <code>Dashboard.cs</code>:</p>\n<pre><code>var found = findForm("Request Document Amendment");\nif (found is null)\n{\n var newDoc = new Request_Document_Amendment();\n newDoc.Show();\n}\n</code></pre>\n<p>Firstly, do you expect there to be multiple windows of the same type with different values of the <code>Text</code> property? If not, I think it much more expressive to search for a form of a particular type.</p>\n<p>Also, if you pass in type information to <code>findForm</code> and the form is not found, <code>findForm</code> can use that type information to create a new form instance of that type.</p>\n<p>Something like this <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods\" rel=\"nofollow noreferrer\">generic method</a>:</p>\n<pre><code>private TForm findOrOpenForm<TForm>() where TForm : Form, new() {\n var found = Application.OpenForms.OfType<TForm>().FirstOrDefault();\n if (!(found is null)) {\n found.BringToFront();\n if (found.WindowState == FormWindowState.Minimized) {\n found.WindowState = FormWindowState.Normal;\n }\n } else {\n found = new TForm();\n found.Owner = this;\n found.Show();\n }\n return found; // This allows further actions outside of `findOrOpenForm`; you may not need it.\n}\n</code></pre>\n<p>which you could then call like this:</p>\n<pre><code>private void requestDocumentAmendmentToolStripMenuItem_Click(object sender, EventArgs e) => \n findOrOpenForm<Request_Document_Amendment>();\n</code></pre>\n<p>(NB. It may be possible to simplify this even further, but I think it would require some reflection.)</p>\n<h3>Consider using <a href=\"https://dev.mysql.com/doc/dev/connector-net/6.10/html/M_MySql_Data_MySqlClient_MySqlParameterCollection_Add_2.htm\" rel=\"nofollow noreferrer\"><code>Add</code></a> with an explicit data type instead of <a href=\"https://dev.mysql.com/doc/dev/connector-net/6.10/html/M_MySql_Data_MySqlClient_MySqlParameterCollection_AddWithValue.htm\" rel=\"nofollow noreferrer\"><code>AddWithValue</code></a></h3>\n<p>When you use <code>AddWithValue</code> to add parameters, you're relying on the MySQL provider to figure out the corresponding data type based the object that's been passed in. I know that -- at least in SQL Server -- there may be performance penalties if the algorithm guesses incorrectly (<a href=\"https://www.dbdelta.com/addwithvalue-is-evil/#:%7E:text=To%20follow%20best%20practices%2C%20avoid,and%20worth%20a%20few%20keystrokes.\" rel=\"nofollow noreferrer\">link1</a>, <a href=\"https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/\" rel=\"nofollow noreferrer\">link2</a>); I don't know if the same holds true for MySQL, but I would suggest checking this.</p>\n<h3>Consider using a <a href=\"https://dev.mysql.com/doc/dev/connector-net/8.0/html/T_MySql_Data_MySqlClient_MySqlDataReader.htm\" rel=\"nofollow noreferrer\"><code>DataReader</code></a> instead of <code>DataTable</code> and <code>DataAdapter</code></h3>\n<p>Per <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataadapters-and-datareaders\" rel=\"nofollow noreferrer\">Microsoft</a>:</p>\n<blockquote>\n<p>You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database.</p>\n</blockquote>\n<p>Since you're only retrieving a single row of data, and you're not reusing the retrieved data in any way (outside of the single row check), I think a <code>MySqlDataReader</code> is a better choice here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:28:36.563",
"Id": "478769",
"Score": "0",
"body": "Hello again :) .. thanks once again for an answer. Regarding the `findOrOpenForm` I have an error `The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:30:16.853",
"Id": "478770",
"Score": "1",
"body": "@LV98 Fixed. I'm writing all this stuff outside the IDE, so there may be some errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:43:44.903",
"Id": "478772",
"Score": "0",
"body": "@LV98 I've added another point, about DataReader."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:48:58.377",
"Id": "478773",
"Score": "0",
"body": "Appreciate your review Zev - making all my changes now and having a read about it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:11:11.247",
"Id": "478806",
"Score": "0",
"body": "Regarding open form.. what is the type of logic used? Is it a function or what is it?... Never seen anything like that in C#?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T13:30:57.473",
"Id": "478819",
"Score": "0",
"body": "Hi, if I wanted to add `.Owner = this;` to all forms opened, how would I implement it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T14:56:51.730",
"Id": "478822",
"Score": "1",
"body": "RE _Is it a function or what is it?_ @LV98 Do you mean `=>` (AKA \"fat arrow\")? [Expression-bodied members](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) is a syntax introduced in C# 6 and expanded in C# 7 that lets you use `=>` and a single expression instead of a full-blown method body.. And yes, it is a function in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:00:15.213",
"Id": "478825",
"Score": "1",
"body": "@LV98 RE `.Owner` -- Presumably `Owner` is a property on `Form`. I've updated `findOrOpenForm` to do this."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T05:38:10.140",
"Id": "243898",
"ParentId": "243759",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:36:50.727",
"Id": "243759",
"Score": "2",
"Tags": [
"c#",
"winforms"
],
"Title": "Windows Forms Log in and Dashboard"
}
|
243759
|
<p>Consider the following example code:</p>
<pre><code>c1 = ["Mary herself","Mary is mine","John himself","John is mine","Alan himself","Alan is mine"]
s1 = pd.Series(c1)
c2 = [1,2,3,4,5,6]
s2 = pd.Series(c2)
dictionary = {"A":s1,"B":s2}
df = pd.DataFrame(dictionary)
print(df)
for i in range(6):
name = df["A"].iloc[i]
if "Mary" in name:
print(name)
if "Alan" in name:
print(name)
else:
print("no")
</code></pre>
<p>I want to filter strings that include "Mary" or "Alan". My solution works well for only two cases, but I wonder if there is a more suitable solution for a lot more cases. For example, if I want to filter "John" and "Brown" too, I would already need four if statements.</p>
<p>How can I improve my code so I wouldn't have to add a new if statement for each name I want to filter?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T09:17:58.940",
"Id": "478467",
"Score": "3",
"body": "I see exactly *one* `if:…else:…` - can you make me see the issue with `so many if else`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T09:20:55.607",
"Id": "478468",
"Score": "0",
"body": "Sorry, I don't explain clearly. I mean there are two \"if:\" statement, if I want to filter more people, such as John, Brown,etc. There will be three four or five \"if:\" statement.\nDoes this unavoidable? The code will very long and difficult to maintain in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T09:26:04.240",
"Id": "478470",
"Score": "3",
"body": "That is a valid concern, presented understandably: *Put it in the question*!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:29:36.377",
"Id": "478475",
"Score": "1",
"body": "I edited the question to better highlight the concern explained in your comment @Samulafish"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:40:08.267",
"Id": "478476",
"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-06-12T14:33:19.633",
"Id": "478498",
"Score": "0",
"body": "Thank you for the suggestions, I will follow all the instructions to make a better thread in the future."
}
] |
[
{
"body": "<p>Your code follows this pseudo-code pattern:</p>\n<pre><code>if any of these strings are in name:\n do x\n</code></pre>\n<p>The simplest way to express that in Python is to invert the condition:</p>\n<pre><code>if name in any of these strings:\n do x\n</code></pre>\n<p>Or as actual Python:</p>\n<pre><code>if name in ["Alan", "Mary"]:\n print(name)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T13:03:50.623",
"Id": "478488",
"Score": "2",
"body": "better use a set for containment check `if name in {\"Alan\", \"Mary\"}:`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:15:34.697",
"Id": "478524",
"Score": "2",
"body": "This is wrong, since `\"Mary is herself\" in [\"Alan\", \"Mary\"]` will return `False`. @MaartenFabré `\"Mary is herself\" in {\"Alan\", \"Mary\"}` will return `False` a little faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T17:31:47.710",
"Id": "478531",
"Score": "1",
"body": ":facepalm:. Time for the weekend"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T10:30:31.330",
"Id": "243764",
"ParentId": "243760",
"Score": "5"
}
},
{
"body": "<h1>elif</h1>\n<p>Your code doesn't look like it will work the way you intend it to:</p>\n<pre><code> if "Mary" in name:\n print(name)\n if "Alan" in name:\n print(name)\n else:\n print("no")\n</code></pre>\n<p>If <code>name</code> contains <code>"Mary"</code>, but does not contain <code>"Alan"</code>, you will have two lines printed, due to the first <code>print(name)</code> and the <code>print("no")</code> statements. It would also print <code>name</code> twice in the string contained both <code>"Mary"</code> and <code>"Alan"</code>, like "Mary is Alan's"`.</p>\n<p>You probably wanted an <code>if</code>/<code>elif</code>/<code>else</code> statement:</p>\n<pre><code> if "Mary" in name:\n print(name)\n elif "Alan" in name:\n print(name)\n else:\n print("no")\n</code></pre>\n<p>This will print only once per row.</p>\n<h1>.startswith</h1>\n<p>Do you really want in? Should <code>"Anne"</code> match <code>"Mary-Anne is herself"</code>? Or are you looking for <code>name.startswith("...")</code> tests?</p>\n<p>Should <code>"Mary"</code> match <code>"Maryanne is herself"</code> or <code>"Mary-Anne is herself"</code>? Maybe you want to add a space to the end of the search term:</p>\n<pre><code> if name.startswith("Mary "):\n print(name)\n elif name.startswith("Alan "):\n print(name)\n else\n print(no)\n</code></pre>\n<p>Alternately, you may want to split <code>name</code> into words, and check for equality. You'll have to clarify your question.</p>\n<h1>or</h1>\n<p>If you want to do the same thing with multiple conditions, you could link them with <code>or</code>:</p>\n<pre><code> if name.startswith("Mary ") or name.startswith("Alan "):\n print(name)\n else\n print(no)\n</code></pre>\n<h1>any</h1>\n<p>If you want to test a long list of similar conditions, joined together with <code>or</code>, you are really wanting to test if <code>any</code> of the conditions match. Which is perfect for the <code>any(...)</code> function, which returns <code>True</code> if any of the conditions is <code>True</code>.</p>\n<p>Combined <code>any()</code> with a generator expression, to generate a series of conditions to test:</p>\n<pre><code>prefixes = ["Mary ", "Alan "]\nfor i in range(6):\n name = df["A"].iloc[i]\n if any(name.startwith(prefix) for prefix in prefixes):\n print(name)\n else:\n print("no")\n</code></pre>\n<h1>Loop like a native</h1>\n<p>Why are you looping over indices, and then extracting the data by index? Why hard-code the length of the range?</p>\n<pre><code>prefixes = ["Mary ", "Alan "]\nfor name in df["A"]:\n if any(name.startwith(prefix) for prefix in prefixes):\n print(name)\n else:\n print("no")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:14:35.430",
"Id": "243779",
"ParentId": "243760",
"Score": "4"
}
},
{
"body": "<p>If your series has many more rows than you have names to check (which should be the case), you should use the vectorized string functions in <code>pandas</code>.</p>\n<pre><code>names = ["Mary", "Alan"]\nnames_re = "|".join(names)\n\ndf = pd.DataFrame({"A": ["Mary herself","Mary is mine","John himself","John is mine","Alan himself","Alan is mine"],\n "B": [1,2,3,4,5,6]})\ndf[df["A"].str.contains(names_re)]\n\n# A B\n# 0 Mary herself 1\n# 1 Mary is mine 2\n# 4 Alan himself 5\n# 5 Alan is mine 6\n</code></pre>\n<p>This is because iterating over a series using Python is much slower than these vectorized functions which are run in C. Note that the combined search string is a regex looking for any of the names. Don't do this if you a hundred names or more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:19:28.440",
"Id": "478858",
"Score": "1",
"body": "Again, without start-of-line (`^`) and word-break (`\\b`) patterns in the regex, this would match `\"Alana is herself\"` and `\"Avoid Typhoid-Mary like the plague\"`, which may not be intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:21:07.193",
"Id": "478859",
"Score": "1",
"body": "@AJNeufeld It also may be intended. This answer reproduces the behavior in the OP (except for the different output format). The regex can be modified for different things if needed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T11:38:30.873",
"Id": "243914",
"ParentId": "243760",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T08:45:30.297",
"Id": "243760",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Searching for many different names in a Panda frame"
}
|
243760
|
<p>Here is my implementation of arg max in Scala. q_table_test.txt contains:</p>
<pre><code>["---------,'0','0','0','0','0','0','0','0','0', "X--------,'0.', '0.1', '0.1', '0.1', '0.1', '0.1', '0.1', '0.1', '0.1'"]
</code></pre>
<p>For example the String <code>---------,'0','0','0','0','0','0','0','0','0'</code> maps to key: <code>"---------"</code> , with values: <code>[0,0,0,0,0,0,0,0,0]</code>
After filtering values which are not valid I return the arg max of values from the list of positions.</p>
<p>Coming from a java background, what is a more functional programming principled method of implementing arg max?</p>
<p>Should the list filtering be contained in a separate function?</p>
<p>The <code>QTable apply()</code> method parses reads a file and returns <code>Map[String , List[Double]]</code> . It is evaluated lazily as it should just be evaluated once.</p>
<p>I think the use of apply in lazy val is not correct ?</p>
<p>Is this a 'good' method of finding the arg max value ?:</p>
<pre><code>val qValues = bindings.get(state).getOrElse(List.fill(8)(0.0)).zipWithIndex
val availableQValueBoardPositions = qValues.filter(f => remainingPositions.contains(f._2))
</code></pre>
<p>Complete code:</p>
<pre><code>import java.io.InputStream
import play.api.Environment
case class QTable(bindings: Map[String, List[Double]]) {
def getArgMaxValue(state: String, remainingPositions: List[Int]) = {
val qValues = bindings.get(state).getOrElse(List.fill(8)(0.0)).zipWithIndex
val availableQValueBoardPositions = qValues.filter(f => remainingPositions.contains(f._2))
availableQValueBoardPositions.maxBy(x => x._1)._2
}
}
object QTable {
private def getQTableFromFile(filename: String) = {
lazy val env = Environment.simple()
lazy val is: InputStream = Option(env.classLoader.getResourceAsStream(filename)).get
scala.io.Source.fromInputStream(is).mkString
}
private def cleanData(data: String): String = {
data.replace("\"", "").replace("\'", "").replace("[", "").replace("]", "")
}
def apply(filename: String) = {
val number_attributes_per_instance = 10;
val qtable = getQTableFromFile(filename)
lazy val cleanedQtable: String = cleanData(qtable)
lazy val dataInstances: List[List[String]] = cleanedQtable.split(",").toList.grouped(number_attributes_per_instance).toList
lazy val stateIdValues: List[String] = dataInstances.map(m => m.head.trim)
lazy val stateAttributeValues: List[List[Double]] = dataInstances.map(m => m.tail.map(x => x.toDouble))
lazy val policy: QTable = new QTable(stateIdValues.zip(stateAttributeValues).toMap)
policy
}
}
object ArgMain extends App {
print(QTable("q_table_test.txt").getArgMaxValue("---------", List(1, 2, 3)))
}
</code></pre>
|
[] |
[
{
"body": "<p>So you want the index of the maximum value in your collection. That's a lot of code for such a simple task.</p>\n<p>Let's start at the top.</p>\n<p><code>q_table_test.txt</code> - The sample data supplied is rather ridiculous. The elements that will become "attribute values" are all the same. How do you know the code is correct if there is no maximum? Does it matter which index is returned?</p>\n<p><code>QTable.apply(filename)</code> - The number_attributes_per_instance should be a configuration parameter, or derived directly from the input data. What if you needed to support more than one number_attributes_per_instance?</p>\n<p>You don't appear to know what a <code>lazy val</code> is and what it's for. Its usage here makes no sense.</p>\n<p>There are no safety checks. The file text is loaded as if formatting errors can't happen.</p>\n<p><code>getQTableFromFile()</code> - Why is <code>getResourceAsStream()</code> wrapped in an <code>Option</code> and then unwrapped with a <code>.get</code>? That's like loaning your brother a dollar so that he can repay the dollar he borrowed from you yesterday. A lot of busy work that accomplishes nothing.</p>\n<p><code>cleanData()</code> - Very inefficient.</p>\n<p><code>getArgMaxValue()</code> - If the <code>state</code> parameter is faulty you go through the trouble of building a bogus <code>qValues</code> list and then the elaborate and convoluted steps of finding the index of its max value, of which there is none. If you're going to lie to the user why not just return <code>remainingPositions.head</code> and be done with it?</p>\n<hr />\n<p>As a demonstration, here's a smaller yet safer implementation of the same basic outline.</p>\n<pre><code>import scala.util.{Try, Using} //Scala 2.13.x\n\nclass QTable(bindings: Map[String, Array[Double]]) {\n def getMaxValueIdx(state : String\n ,remainingPositions : List[Int]\n ) :Option[Int] =\n bindings.get(state)\n .flatMap(arr => remainingPositions.maxByOption(arr.lift))\n}\n\nobject QTable {\n private def loadFromFile(filename :String) :Try[String] =\n Using(scala.io.Source.fromFile(filename)) {\n _.getLines().map(_.takeWhile(_ != '#').trim).mkString\n }\n\n private val recFormat =\n """([^,"\\[\\]]+)\\s*,((\\s*('\\d*\\.?\\d*')\\s*,?)+)""".r.unanchored\n\n def apply(filename :String) :QTable =\n loadFromFile(filename).flatMap{ data => Try {\n recFormat.findAllMatchIn(data)\n .map(m => m.group(1) -> m.group(2)\n .split("[,\\\\s]+")\n .collect{case s"'$n'" => n.toDouble}\n ).toMap\n }}.fold(err => {println(err); new QTable(Map.empty)}\n ,new QTable(_))\n}\n</code></pre>\n<p>My <code>q_table_test.txt</code> file:</p>\n<pre><code>[\n"1st 9 Tbl,'0','1','2','3','4','5','6','7','8', #table of 9 elements\n"Short Tbl, '7' , '1.1','.22', '3' ,'12.0' , #mixed spacing\n"Split Tbl, '17', '1.25', '.127', '300.003' #1st part\n , '12.0', '4321', '.1234' , #2nd part\n"2nd 9 Tbl,'0.','0.9','0.8','0.7','0.6','0.5','0.4','0.3','0.2'"\n]\n</code></pre>\n<p>testing:</p>\n<pre><code>val qx = QTable("bogus.txt") // (No such file or directory)\nqx.getMaxValueIdx("1st 9 Tbl", List(7, 2, 3)) // None\n\nval qt = QTable("./q_table_test.txt")\nqt.getMaxValueIdx("1st 9 Tbl", List(7, 2, 3)) // Some(7)\nqt.getMaxValueIdx("1st 9 Tbl", List()) // None\nqt.getMaxValueIdx("Short Tbl", List(2,3,0)) // Some(0)\nqt.getMaxValueIdx("Short Tbl", List(2,3,990)) // Some(3)\nqt.getMaxValueIdx("NoSuchTbl", List(5,0,8)) // None\nqt.getMaxValueIdx("Split Tbl", List(5,0,8)) // Some(5)\nqt.getMaxValueIdx("2nd 9 Tbl", List(7, 2, 3)) // Some(2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T05:42:12.580",
"Id": "243962",
"ParentId": "243765",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243962",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T11:23:33.567",
"Id": "243765",
"Score": "2",
"Tags": [
"scala"
],
"Title": "argmax of List of Double"
}
|
243765
|
<p>First time creating my own Proxy handler, instead of copy pasting code.</p>
<p>Goal is to chain CSS definitions: <strong>style(element).color("red").background("green")</strong></p>
<p>and allow whole CSS objects:</p>
<p><strong>style(element).CSS({color:"red",font:"12 px Arial"}).background("green")</strong></p>
<h3>Any optimizations?</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let handler = {
get: (target, prop) => val => // getter returns a function
val ?
(
handler.set(target, prop, val), //process val parameter as setter
new Proxy(target, handler) // and return new proxy for chaining
)
//else:
: target[prop], // no parameter value, return property value
set: (target, prop, val) => prop === "CSS" ? Object.assign(target, val) : target[prop] = val
}
let style = element => new Proxy(element.style, handler);
let el = document.body.appendChild(document.createElement("div"));
el.style.backgroundColor = "red"; // standard non-Proxy way of setting styles
style(el).fontSize = "30px"; // style property name as SETTER
// Proxy allows for chaining because each function returns a Proxy again:
style(el)
.backgroundColor("green") // style property Name processed as function
.CSS({ // custom function applies CSS
width: "100px",
})
.CSS = { // custom SETTER applies CSS (last action in the chain)
color: "gold",
fontWeight: "bold",
textAlign: "center"
};
el.textContent = style(el).fontSize(); // GETTER as function notation!!</code></pre>
</div>
</div>
</p>
<h3>Update #1</h3>
<p>I reduced the <code>style()</code>function definition to a one-liner:</p>
<pre><code>let style = element => new Proxy(element.style, handler = {
get: (target, prop, proxy) => val =>
val ? (handler.set(target, prop, val), proxy) : target[prop],
set: (target, prop, val) =>
prop === "CSS" ? Object.assign(target, val) : target[prop] = val
});
</code></pre>
<p>any issues here?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T12:49:10.393",
"Id": "243767",
"Score": "1",
"Tags": [
"javascript",
"proxy"
],
"Title": "JavaScript Proxy: set DOM Element styles by chaining CSS setters"
}
|
243767
|
<p>I am writing a small application to generate the domain name of computers, from their known properties, and business rules.</p>
<p>My <code>Asset</code> class is:</p>
<pre><code>public enum AssetSite
{
Rotterdam,
Sydney,
}
public class Asset
{
/// <summary>
/// Gets the Asset Tag of the asset.
/// </summary>
public string AssetTag { get;}
/// <summary>
/// Gets the site to which the asset belongs.
/// </summary>
public AssetSite AssetSite { get; }
/// <summary>
/// Gets a value indicating whether the asset is a laptop.
/// </summary>
public bool IsLaptop { get; }
/// <summary>
/// Gets the name of the asset.
/// </summary>
public string Name
{
get
{
var nameBuilder = new StringBuilder();
nameBuilder.Append('I'); // Convention: All names start with I
// Second letter indicates the location of the PC.
if (this.AssetSite == AssetSite.Sydney)
{
nameBuilder.Append('S');
}
else if (this.AssetSite == AssetSite.Rotterdam)
{
nameBuilder.Append('R');
}
else
{
throw new ArgumentOutOfRangeException("Invalid site");
}
nameBuilder.Append("PC"); //Then, all PCs have 'PC' in their name.
if (this.IsLaptop)
{
nameBuilder.Append("L"); //Laptops get a "L" in their name
}
else
{
nameBuilder.Append("D"); //Desktops get a "D"
}
nameBuilder.Append(this.AssetTag); //Unique identifier of the computer
return nameBuilder.ToString();
}
}
</code></pre>
<p><code>Asset</code> objects are created through the deserialization of a JSON file</p>
<p>I am worried about my implementation of the <code>Name</code> getter. It feels way too long and complex, but at the same time, extracting each letter generation to a dedicated method feels way to complex as well.</p>
<p>My main concerns here are readability and maintainability.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T09:30:17.430",
"Id": "478581",
"Score": "0",
"body": "Not worthy of a full review, so I'll put it here: comments should not describe what but why. Things like `//Desktops get a \"D\"` should be clear from the code, otherwise you'd need to rewrite your code."
}
] |
[
{
"body": "<p>I would highlight two things:</p>\n<ol>\n<li>It is not really common to throw exception inside a property getter</li>\n<li>Because the <code>Name</code> has only just a getter then you can consider to expose it as a method instead.</li>\n</ol>\n<p>From implementation point of you, you can improve readability if you do something like this:</p>\n<pre><code>var nameBuilder = new StringBuilder();\nnameBuilder.Append('I'); \n\nvar siteWhitelist = new AssetSite[] { AssetSite.Sydney, AssetSite.Rotterdam };\nif (!siteWhitelist.Contains(this.AssetSite))\n throw new ArgumentOutOfRangeException("Invalid site");\n\nstring site = this.AssetSite switch\n{\n AssetSite.Sydney => "S";\n AssetSite.Rotterdam => "R"; \n};\n\nnameBuilder.Append(site);\nnameBuilder.Append("PC"); \n\nstring computerType = this.IsLaptop ? "L" : "D";\n\nnameBuilder.Append(computerType)\nnameBuilder.Append(this.AssetTag);\n\nreturn nameBuilder.ToString();\n</code></pre>\n<p>Of course you can further improve it, by introducing a <code>Dictionary<AssetSite, string></code> where you can store the mapping between sites and letters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T13:52:38.913",
"Id": "243771",
"ParentId": "243770",
"Score": "2"
}
},
{
"body": "<p>It is hard to tell because the AssetSite enum is small. Is the logic for generating Name is to take the first letter from AssetSite? If so, no need for ifs or switch case. And you don't need to update the function when a new site is added to the enum.</p>\n<h1>Error handling</h1>\n<p>In general, the creation of class should fail if it's data is invalid.</p>\n<p>Tomorrow you will add more code that use AssetSite, you don't want to handle invalid AssetSite in all the places that use it.</p>\n<p>What is the validation for AssetSite? Can it only be only from a closed set of values?\nAre you sure it should be an enum and not a string?</p>\n<h1>Conciseness</h1>\n<p>Maybe it is a matter of taste, I prefer to call <code>property</code> instead of <code>this.Property</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T07:56:55.840",
"Id": "243810",
"ParentId": "243770",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243771",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T13:24:14.030",
"Id": "243770",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Generate the name of a computer from its properties"
}
|
243770
|
<pre><code>int get_digits (int num)
{
if(num < 10)
return 1;
if(num < 100)
return 2;
if(num < 1000)
return 3;
if(num < 10000)
return 4;
if(num < 100000)
return 5;
if(num < 1000000)
return 6;
if(num < 10000000)
return 7;
if(num < 100000000)
return 8;
if(num < 1000000000)
return 9;
return 10; /* num > 1000000000 */
}
char *itoa (int n)
{
static char temp[10]; // MN that can be replaced by some def?
int nDigits = 0;
int i = 0;
if(n == 0)
{
temp[0] = '0';
temp[1] = '\0';
return temp; // or just return "0"; ?
}
nDigits = get_digits(n); // fast function to count digits..
temp[nDigits] = '\0'; // ..needed just here
for(i = n; i >= 1; i /= 10) // whole method stinks
{
temp[--nDigits] = ((i % 10) + '0'); // modulo is quite slow
}
return temp;
}
</code></pre>
<p>This is my implementation of the infamous function <code>itoa()</code>, which isn't available everywhere and more importantly not available in my environment. Generally, the implementation of this function is ought to be different anyway. Performance and memory optimization is important.
This function converts an integer to a string. The function owns the reference to the returned string, which is statically allocated and the caller is responsible to make a copy of the returned string if he plans on changing it or preserving it across subsequent calls.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T18:04:57.860",
"Id": "478532",
"Score": "0",
"body": "Some minor comments: You don't need to special case `n == 0` (since you will get the correct output with the rest of the code). `get_digits` (which should be completely eliminated) could possibly be improved a bit with some nested conditionals (`if (num < 100) return num < 10 ? 1 : 2;`), although smaller numbers will be more common that larger ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T05:02:46.813",
"Id": "478553",
"Score": "1",
"body": "@1201ProgramAlarm the loop at the bottom has `i >= 1`, therefore the special case for `n == 0` is indeed needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T17:56:43.970",
"Id": "478627",
"Score": "0",
"body": "@RolandIllig Ah, I missed seeing that. However, you can easily change that loop into `i = n; do { ... } while ((i /= 10) >= 1);` to avoid the overhead of a probably rarely needed special case."
}
] |
[
{
"body": "<p>The code almost works.</p>\n<p>To make it work in all cases, test the program with Valgrind, which detects undefined behavior because of invalid memory access. This will prove that the buffer needs to be 11 bytes long, not only 10.</p>\n<p>What about platforms where int has 64 bits instead of just 32? For these you need a larger buffer. Until then, you should use a <em>compile-time assertion</em> (static_assert) to ensure this implicit assumption.</p>\n<p>What about negative numbers? -6 is a valid integer as well, and it should be converted appropriately.</p>\n<p>If this function is the bottleneck of your whole program because it is too slow, have a look at how the Go programming language <a href=\"https://golang.org/src/strconv/itoa.go\" rel=\"noreferrer\">converts integers to strings</a>. It's in the <code>strconv</code> package and uses lots of nice tricks to cut down the number of integer divisions, since that's the most expensive machine instruction in your code.</p>\n<p>You can get rid of the <code>get_digits</code> function if you have the end of the string at a fixed address. Start with:</p>\n<pre><code>char *p = buf + sizeof buf - 1;\n*p = '\\0';\n</code></pre>\n<p>and then continue to fill the buffer from right to left by doing <code>*(--p) = '0' + digit</code>. At the end just <code>return p</code>, which will point to the first digit.</p>\n<p>The return type should be <code>const char *</code> instead of <code>char *</code> since the caller is not supposed to do anything to the buffer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:12:02.237",
"Id": "478683",
"Score": "0",
"body": "I just don't like referring to \"Go\" in a way that suggests that I (or everyone) actually know this language and can read it. Please talk C"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:30:16.850",
"Id": "478706",
"Score": "0",
"body": "I provided you with the Go code as additional information because it is quite simple to read for a C programmer. In contrast, the C libraries often use hard to read code or just use the straight-forward, unoptimized algorithm: [NetBSD](https://github.com/NetBSD/src/blob/1d3bf9c3887c1183e411dee14e1ba2e9d60de3e6/lib/libc/stdio/vsnprintf_ss.c#L398), [GNU libc](https://code.woboq.org/userspace/glibc/stdio-common/_itoa.c.html#_itoa_word), which is quite boring for learning tricks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T18:46:18.510",
"Id": "478717",
"Score": "0",
"body": "I don't know, personally me, with over 10 years of experience in C, I am completely fine with the way C looks and feels. Also don't want to distract myself with Go, and make an effort to learn it, at least for now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:29:16.070",
"Id": "243782",
"ParentId": "243777",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:07:57.627",
"Id": "243777",
"Score": "3",
"Tags": [
"performance",
"c",
"strings",
"integer",
"converting"
],
"Title": "Implementation of itoa"
}
|
243777
|
<p>This is a class from an <a href="https://github.com/georgebarwood/Database" rel="nofollow noreferrer">implementation of SQL in C# I am writing</a>. It fully buffers all reads and writes, and also logs changes to a <a href="https://github.com/georgebarwood/Database/blob/master/Log.cs" rel="nofollow noreferrer">log file</a> so that updates are atomic ( all or nothing ). It implements the standard IO.Stream methods, but also has a "FastRead" method that allows direct access to the buffer to increase read performance, intended to speed up the rate at which a SQL base table can be scanned. All feedback appreciated ( and also feedback on the rest of the project, available at the github link above ).</p>
<pre><code>namespace DBNS {
using IO = System.IO;
using G = System.Collections.Generic;
class FullyBufferedStream : IO.Stream
{
// Implementation of IO.Stream in which all writes are buffered, and buffers are kept for every page access ( unless Rollback is called ).
// Writes are recorded in the supplied log file, which ensures atomic updates.
// Flush() must be called to write changes to the underlying stream, alternatively Rollback() may be called to discard changes.
public FullyBufferedStream ( Log log, long fileId, IO.Stream f )
{
Log = log;
FileId = fileId;
BaseStream = f;
Len = BaseStream.Length;
Pos = 0;
ReadAvail = 0;
WriteAvail = 0;
}
readonly Log Log; // Log file to ensure atomic updates.
readonly long FileId; // For Log file.
readonly IO.Stream BaseStream; // Underlying stream.
long Len; // File length
long Pos; // Current position in the file
readonly G.Dictionary<long,byte[]> Buffers = new G.Dictionary<long,byte[]>();
readonly G.SortedSet<long> UnsavedPageNums = new G.SortedSet<long>();
// Buffer size constants.
const int BufferShift = 12; // Log base 2 of BufferSize.
const int BufferSize = 1 << BufferShift;
byte [] CurBuffer; // The current buffer.
long CurBufferNum = -1; // The page number of the current buffer.
int CurIndex; // Index into current buffer ( equal to Pos % BufferSize ).
int WriteAvail; // Number of bytes available for writing in CurBuffer ( from CurIndex ).
int ReadAvail; // Number of bytes available for reading in CurBuffer ( from CurIndex ).
bool UnsavedAdded; // Current buffer has been added to UnsavedPageNums.
public override long Seek( long to, System.IO.SeekOrigin how )
{
long newpos;
if ( how == System.IO.SeekOrigin.Begin )
newpos = to;
else if ( how == System.IO.SeekOrigin.End )
newpos = Len + to;
else // how == System.IO.SeekOrigin.Current
newpos = Pos + to;
if ( Pos != newpos )
{
Pos = newpos;
WriteAvail = 0;
ReadAvail = 0;
}
return newpos;
}
public override int Read( byte[] b, int off, int n )
{
int request = n;
while ( n > 0 )
{
int got = n > ReadAvail ? ReadAvail : n;
if ( got > 0 )
{
for ( int i = 0; i < got; i += 1 ) b[ off + i ] = CurBuffer[ CurIndex + i ];
off += got;
n -= got;
Pos += got;
CurIndex += got;
ReadAvail -= got;
}
else if ( Pos < Len ) DoSeek( true );
else break;
}
return request - n;
}
// Instead of copying bytes, if possible Fastread returns the underlying buffer and an index into it.
public byte[] FastRead( int n, out int ix )
{
if ( ReadAvail == 0 ) DoSeek( true );
if ( ReadAvail >= n )
{
ix = CurIndex;
CurIndex += n;
Pos += n;
ReadAvail -= n;
return CurBuffer;
}
else
{
byte [] result = new byte[ n ];
Read( result, 0, n );
ix = 0;
return result;
}
}
public override void Write( byte[] b, int off, int n )
{
Log.LogWrite( FileId, Pos, b, off, n );
if ( Pos + n > Len ) Len = Pos + n;
while ( n > 0 )
{
int got = n > WriteAvail ? WriteAvail : n;
if ( got > 0 )
{
if ( !UnsavedAdded )
{
UnsavedPageNums.Add( CurBufferNum );
UnsavedAdded = true;
}
for ( int i = 0; i < got; i += 1 ) CurBuffer[ CurIndex + i ] = b[ off + i ];
off += got;
n -= got;
Pos += got;
CurIndex += got;
WriteAvail -= got;
}
else DoSeek( false );
}
}
// Version of Write which checks the first byte written is zero.
public bool Write( byte[] b, int off, int n, bool checkFirstByteZero )
{
Log.LogWrite( FileId, Pos, b, off, n );
if ( Pos + n > Len ) Len = Pos + n;
while ( n > 0 )
{
int got = n > WriteAvail ? WriteAvail : n;
if ( got > 0 )
{
if ( checkFirstByteZero )
{
if ( CurBuffer[ CurIndex ] != 0 ) return false;
checkFirstByteZero = false;
}
if ( !UnsavedAdded )
{
UnsavedPageNums.Add( CurBufferNum );
UnsavedAdded = true;
}
for ( int i = 0; i < got; i += 1 ) CurBuffer[ CurIndex + i ] = b[ off + i ];
off += got;
n -= got;
Pos += got;
CurIndex += got;
WriteAvail -= got;
}
else DoSeek( false );
}
return true;
}
public void Rollback()
{
Buffers.Clear();
UnsavedPageNums.Clear();
UnsavedAdded = false;
ReadAvail = 0;
WriteAvail = 0;
CurBufferNum = -1;
}
public override void Flush()
{
foreach ( long bufferNum in UnsavedPageNums )
{
byte [] b = GetBuffer( bufferNum );
long pos = bufferNum << BufferShift;
long n = Len - pos;
if ( n > BufferSize ) n = BufferSize;
if ( BaseStream.Position != pos ) BaseStream.Position = pos;
BaseStream.Write( b, 0, (int)n );
}
UnsavedPageNums.Clear();
UnsavedAdded = false;
BaseStream.SetLength( Len );
BaseStream.Flush();
}
public override void Close()
{
Rollback();
BaseStream.Close();
}
public override void SetLength( long x )
{
Log.SetLength( FileId, x );
Len = x;
ReadAvail = 0;
WriteAvail = 0;
}
public override bool CanRead { get{ return true; } }
public override bool CanWrite { get{ return true; } }
public override bool CanSeek { get{ return true; } }
public override long Length { get{ return Len; } }
public override long Position { get{ return Pos; } set{ Seek(value,0); } }
void DoSeek( bool read )
{
if ( CurBufferNum != ( Pos >> BufferShift ) )
{
CurBufferNum = Pos >> BufferShift;
CurBuffer = GetBuffer( CurBufferNum );
UnsavedAdded = false;
}
CurIndex = (int) ( Pos & ( BufferSize - 1 ) );
if ( read )
{
ReadAvail = BufferSize - CurIndex;
if ( ReadAvail > Len - Pos ) ReadAvail = (int)( Len - Pos );
WriteAvail = 0;
}
else
{
WriteAvail = BufferSize - CurIndex;
ReadAvail = 0;
}
}
byte [] GetBuffer( long bufferNum )
{
byte [] result;
if ( Buffers.TryGetValue( bufferNum, out result ) ) return result;
result = new byte[ BufferSize ];
Buffers[ bufferNum ] = result;
long pos = bufferNum << BufferShift;
if ( BaseStream.Position != pos ) BaseStream.Position = pos;
int i = 0;
while ( i < BufferSize )
{
int got = BaseStream.Read( result, i, BufferSize - i );
if ( got == 0 ) break;
i += got;
}
return result;
}
} // end class FullyBufferedStream
} // end namespace DBNS
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:57:11.107",
"Id": "478631",
"Score": "0",
"body": "When `how == End` in `Seek(...)`, you set `newpos = Len + to;` - shouldn't that be `newpos = Len - to;`? Or else you seek beyond the length of the file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T19:11:19.600",
"Id": "478632",
"Score": "0",
"body": "@HenrikHansen I had to go and check ( https://docs.microsoft.com/en-us/dotnet/api/system.io.seekorigin), but it says \"The Seek methods take an offset parameter that is relative to the position specified by SeekOrigin\" and the example uses negative offsets which further clarifies. So I think it's correct as is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T04:19:35.520",
"Id": "478662",
"Score": "0",
"body": "OK, I now realize that we are \"inside\" the stream, so you expect `to` to be negative. That makes sense, but I would maybe check the sign of `to` before adding it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T05:08:40.810",
"Id": "478663",
"Score": "1",
"body": "It's legal ( and somewhat normal ) to seek beyond the end of the stream and then write, so positive offsets from End are not wrong - that said, I don't use Seek at all, let alone the End and Current options, instead assigning Position seems simpler. Which suggests a change : I think I will make that the \"core\" operation, with Seek setting position rather than Position calling Seek."
}
] |
[
{
"body": "<p>I discovered what I think is a flaw - in Flush() I call simply Flush() on the underlying stream, however I think this needs to be Flush(true) to ensure that all the changes are written before the log file is reset. I made the same change in Log.cs.</p>\n<p>This means changing the type of BaseStream to FileStream, as Flush(true) is specific to FileStream.</p>\n<p>The primitive I want is some kind of "fence" to say "write operations (all FileStreams) must not be re-ordered over this fence (either way)." However this doesn't seem to be available unless I have missed something - or perhaps plain Flush() has this effect, but if so, it doesn't seem to be documented.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:30:20.403",
"Id": "243908",
"ParentId": "243780",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:22:32.670",
"Id": "243780",
"Score": "2",
"Tags": [
"c#",
"sql",
"database"
],
"Title": "Fully buffered stream with atomic commit"
}
|
243780
|
<p>I've ported a prime-number calculation program from <a href="https://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html#primes" rel="nofollow noreferrer">primes.pyx</a> to C++ for benchmark purpose.</p>
<p>Since I wrote it in C++, I thought that my program would be faster than the original. However, mine took 25.8 ms at the fastest, while the original took only 1.45 ms on the same machine. I tested 10 times each, but got similar results (25.8~51.7ms vs 1.45~1.47ms). But, why?</p>
<p>Here's my code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <chrono>
using namespace std;
vector<int> primes(size_t nb_primes)
{
int n;
vector<int> p;
p.reserve(nb_primes);
n = 2;
while (p.size() < nb_primes)
{
bool other = true;
for (size_t i = 0; i < p.size(); i++)
{
if (n % p[i] == 0)
{
other = false;
break;
}
}
if (other)
p.push_back(n);
n += 1;
}
return p;
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
vector<int> p = primes(1000);
//for (auto i : p)
// cout << i << ' ';
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed Time: " << elapsed.count() << " s\n";
}
</code></pre>
<p>These algorithms are exactly the same, I believe.<br />
Please don't limit the check up to sqrt(n), to achieve a sieve of Eratosthenes.<br />
I need to compare with the original.</p>
<p>One thing I'm worried is the <code>for ... else</code> statement in the original.<br />
I borrowed the idea to use the <code>other</code> flag from <a href="https://stackoverflow.com/questions/24693694/is-there-an-equivalent-to-the-for-else-python-loop-in-c">Username: haccks</a>.<br />
If you can apply another <code>for ... else</code> method, please go ahead.</p>
<p>My Windows 10 machine (i5) spec:<br />
Clock Frequency: 1.60GHz 1.80GHz<br />
Memory: 8.00GB</p>
<p>I wrote the original version on Anaconda Prompt/Python 3.8.<br />
I write the C++ version on Visual Studio 2019.</p>
<p>If you need more information, please ask me.<br />
Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:49:34.480",
"Id": "478529",
"Score": "5",
"body": "What compiler optimisation options are you using? It completes in 1ms for me with `g++ -O3`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T18:13:49.107",
"Id": "478533",
"Score": "0",
"body": "You tagged this benchmarking, but how did you benchmark it? What optimizers on what system?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T18:36:15.867",
"Id": "478535",
"Score": "0",
"body": "@gmath I see! Thanks to you, I've just got `Elapsed Time: 0.0014516 s`! Please make it an answer; so I will accept it. Firstly, I was running in `Debug Mode` (sorry). Changing to `Release Mode` made it 2~7ms. Then, I set `Favor Size Or Speed` as `Favor fast code (/Ot)`. It made 1.45ms! Thank you sooo much!"
}
] |
[
{
"body": "<p>There are some optimizations that can make your code better, even with compiler optimizations turned on:</p>\n<p>Pre-allocate the vector and treat it like an array.</p>\n<p>Use a variable to keep track of the length.</p>\n<p>Putting these together, I found about a 10% increase in speed:</p>\n<pre><code>vector<int> primes(size_t nb_primes)\n{\n vector<int> p(nb_primes,2);\n int n = 2;\n size_t len_p = 0;\n while (len_p < nb_primes)\n {\n bool other = true;\n for (size_t i = 0; i < len_p; i++)\n {\n if (n % p[i] == 0)\n {\n other = false;\n break;\n }\n }\n if (other)\n p[len_p++] = n;\n n += 1;\n }\n return p;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T14:23:56.267",
"Id": "478597",
"Score": "0",
"body": "You're right, you improved 11.0% on average. In addition, your version is closer to the original since you introduced the variable `len_p`. `vector<int> p(nb_primes,2);` was new to me. It seems it's called [Expression List](https://ncona.com/2019/01/variable-initialization-in-cpp/). I'll learn these techniques. Thank you so much!\n\n/ Primes by me\n/ # of Tests: 100\n/ Average: 0.00141529\n/ Minimum: 0.0012612\n/ Maximum: 0.0023088\n/ Median: 0.0013155\n\n/ Primes by tinstaafl\n/ # of Tests: 100\n/ Average: 0.00127456\n/ Minimum: 0.0012637\n/ Maximum: 0.0016251\n/ Median: 0.0012686"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T20:28:42.497",
"Id": "243791",
"ParentId": "243781",
"Score": "2"
}
},
{
"body": "<p><strong>The code is not the cause of the slow down</strong></p>\n<blockquote>\n<p>Since I wrote it in C++, I thought that my program would be faster than the original. However, mine took 25.8 ms at the fastest, while the original took only 1.45 ms on the same machine.</p>\n</blockquote>\n<p>I get about 1ms when compiling with <code>g++ -O3</code>. So the code is achieves your goal of performing (at least as) well as the <code>.pyx</code> code, it must be your compilation options. C++ compilers often do not turn on optimisations by default. When bench-marking code ensure that you are compiling your code with optimisations on.</p>\n<p>As you mention there are optimisations that can be applied to the code, such as using <code>sqrt(n)</code>, which you won't use because you "need to compare with the original". Your code seems to be already as optimised as the <code>.pyx</code>, so any further optimisations may impair the comparison. You could avoid using <code>using namespace std;</code>, however, which is not usually recommended as using an entire name space can result in name collisions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T05:52:33.833",
"Id": "478562",
"Score": "0",
"body": "[This does not provide insight about the code in the question.](https://codereview.stackexchange.com/help/how-to-answer) And it does little to improve microbenchmarking skills or know-how."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:00:54.127",
"Id": "478564",
"Score": "0",
"body": "@greybeard Perhaps, but it is correct answer to the question asked (Why is my C++ code slower than '.pyx'). And the OP specifically asked *not* to optimise the algorithm past the `.pyx` code. Arguably this is the wrong site to ask the question, but the OP didn't know that till I answered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:07:02.173",
"Id": "478565",
"Score": "0",
"body": "I was the only one to make the observation that the code wasn't the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:47:39.460",
"Id": "478572",
"Score": "0",
"body": "That link mentions that short answers are fine, but `using namespace std;` is not recommended I guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T14:09:49.747",
"Id": "478593",
"Score": "0",
"body": "@gmatht Upvoted. As you suggested, my compiler optimization options were the main cause of the slowness. Also, thank you for telling me that `using namespace std;` is not recommended. Thank you so much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T14:10:27.143",
"Id": "478594",
"Score": "0",
"body": "People: If I were you guys, I would downvote **my question**, but not gmatht's answer. He came here to help me, and actually helped me. I didn't notice the compiler optimization options until he let me know. If something is wrong here, it's all my fault."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:28:06.950",
"Id": "478606",
"Score": "1",
"body": "@IanHacker It isn't always possible to avoid the XY problem, e.g asking for code optimisation when code isn't the cause; the recommendation is to give enough information to find the real problem (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). In this case you gave a complete working example together with your expected and actual result. Answering this question was fairly easy, so I think this is a relatively good question."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T02:28:44.043",
"Id": "243798",
"ParentId": "243781",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243791",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T16:27:26.803",
"Id": "243781",
"Score": "1",
"Tags": [
"c++",
"primes",
"benchmarking"
],
"Title": "Calculating primes: Could this be any faster?"
}
|
243781
|
<p>I'm writing a <a href="https://github.com/C-Coretex/Little-NeuralNetwork-Library" rel="nofollow noreferrer">NeuralNetwork library</a>, so everyone could use it and I'm wondering if I can optimize it even more.</p>
<p>Here is <a href="https://github.com/C-Coretex/Little-NeuralNetwork-Library" rel="nofollow noreferrer">my GitHub repo</a> if you want to check the whole project (I recommend using the <code>NeuralNetworkExample_FishersIris</code> project to test the performance of the Neural Network).</p>
<pre> using System;
namespace NN
{
[Serializable]
public struct Neuron
{
public double value;
public double[] weights;
// TODO: add error
}
}
</pre>
<hr />
<pre> using System;
using System.Runtime.Serialization.Formatters.Binary;
namespace NN
{
/// <summary>
/// This file is a library with public methods to use Neural Network.
/// Check another file to understand how to use the library.
/// You are free to use the library in yout own needs
/// </summary>
[Serializable]
public class NeuralNetwork //output = sum (weights * inputs) + bias
{
/// <summary>
/// The public struct(Neuron[][]) network. To access to the certain neuron type: network[i][j]
/// </summary>
public Neuron[][] Network { get; set; }
private double _moment = 0;
private double _learningRate = 1;
public double Moment
{
get { return _moment; }
set
{
if (value < 0 || value > 1)
{
throw new ArgumentException("Moment must be from 0 to 1");
}
_moment = value;
}
}
public double LearningRate
{
get{ return _learningRate; }
set
{
if (value <= 0)
{
throw new ArgumentException("Moment must be greater than 0");
}
_learningRate = value;
}
}
private int LayersCount => Network.Length;
private Neuron[][] deltaNetwork;
private double[][] previousWeights;
private uint[] withoutBiasLength;
//Introducing all the variables that are used in the functions, so garbage collector will no longer execute (it is used for perfomance optimization)
private int j;
private int i;
private int k;
private int a;
private double output;
private double Grad;
private double delta;
#region Network Initialization/Load/Save
/// <summary>
/// Creates the network.
/// </summary>
/// <param name="NeuronsAndLayers">The struct of the network. For instance, "4+ 15+ 5 3" whare '+' means bias. Watch readme</param>
/// <param name="randMin">Minimal random weight of synapse.</param>
/// <param name="randMax">Maximal random weight of synapse.</param>
public NeuralNetwork(string NeuronsAndLayers, double randMin, double randMax)
{
Random rand = new Random();
string[] neuronsSTR = NeuronsAndLayers?.Split(' ');
Network = new Neuron[neuronsSTR.Length][];
withoutBiasLength = new uint[neuronsSTR.Length];
System.Collections.ArrayList biases = new System.Collections.ArrayList();
for (i = 0; i < neuronsSTR.Length; ++i) //Count of neurons in each layer
{
try //Check if there are biases
{
uint index = Convert.ToUInt32(neuronsSTR[i]);
Network[i] = new Neuron[index];
withoutBiasLength[i] = index;
}
catch (Exception) //If bias is in the layer then
{
if (i == neuronsSTR.Length - 1)
throw new Exception("You cannot add biases to OUTPUT layers");
else
{
biases.Add(i);
uint index = Convert.ToUInt32(neuronsSTR[i].Substring(0, neuronsSTR[i].Length-1)) + 1;
Network[i] = new Neuron[index]; //Convert only count of neurons without bias(+)
Network[i][index - 1].value = 1;
withoutBiasLength[i] = index - 1;
}
}
}
previousWeights = new double[Network.Length][];
//Distribution of values in weights of Neural Network and initializing PreviousWeights
for (i = 0; i < Network.Length - 1; ++i) // Every layer in this NeuralNetwork
{
previousWeights[i] = new double[Network[i].Length * withoutBiasLength[i + 1]];
uint countOfWeights = 0;
for (j = 0; j < Network[i].Length; ++j) // Every neuron in layer[i]
{
Network[i][j].weights = new double[withoutBiasLength[i + 1]];
for (uint a = 0; a < Network[i][j].weights.Length; ++a) // Every weight from neuron[i][j]
{
previousWeights[i][countOfWeights] = 0; //PrewiosWeight on the first iteration = 0
++countOfWeights;
weightWasZeroREPEAT:
Network[i][j].weights[a] = Math.Round(rand.NextDouble() * (randMax - randMin) + randMin, 5); //Random value for the weight
if (Network[i][j].weights[a] == 0)
goto weightWasZeroREPEAT; //Value of weight cannot be 0
}
}
}
//Creating a copy of NeuralNetwork to work with it
deltaNetwork = new Neuron[Network.Length][];
for (i = 0; i < Network.Length; ++i)
{
deltaNetwork[i] = new Neuron[Network[i].Length];
for (j = 0; j < Network[i].Length; ++j)
deltaNetwork[i][j] = Network[i][j];
}
}
/// <summary>
/// Loads the network.
/// </summary>
/// <param name="pathAndName">The path to the file with its name.</param>
public NeuralNetwork(string pathAndName)
{
if (System.IO.File.Exists(pathAndName))
{
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(pathAndName, System.IO.FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
NeuralNetwork n = (NeuralNetwork)formatter.Deserialize(fs);
Network = n.Network;
previousWeights = n.previousWeights;
Moment = n.Moment;
LearningRate = n.LearningRate;
}
}
catch(Exception ex)
{
throw new System.IO.IOException($"Couldn't open file {pathAndName}\r\n{ex.ToString()}");
}
//Creating a copy of NeuralNetwork to work with it
deltaNetwork = new Neuron[Network.Length][];
for (i = 0; i < Network.Length; ++i)
{
deltaNetwork[i] = new Neuron[Network[i].Length];
for (j = 0; j < Network[i].Length; ++j)
deltaNetwork[i][j] = Network[i][j];
}
}
else
throw new System.IO.FileNotFoundException("This file does not exist.\rTry to recheck the path or just save new Neural Network with <SaveNetwork> method", pathAndName);
}
/// <summary>
/// Saves the network.
/// </summary>
/// <param name="pathAndName">The path to the file with its name.</param>
public void SaveNetwork(string pathAndName)
{
using (System.IO.FileStream fs = new System.IO.FileStream(pathAndName, System.IO.FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, this);
}
}
#endregion
#region NeuralNetwork Run
/// <summary>
/// Runs the network and returns reference to Output neurons with the struct Neuron[].
/// </summary>
/// <param name="inputValues">This is array that contains input set.</param>
/// <returns>Neuron[] reference</returns>
public virtual ref Neuron[] RunNetwork(double[] inputValues)
{
//INPUT neurons assignment
for (j = 0; j < inputValues.Length; ++j)
Network[0][j].value = inputValues[j];
for (i = 1; i < LayersCount; ++i)
{
for (j = 0; j < withoutBiasLength[i]; ++j) // Every neuron in layer[i]
{
// Calculation value of the neuron, depending on all values of neurons and weights of synapses connected to this neuron
output = 0;
for (k = 0; k < Network[i - 1].Length; ++k) // Summ of every neuron in layer[i-1] * every neuron of weight[i-1] = weight[j]
output += Network[i - 1][k].value * Network[i - 1][k].weights[j];
//Value activation
Network[i][j].value = Sigmoid(output);
}
}
return ref Network[Network.GetLength(0) - 1];
}
//===========================================================================================================
private double Sigmoid(double num)
{
return (1.0 / (1 + Math.Pow(Math.E, -num)));
}
#endregion
#region NeuralNetwork Train
/// <summary>
/// Function to Train the network after run
/// </summary>
/// <param name="ideal">Expected values(double[]).</param>
public virtual void TeachNetwork(double[] ideal)
{
//Calculating Delta(OUT) for OUTPUT neurons of the NeuralNetwork
for (i = 0; i < ideal.Length; ++i)
deltaNetwork[LayersCount - 1][i].value = DeltaOut(ideal[i], Network[LayersCount - 1][i].value);
//Calculating Delta(HIDDEN) for HIDDEN neurons the NeuralNetwork
for (i = LayersCount - 2; i >= 1; --i) //Start - from the last HIDDEN layer | End - to the firs HIDDEN layer
for (j = 0; j < Network[i].Length; ++j)
deltaNetwork[i][j].value = DeltaHidden(Network[i][j].weights, ref deltaNetwork[i + 1], Network[i][j].value);
//Calculating delta of all the weights to change them
for (i = LayersCount - 2; i >= 0; --i) // Start - from the last HIDDEN layer | End - to the firs layer (INPUT)
for (j = 0; j < Network[i].Length; ++j) // Every neuron in layer[i]
for (a = 0; a < Network[i][j].weights.Length; ++a) // Every weight from neuron[i][j]
{
Grad = Network[i][j].value * deltaNetwork[i + 1][a].value; //Calculating gradient(gradient descent) for the weight
delta = _learningRate*Grad + _moment*previousWeights[i][j]; //Calculating delta of the weight
Network[i][j].weights[a] += delta; //Change the weight of synapse (ActualWeight + DeltaOfThisWeight)
previousWeights[i][j] = delta;
}
}
/// <summary>
/// Function to Train the network.
/// </summary>
/// <param name="input"> Values for INPUT neurons </param>
/// <param name="ideal"> Expected values for OUTPUT neurons </param>
public virtual void TeachNetwork(double[] input, double[] ideal)
{
RunNetwork(input);
TeachNetwork(ideal);
}
//===========================================================================================================
private double SigmoidError(double output)
{
return (1 - output) * output;
}
private double DeltaOut(double outIdeal, double outActual)
{
return ((outIdeal - outActual) * SigmoidError(outActual));
}
private double DeltaHidden(double[] weights, ref Neuron[] delta, double output)
{
double actualSum = 0;
for (k = 0; k < weights.Length; ++k) //((w1 * d1) + (w2 * d2) + .. + (wn * dn))
actualSum += weights[k] * delta[k].value;
return (SigmoidError(output) * actualSum);
}
#endregion
}
}
<span class="math-container">```</span>
</pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:42:58.973",
"Id": "478544",
"Score": "2",
"body": "`// TODO: add error` Unique!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T14:28:17.237",
"Id": "478598",
"Score": "1",
"body": "Does this work? Have you tested it on some dataset? I'd suggest you make a standalone program that uses your NN to try to solve a specific task (e.g. reading hand written numbers - http://yann.lecun.com/exdb/mnist/). If that works, great! But as it stands, you're not really giving anyone a reason to want to use your library. What does it do? Why should I use it? And finally, Code Review isn't for reviewing code that's unfinished or not working properly. Don't be afraid to add too much code, it's always better that too little!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:10:36.620",
"Id": "478629",
"Score": "0",
"body": "@cliesens It works. At the first time, I left a link to my GitHub repository with a working project, but I was informed that it is incorrect to leave links to GitHub repos here. This code is finished and, if you are interested, I can leave a link to the project. \nWhat about why should you use this, I understand that tool like Tensorflow is way more powerful than mine, but I just wanted to make a neural network from scratch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T04:29:57.650",
"Id": "478753",
"Score": "1",
"body": "I have readded the link to the github repo. You always can add a link to your repo as long as you post the code in the question as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T06:44:23.243",
"Id": "478762",
"Score": "0",
"body": "@Heslacher Thank you, I've changed this"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T19:06:58.243",
"Id": "243787",
"Score": "1",
"Tags": [
"c#",
"performance",
".net",
"library",
"neural-network"
],
"Title": "C# Neural Network project"
}
|
243787
|
<h2>The problem</h2>
As a Front-end developer, I do not have control over the data that is returned from the Backend. I sometimes notice that the data shape and types I expect on the Front-end are different from the actual data inside the API response. I don't want to manually look up these differences and I want to have some kind of report that points out these cases: <br><br>
<p><strong>1. Missing Property</strong> - some properties that I expect are not found inside the response data</p>
<p><strong>2. Unexpected Property</strong> - extra properties inside the response data that I don't expect</p>
<p><strong>3. Type Mismatch</strong> - the types on certain properties inside the response data are different from what I expect</p>
<p><strong>4. Nullable Mismatch</strong> - I don't expect the value on certain properties to be <em>null</em></p>
<p>Based on this, I'm trying to create <code>apiDiffCheckReport</code>, that generates the mentioned report and checks whether <code>res.data</code> is safe to dump inside my typed <code>users</code> array. So I can simply do this after every API GET response:</p>
<pre><code>const res = await axios.get("https://my.api.com/users")
const [isResDataSafe, report] = apiDiffCheckReport(res.data) // <-- res.data is always type of <any>
if (isResDataSafe) {
const users: User[] = res.data // <-- here res.data is "type of <User[]>"
}
</code></pre>
<h2>The solution</h2>
To be more specific, I have a TypeScript User model (this is how I expect the response data to look like):
<p><em>models/User.ts</em></p>
<pre><code>export interface Comment {
id: number;
body: string;
}
export interface User {
id: number;
createdAt?: string;
newsLetter?: boolean;
name: string;
age: number;
comments?: Comment[];
}
</code></pre>
<p>and my API returns the following data after calling the <code>/users</code> endpoint:</p>
<p><em>API Response data</em></p>
<pre class="lang-js prettyprint-override"><code>[
{
"id": "0", // <-- Should detect this as 3. Type Mismatch,
// because I expect a <number> here
"createdAt": "2020-06-06T08:34:49.749Z",
"newsLetter": true,
"isPremium": false, // <-- Should detect this as 2. Unexpected Property,
// because I don't expect this property
"name": "John",
// <-- Should detect this as 1. Missing Property,
// because I expect an `age` property here
"comments": [
{
"id": null, // <-- Should detect this as 4. Nullable Mismatch,
// because I don't expect <null> here
"subtitle": "my first comment" // <-- Should detect this as 2. Unexpected Property,
// because I don't expect this property
// <-- Should detect this as 1. Missing Property,
// because I expect a `body` property here
}
]
},
{
"id": "1",
"createdAt": "2010-06-06T08:34:49.749Z",
"newsLetter": false,
"isPremium": false,
"name": "Tom",
"comments": [
{
"id": null,
"subtitle": "my second comment"
}
]
}
]
</code></pre>
<p>First, I flat (using <em>npm flat</em>) the API response data and my initialized expected <em>User array</em>. To my <em>User array</em> values I also hardcode the information whether the property is nullable or not like so:</p>
<p><em>data/UserDataManager.ts</em></p>
<pre><code>const flatResData = flat(resData);
const flatExpectedData = flat(initUserArr(resData.length));
const flatExpectedAllData = initAllUserArr(flatResData, flatExpectedData);
// console.log(flatResData)
// {
// 0.id: "0"
// 0.createdAt: "2020-06-06T08:34:49.749Z"
// 0.newsLetter: true
// 0.isPremium: false
// 0.name: "John"
// 0.comments.0.id: null
// 0.comments.0.subtitle: "my first comment"
// 1.id: "1"
// 1.createdAt: "2010-06-06T08:34:49.749Z"
// 1.newsLetter: false
// 1.isPremium: false
// 1.name: "Tom"
// 1.comments.0.id: null
// 1.comments.0.subtitle: "my second comment" }
// console.log(flatExpectedAllData)
// {
// 0.id: 1 <-- not nullable
// 0.age: 1 <-- not nullable
// 0.name: "1" <-- not nullable
// 0.createdAt: "0" <-- nullable
// 0.newsLetter: false <-- nullable
// 0.comments.0.id: 1 and so on...
// 0.comments.0.body: "1"
// 1.id: 1
// 1.age: 1
// 1.name: "1"
// 1.createdAt: "0"
// 1.newsLetter: false
// 1.comments.0.id: 1
// 1.comments.0.body: "1" }
</code></pre>
<p>Inside my <code>apiDiffCheckReport</code>, I'm handling each report's case separately. To get the <strong>1. Missing Properties</strong> and the <strong>2. Unexpected Properties</strong>, I first look for all the matching keys (<code>subKeys</code> for arrays i.e. <code>0.comments</code>) in both <code>resDataKeys</code> and <code>flatExpectedKeys</code>. After that I just simply filter out all the extra keys from the original array:</p>
<pre><code>const matchingKeys = flatExpectedKeys.map(key => {
let matchingKey = "";
if (flatResKeys.includes(key)) {
matchingKey = key;
}
const subKey = getSubKey(key);
if (flatResKeys.includes(subKey)) {
matchingKey = subKey;
}
return matchingKey;
});
// for 1. Missing Properties the `targetArr` is `flatExpectedKeys`. In other words, give me all the keys
// that were expected but were not found inside `flatResKeys`.
// for 2. Unexpected Properties the `targetArr` is `flatResKeys`. In other words, give me all the keys
// that arrived inside the API response but were not found inside `flatExpectedKeys`.
return targetArr.filter(key => !matchingKeys.includes(key));
</code></pre>
<p>Finally, In both cases, I simply remove the duplicates and make the keys more human-readable. As a result, I get something like this:</p>
<pre><code>// console.log(extractUnexpectedKeys(flatExpectedKeys, flatResKeys))
// ↓
return formatReportKeys(arrUnique(arrNoDigits(unexpectedKeys)));
// [".isPremium", ".comments[].subtitle"]
// console.log(extractMissingKeys(flatExpectedKeys, flatResKeys))
// ↓
return formatReportKeys(arrUnique(arrNoDigits(missingKeys)));
// [".age", ".comments[].body"]
</code></pre>
<p>To get the <strong>3. Type Mismatch</strong> report, I loop through the <code>expected keys</code>, check whether the key is also inside <code>response keys</code>, and then compare the two key-value types. I ignore the cases when the value is <em>null</em> and the property is nullable. That should not be a <em>Type Mismatch</em>, because I also expect <code>null</code> in that case:</p>
<pre><code>const mismatchedTypes: any = [];
Object.keys(flatExpectedData).forEach(key => {
if (Object.keys(flatResData).includes(key)) {
const item = {
key: key,
expectedType: typeof flatExpectedData[key],
foundType: typeof flatResData[key]
};
const isTypeMismatch = item.foundType !== item.expectedType;
const isNullable =
flatResData[key] === null &&
(flatExpectedData[key] === 0 ||
flatExpectedData[key] === "0" ||
flatExpectedData[key] === false); // <-- this is where I make use of the User array
// initialization, back in data/UserDataManager.ts, I'm
// using the value to find out whether the property is
// nullable or not
if (isTypeMismatch && !isNullable) {
mismatchedTypes.push(item);
}
}
});
</code></pre>
<p>And finally the <strong>4. Nullable Mismatch</strong>, I look for a mismatch through the values again:</p>
<pre><code>const isTypeMismatch =
typeof flatExpectedData[key] !== typeof flatResData[key];
const isNullableMismatch =
flatResData[key] === null &&
(flatExpectedData[key] !== 0 &&
flatExpectedData[key] !== "0" &&
flatExpectedData[key] !== false);
if (isTypeMismatch && isNullableMismatch) {
mismatchedNullables.push(key);
}
</code></pre>
<p>This is what the final report looks like:</p>
<pre><code>// 0: { case: 1, key: ".age" }
// 1: { case: 1, key: ".comments[].body" }
// 2: { case: 3, key: ".id", expectedType: "number", foundType: "string" }
// 3: { case: 3, key: ".comments[].id", expectedType: "number", foundType: "object" }
// 4: { case: 4, key: ".comments[].id" }
// 5: { case: 2, key: ".isPremium" }
// 6: { case: 2, key: ".comments[].subtitle" }
</code></pre>
<p>Before I jump into my TODOS, I would like some feedback on my current progress. Feel free to edit the code on sandbox, please ignore the <code>generateHtmlReport</code>, that's just a quick way to visualize the final report.</p>
<p><a href="https://codesandbox.io/s/long-brook-gvvnz" rel="nofollow noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit new" /></a></p>
<h2>TODOS</h2>
<ul>
<li>handle nullable arrays (I'm only to identify primitive nullable types via values, but I don't know how to handle arrays/objects)</li>
<li>more options inside <code>apiDiffCheckReport</code>, such as <code>isStrict</code> (allow warnings), <code>isFull</code> (all cases), etc.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T12:11:20.740",
"Id": "478589",
"Score": "0",
"body": "I feel like this is a lot of hardwork that should be fixed backend. Why not contact the people responsible and see if it can't be fixed. If that doesn't work, I would probably create a proxy server that automatically fills in the gaps and/or filter out incomplete data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T12:43:51.043",
"Id": "478591",
"Score": "0",
"body": "@kemicofaghost if we are talking real-world application I agree that this is a lot of extra code to have on the Front-end. But I want to integrate this into my E2E tests and CI/CD build so this report is generated alongside my code coverage report automatically. Also, we are developing a brand new larger-scale app so the data changes quite often at the moment and the people responsible will also have this report available, so in some cases, we can resolve these inconsistencies individually."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T19:12:12.037",
"Id": "243788",
"Score": "1",
"Tags": [
"javascript",
"typescript"
],
"Title": "TypeScript model and API response data diff checker report"
}
|
243788
|
<p>I wrote a makefile that would generate a simple executable from the example directory structure.</p>
<pre><code>project/
source/
include/
makefile
</code></pre>
<p>The makefile itself comes equipped with dependency tracking, and automatically generates two directories named <strong>build</strong> and <strong>dependency</strong>. Currently the makefile I made works, yet it takes anywhere from three to five seconds to build the executable on my machine. I was wondering whether my makefile source code was setup inefficiently, or am I just being impatient?</p>
<pre>target := driver.exe
compiler := g++
ccflags := -Wall -Werror -pedantic -pedantic-errors -O2 -std=c++17
src_dir := source
build_dir := build
deps_dir := dependency
ccfiles := $(wildcard $(src_dir)/*.cc)
objects := $(patsubst $(src_dir)/%.cc, $(build_dir)/%.o, $(ccfiles))
deps := $(patsubst $(build_dir)/%.o, $(deps_dir)/%.d, $(objects))
-include $(deps)
deps_flags = -MMD -MF $(@:$(build_dir)/%.o=$(deps_dir)/%.d)
$(target): $(objects)
@$(compiler) -o $@ $^
@echo "Successfully built "$@"!"
$(build_dir)/%.o: $(src_dir)/%.cc | setup
@$(compiler) $(cflags) -o $@ -c $< $(deps_flags)
@echo "Successfully built "$<" into "$@"!"
.PHONY: setup
setup:
@mkdir -p $(build_dir) $(deps_dir)
.PHONY: clean
clean:
rm -rf $(target) $(build_dir) $(deps_dir)
</pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T21:19:53.513",
"Id": "478539",
"Score": "0",
"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."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:05:00.893",
"Id": "478540",
"Score": "0",
"body": "There we go! Hopefully, the edits I made now narrow down what I would like advice on! I really hope that the makefile I created is inefficient. Otherwise, this makefile just proves how old my computer is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:29:15.253",
"Id": "478541",
"Score": "0",
"body": "@FooBar You have a phony `PHONY` target (change `.PHONEY` to `.PHONY`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:30:42.257",
"Id": "478542",
"Score": "0",
"body": "Whoops, let me fix fix that typo!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:41:53.650",
"Id": "478543",
"Score": "0",
"body": "@FooBar \"I was wondering whether my makefile source code was setup inefficiently\": I doubt that this is because of your Makefile. Of course, one way to test it would be to use `time g++ -Wall -Werror -pedantic -pedantic-errors -O2 -std=c++17 -c ...` (that is, compile the object files and link them without using Make's pattern subsitution). You should make sure to do these two steps (compile and link) separately to account for possibly writing the `.o` files to disk."
}
] |
[
{
"body": "<p>Instead of defining your own <code>compiler</code> variable, I would override the <a href=\"https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html\" rel=\"nofollow noreferrer\">implicit <code>CXX</code> variable</a>. This also goes for the implicit <code>CXXFLAGS</code> (instead of your <code>ccflags</code>).</p>\n<p>This allows other users to easily <a href=\"https://stackoverflow.com/questions/2969222/make-gnu-make-use-a-different-compiler\">change the compiler used</a> when using a different environment than you.</p>\n<p>You might also want to remove all the leading <code>@</code> in favour of <a href=\"https://stackoverflow.com/a/35451730\"><code>make -s</code></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T23:11:07.043",
"Id": "478546",
"Score": "0",
"body": "I see your point @FromTheStackAndBack. I also did the `time` test you suggested, and you were right! Turns out a I left a few applications running in the background. After shutting them down, my makefile builds my executable quickly. Now I don't know if this question was a waste, but I did learn some new things about `make`, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T23:20:11.647",
"Id": "478547",
"Score": "0",
"body": "@FooBar I would suggest [waiting a bit longer before accepting an answer](https://codereview.meta.stackexchange.com/questions/9457/how-long-should-you-leave-a-question-before-you-accept-an-answer). Other users may have more to add in addition to what I have written."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T23:30:50.520",
"Id": "478548",
"Score": "0",
"body": "Good advice @FromTheStackAndBack, but do I revoke the check mark? I would like to give you an up vote, yet the site tells me that I do not have enough reputation points to do so."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:36:01.893",
"Id": "243793",
"ParentId": "243790",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243793",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T19:55:47.583",
"Id": "243790",
"Score": "1",
"Tags": [
"c++",
"performance",
"makefile",
"make"
],
"Title": "Optimization of General Purpose Makefile"
}
|
243790
|
<p>I am working on a game in Unity/C#. I have a section of code that both feels like the best solution and code smell.</p>
<p>There are two objects. A player, and something interactable. The interactable object defines a method from an interface <code>IInteractable</code> with the signature <code>void Interact(GameObject interactor)</code>. The player can call this method on any <code>IInteractable</code> object.</p>
<p>The player object implements an <code>IHolder</code> interface, and the object in question that implements <code>IInteractable</code> is of type <code>Holdable</code>.</p>
<p>When the player calls <code>Interact()</code> on the <code>Holdable</code>, the <code>Holdable</code> checks if the caller implements <code>IHolder</code> by using a generic method call. If it succeeds then it makes the holder call a more specific method on it's own instance.</p>
<pre><code>public void Interact(GameObject interactor)
{
if (interactor.TryGetComponent<IHolder>(out this.holder))
{
this.holder.Hold(this);
}
}
</code></pre>
<p>It doesn't feel right to me that the object to be held is commanding the holder to hold it.</p>
<p>Would a more appropriate solution be to have <code>Interact()</code> return an <code>Action<GameObject></code> that the player can decide to <code>.Invoke()</code>? Not sure if having the caller call the callee's suggestion to call the caller's method with the callee as an argument is actually better and not just hiding the issue with complexity.</p>
<p>Edit:</p>
<p>Using this refactor as the solution:</p>
<pre><code>public Action GetInteraction(GameObject interactor)
{
IHolder potentialHolder;
if (interactor.TryGetComponent<IHolder>(out potentialHolder))
{
return () => potentialHolder.Hold(this);
}
return null;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-12T22:31:53.680",
"Id": "243792",
"Score": "1",
"Tags": [
"c#",
"unity3d"
],
"Title": "Callee specifying more spectific behaviour of the caller"
}
|
243792
|
<p>I'm learning c++ and I know some algorithms and data structures. I was wondering what is the best way to do merge sort for a vector in c++.</p>
<pre><code>// will write a program for merge sort
/* steps:
* have an array of size n call it A
* divide A into left and right halves L and R
* call merge sort on the two halves now L' and R'
* now merge the two halves into B (the sorted version of A)
*/
/* the merging algorithm:
* the merging algorithm is a "two finger algo"
* where an element of L' is compared with each elt of R' until the elt in R' is less
* we then take this element and put it into our sorted array, B
*/
#include <iostream>
#include <vector> // will use the vector class to make things like list slicing very easy
using namespace std;
void merge_sort(vector<int> &arr);
void merge(vector<int >&left, vector<int> &right, vector<int> &results);
int main() {
vector<int> my_vector{10, 30, 50, 40};
merge_sort(my_vector);
for (int i: my_vector)
cout << i << ',';
return 0;
}
void merge_sort(vector<int> & arr) {
if (arr.size() <= 1) return;
int mid = arr.size() / 2;
vector<int> left(arr.begin(), arr.end() - mid);
vector<int> right(arr.begin() + mid, arr.end());
merge_sort(left);
merge_sort(right);
merge(left, right, arr);
}
void merge(vector<int> &left, vector<int> &right, vector<int> &results)
{
int L_size = left.size();
int R_size = right.size();
int i = 0, j = 0, k = 0;
// two finger algorithm
while (j < L_size && k < R_size)
{
if (left[j] < right[k]) {
results[i] = left[j];
j++;
}
else {
results[i] = right[k];
k++;
}
i++;
}
while (j < L_size) {
results[i] = left[j];
j++; i++;
}
while (k < R_size) {
results[i] = right[k];
k++; i++;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T02:16:37.590",
"Id": "478550",
"Score": "0",
"body": "`merge_sort` does not properly split the array (if the size is odd). If the length is 3, `left` will have elements 0 and 1, while `right` will have elements 1 and 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T05:55:20.823",
"Id": "478563",
"Score": "0",
"body": "I like the very first line of code; I'd just edit \"the will do\" once done."
}
] |
[
{
"body": "<h2>Overall</h2>\n<p>Looks good overall.</p>\n<p>The design works perfectly for sorting integers. But in C++ we can potentially sort anything. So why not allow your sorting algorithm to work with any sortable type.</p>\n<p>To do this learn templates:</p>\n<pre><code> void merge_sort(vector<int> &arr);\n\n // Change to:\n\n template<typename T>\n void merge_sort(vector<T>& arr);\n</code></pre>\n<p>The next thing to think about is that <code>vector<></code> is not the only thing that can be sorted. There are lots of container types that can be sorted. Normally we don't care about the container type and we abstract the container away and specific what what we want to sort in terms of iterators.</p>\n<p>So the next subject to learn are iterarators'. Then you can specify what you want to sort in terms of the beginning and end of a range.</p>\n<pre><code>template<typename I>\nvoid merge_sort(I begin, I end);\n</code></pre>\n<p>The next thing you should think about is the memory requirements your algorithm uses. Currently your algorithm uses 2 times the current size of the array you want to sort (in addition the vector). You can change this so you only use 1 times the current size of the vector.</p>\n<p>To achieve this you want to allocate the memory once outside the recursive sort function then pass in this temporary memory into the merge sort.</p>\n<pre><code>// The wrapper\ntemplate<typename I>\nvoid merge_sort(I begin, I end)\n\n // Create a single buffer are to be be re-used.\n std::vector<int> tmpData(std::distance(begin, end));\n\n merge_sort_with_buffer(begin, end, std::begin(tmpData) std::end(tmpData));\n}\n\ntemplate<typename I1, template I2>\nvoid merge_sort_with_buffer(I1 b , I1 e, I2 tb, I2 te)\n{\n std::size_t s = std::distance(begin, end);\n\n if (s < 2) {\n return;\n }\n\n I1 m = std::next(begin, s/2);\n I2 tm = std::next(tBegin, s/2);\n\n merge_sort_with_buffer(b, m, tb, tm);\n merge_sort_with_buffer(m, e, tm, te);\n merge(tb, tm, te, b);\n}\n\ntemplate<typename I2, template I1>\nvoid merge(I2 tb, I2 tm, I2 te, I1 dst)\n{\n // copy tb->tm\n // copy tm->te\n //\n // To the destination\n}\n</code></pre>\n<h2>Code Review</h2>\n<p>Not a fan of bad comments:</p>\n<pre><code>#include <vector> // will use the vector class to make things like list slicing very easy\n</code></pre>\n<p>Do you use slicing?</p>\n<hr />\n<p>Stop doing this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>It might be useful in books where space is limited. But in real code it actually causes problems. I recomend you stop using it because it becomes a habit. This is a bad one. When you have a bad habit you will just use it without thinking and accidentally cause on f the problems.</p>\n<p>See: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a> Personally I find the second answer the <a href=\"https://stackoverflow.com/a/1453605/14065\">best</a>.</p>\n<hr />\n<p>In C++ it is more normal to put the <code>&</code> with the type in the declaration.</p>\n<pre><code>void merge_sort(vector<int> &arr);\n\n// Like this:\n\nvoid merge_sort(vector<int>& arr);\n</code></pre>\n<p>Note: This is the opposite of what is common in C.</p>\n<hr />\n<p>Please always add the curly craces '{}'</p>\n<pre><code> for (int i: my_vector)\n cout << i << ',';\n\n // Like this:\n\n for (int i: my_vector) {\n cout << i << ',';\n }\n</code></pre>\n<p>The trouble is people still make silly macros that are multiple lines. Not using the braces can put you in funny situations where only part of your code is executed by the loop when you least expect it.</p>\n<p>More importantly to me it makes it much simpler to read.</p>\n<hr />\n<p>In C++ the last return in <code>main()</code> is not needed.</p>\n<pre><code> return 0;\n</code></pre>\n<p>If you don't provide one the compiler automatically adds a <code>return 0</code> at the end of main.</p>\n<p>It has been common practice to not include a <code>return 0</code> if main does not ever return anything else. So if I see a <code>return 0</code> at the end I start looking for other error detection code that would return another value.</p>\n<hr />\n<p>This is a subtle one:</p>\n<pre><code> if (left[j] < right[k]) {\n</code></pre>\n<p>If you use the less here then if they are equal you will choose the one from the right. Keep that in mind.</p>\n<p>There is an important mathematical principle around sorting called "Stability" (when sorting). If items that are equal retain there original relative order the sort is considered stable otherwise it is not.</p>\n<p>If you choose from the right when the items are equal your algorithm is not stable. So by using <code><=</code> you automatically make your algorithm stable.</p>\n<pre><code> if (left[j] <= right[k]) {\n</code></pre>\n<hr />\n<p>Note this is a copy operation:</p>\n<pre><code> results[i] = left[j];\n</code></pre>\n<p>Now for integers this makes absolutely no different. But when you make this work for other types this mean copying an object. This can be expensive so we would prefer to use move rather than copy.</p>\n<pre><code> results[i] = std::move(left[j]);\n</code></pre>\n<hr />\n<p>Sure these work.</p>\n<pre><code> while (j < L_size) {\n results[i] = left[j];\n j++; i++;\n }\n while (k < R_size) {\n results[i] = right[k];\n k++; i++;\n }\n</code></pre>\n<p>But much easier to use standard algorithms</p>\n<pre><code> std::copy(&left[j], &left[L_size], &result[i]);\n std::copy(&right[k], &right[R_size], &result[i]);\n</code></pre>\n<p>But then we remember that we want to use move rather than copy.</p>\n<pre><code> std::move(&left[j], &left[L_size], &result[i]);\n std::move(&right[k], &right[R_size], &result[i]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T22:05:00.350",
"Id": "243834",
"ParentId": "243797",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243834",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T01:28:00.883",
"Id": "243797",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"mergesort"
],
"Title": "Merge Sort using vector c++"
}
|
243797
|
<p>I have subclassed tkinter treeview object added many features like cut,paste etc and context menus to insert rows, delete etc. Would like some feedback on how well it works and if it's intuitive or not.</p>
<p>Current version is @: <a href="https://github.com/unodan/TkInter-Treeview-Example-Demo" rel="nofollow noreferrer">https://github.com/unodan/TkInter-Treeview-Example-Demo</a></p>
<pre><code>import json
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkfont
from os import path, makedirs
from sys import platform
from datetime import datetime
ABS_PATH = path.dirname(path.realpath(__file__))
_IID = 0
_TYPE = 1
_OPEN = 2
_TAGS = 3
_SIZE = 4
_MODIFIED = 5
_DATA1 = 6
_SKIP = 0
_CANCEL = 1
class App(tk.Tk):
def __init__(self):
super().__init__()
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.frame = ttk.Frame(self)
self.frame.rowconfigure(0, weight=1)
self.frame.columnconfigure(0, weight=1)
self.frame.grid(sticky=tk.NSEW)
self.app_data = {}
self.style = ttk.Style()
self.style.theme_use('clam')
self.title('Treeview Demo')
self.protocol('WM_DELETE_WINDOW', self.exit)
self.platform = platform
if platform == "linux" or platform == "linux2":
self.platform = 'linux'
self.setup()
def setup(self):
def setup_app():
file = path.join(ABS_PATH, 'app.json')
if path.exists(file):
with open(file) as f:
self.app_data = json.load(f)
else:
self.app_data = {
'geometry': '500x700',
}
def setup_treeview():
tv_line_padding = 8
tv_heading_padding = 5
tv_heading_border_width = 2
font = tkfont.nametofont('TkDefaultFont')
self.linespace = font.metrics('linespace')
row_height = self.linespace + tv_line_padding
tv_indent = row_height
self.style.configure('Treeview', rowheight=row_height)
self.style.configure('Treeview.Heading', padding=tv_heading_padding, borderwidth=tv_heading_border_width)
self.style.configure('Treeview', indent=tv_indent)
self.style.configure('TEntry', selectbackground='#0081c1')
self.style.map('Treeview', background=[('selected', '#0081c1')])
self.style.configure('TCombobox', selectbackground='#0081c1')
self.style.map(
'TCombobox',
foreground=[('readonly', 'white')],
fieldbackground=[('readonly', '#0081c1')],
)
self.option_add("*TCombobox*Listbox*Background", 'white')
self.option_add("*TCombobox*Listbox*Foreground", '#000000')
file = path.join(ABS_PATH, 'treeview.json')
if path.exists(file):
with open(file) as f:
setup = json.load(f)
else:
now = datetime.now()
dt_string = now.strftime("%Y/%m/%d %H:%M:%S")
setup = {
'headings': (
{'text': 'Name', 'anchor': tk.W},
{'text': 'IID', 'anchor': tk.W},
{'text': 'Item', 'anchor': tk.W},
{'text': 'Open', 'anchor': tk.W},
{'text': 'Tags', 'anchor': tk.W},
{'text': 'Size', 'anchor': tk.W},
{'text': 'Last Modified', 'anchor': tk.W},
{'text': 'Data', 'anchor': tk.W},
),
'columns': (
{'width': 180, 'minwidth': 3, 'stretch': tk.NO, 'type': 'Entry', 'unique': True},
{'width': 70, 'minwidth': 3, 'stretch': tk.NO},
{'width': 70, 'minwidth': 3, 'stretch': tk.NO},
{'width': 70, 'minwidth': 3, 'stretch': tk.NO},
{'width': 120, 'minwidth': 3, 'stretch': tk.NO},
{'width': 80, 'minwidth': 3, 'stretch': tk.NO},
{'width': 130, 'minwidth': 3, 'stretch': tk.NO},
{'width': 180, 'minwidth': 3, 'stretch': tk.YES, 'type': 'Combobox',
'values': ('Value 1', 'Value 2', 'Value 3', 'Value 4', 'Value 5'),
},
),
'data': (
{'text': 'Folder 0', 'open': 1, 'values': ('', 'Node', True, '', '', dt_string, ''),
'children': (
{'text': 'photo1.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'photo2.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'photo3.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'Folder 0_1', 'open': 1, 'values': ('', 'Node', True, '', '', dt_string, ''),
'children': (
{'text': 'photo1.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'photo2.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'photo3.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
)},
)},
{'text': 'Folder 1', 'open': 1, 'values': ('', 'Node', True, '', '', dt_string, ''),
'children': (
{'text': 'photo4.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'photo5.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
{'text': 'photo6.png', 'values': ('', 'Leaf', '', '', '0 Kb', dt_string, '')},
)},
),
}
tree = self.treeview = Treeview(self.frame, setup=setup)
tree.focus_set()
settings = dict(setup.get('settings', ()))
item = settings.get('focus', None)
if (not item or not tree.exists(item)) and tree.get_children():
item = tree.get_children()[0]
view = settings.get('view', None)
if view:
self.treeview.xview('moveto', view[0])
self.treeview.yview('moveto', view[1])
tree.focus(item)
tree.selection_add(item)
tree.grid(sticky=tk.NSEW, row=0, column=0)
setup_app()
setup_treeview()
self.geometry(self.app_data['geometry'])
def exit(self):
self.app_data.update({'geometry': self.geometry()})
self.save()
self.destroy()
def save(self):
file = path.join(ABS_PATH, 'app.json')
if file:
dirname = path.dirname(file)
if not path.exists(dirname):
makedirs(dirname)
with open(file, 'w') as f:
json.dump(self.app_data, f, indent=3)
file = path.join(ABS_PATH, 'treeview.json')
if file:
dirname = path.dirname(file)
if not path.exists(dirname):
makedirs(dirname)
with open(file, 'w') as f:
data = self.treeview.serialize()
data['settings'] = tuple({
'view': (self.treeview.xview()[0], self.treeview.yview()[0]),
'focus': self.treeview.focus()
}.items())
for idx, c in enumerate(self.treeview.columns):
c['width'] = self.treeview.column(f'#{idx}', 'width')
json.dump(data, f, indent=3)
class Event:
def __init__(self):
super().__init__()
self.x, self.y = None, None
class DialogBase(tk.Toplevel):
def __init__(self, parent, **kwargs):
width = kwargs.pop('width', None)
height = kwargs.pop('height', None)
title = kwargs.pop('title', '')
resizable = kwargs.pop('resizable', (True, True))
super().__init__(parent, **kwargs)
self.resizable(*resizable)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.results = None
self.container = ttk.Frame(self)
self.container.grid(sticky=tk.NSEW)
self.options = kwargs
geometry = self.geometry().split('+', 1)
_width, _height = geometry[0].split('x')
if width:
_width = width
if height:
_height = height
self.title(title)
self.geometry(f'{_width}x{_height}+{geometry[1]}')
class RenameDialog(DialogBase):
def __init__(self, parent, **kwargs):
message = kwargs.pop('message', 'No Message!')
super().__init__(parent, **kwargs)
self.container.rowconfigure(1, weight=1)
self.container.columnconfigure(0, weight=1)
frame = self.row0 = ttk.Frame(self.container)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
self.label = ttk.Label(frame, text=message)
self.label.grid(sticky=tk.N+tk.EW, pady=(0, 10), row=0, column=0)
self.entry = Entry(frame, width=30)
self.entry.config(textvariable=self.entry.var)
self.entry.grid(sticky=tk.NSEW, row=1, column=0, padx=(5, 0))
frame.grid(row=0, sticky=tk.EW, padx=10, pady=(20, 0))
frame = self.row1 = ttk.Frame(self.container)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
self.button_rename = ttk.Button(frame, text="Rename", width=8)
self.button_rename.grid(sticky=tk.NS + tk.E, row=0, column=0, padx=(5, 0))
self.button_skip = ttk.Button(frame, text="Skip", width=8)
self.button_skip.grid(sticky=tk.NS + tk.E, row=0, column=1, padx=(5, 0))
self.button_cancel = ttk.Button(frame, text="Cancel", width=8)
self.button_cancel.grid(sticky=tk.NS+tk.E, row=0, column=2, padx=(5, 0))
frame.grid(row=1, sticky=tk.EW+tk.S, padx=10, pady=(10, 20))
class MessageDialog(DialogBase):
def __init__(self, parent, **kwargs):
message = kwargs.pop('message', '')
super().__init__(parent, **kwargs)
frame = self.row0 = ttk.Frame(self.container)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
self.label = ttk.Label(frame, text=message)
self.label.grid(sticky=tk.NSEW, pady=5, row=0, column=0)
frame.grid(sticky=tk.EW, padx=10, pady=(20, 0))
frame = self.row1 = ttk.Frame(self.container)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
self.button_ok = ttk.Button(frame, text="Okay")
self.button_ok.grid(sticky=tk.NS + tk.E, row=0, column=0, padx=(5, 0))
frame.grid(row=1, sticky=tk.EW, padx=10, pady=(10, 20))
class Text(tk.Text):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.origin_x = self.origin_y = 0
class Frame(ttk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.scroll_x = \
self.scroll_y = None
class Entry(ttk.Entry):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.var = tk.StringVar()
self.configure(textvariable=self.var)
self.undo_data = {}
self.popup = \
self.menu_background = None
self.style = ttk.Style()
self.setup()
self.bindings_set()
def setup(self):
def set_popup_menu():
opts = dict(self.style.map('Treeview', 'background'))
background = self.style.lookup('Treeview.Heading', 'background')
popup = self.popup = tk.Menu(
self.winfo_toplevel(),
tearoff=0,
background=background,
foreground='#000000',
activebackground=opts['selected']
)
popup.add_command(label="Select All", command=self.select_all)
popup.add_separator()
popup.add_command(label="Cut", command=lambda: self.event_generate('<Control-x>'))
popup.add_command(label="Copy", command=lambda: self.event_generate('<Control-c>'))
popup.add_command(label="Paste", command=lambda: self.event_generate('<Control-v>'))
popup.add_separator()
popup.add_command(label="Delete", command=self.clear)
self.menu_background = self.style.lookup('TScrollbar.thumb', 'background')
set_popup_menu()
def clear(self):
self.delete(0, tk.END)
def select_all(self):
self.select_range(0, tk.END)
self.icursor(tk.END)
def popup_menu(self, event):
if not self.popup:
return
wdg = event.widget
wdg.focus_set()
self.popup.tk_popup(event.x_root, event.y_root)
def bindings_set(self):
bindings = {
'<ButtonPress-3>': self.popup_menu,
}
for command, callback in bindings.items():
self.bind(command, callback)
class Combobox(ttk.Combobox):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.var = tk.StringVar()
self.configure(textvariable=self.var)
self.popup = \
self.menu_background = None
self.style = ttk.Style()
self.setup()
self.bindings_set()
def setup(self):
def set_popup_menu():
opts = dict(self.style.map('Treeview', 'background'))
background = self.style.lookup('Treeview.Heading', 'background')
popup = self.popup = tk.Menu(
self.winfo_toplevel(),
tearoff=0,
background=background,
foreground='#000000',
activebackground=opts['selected']
)
popup.add_command(label="Select All", command=self.select_all)
popup.add_separator()
popup.add_command(label="Cut", command=lambda: self.event_generate('<Control-x>'))
popup.add_command(label="Copy", command=lambda: self.event_generate('<Control-c>'))
popup.add_command(label="Paste", command=lambda: self.event_generate('<Control-v>'))
popup.add_separator()
popup.add_command(label="Delete", command=self.clear)
self.menu_background = self.style.lookup('TScrollbar.thumb', 'background')
set_popup_menu()
def select_all(self):
self.select_range(0, tk.END)
self.icursor(tk.END)
def clear(self):
self.var.set('')
def popup_menu(self, event):
if not self.popup:
return
wdg = event.widget
wdg.focus_set()
self.popup.tk_popup(event.x_root, event.y_root)
def bindings_set(self):
bindings = {
'<ButtonPress-3>': self.popup_menu,
}
for command, callback in bindings.items():
self.bind(command, callback)
class Label(ttk.Label):
def __init__(self, parent, **kwargs):
self.var = tk.StringVar()
super().__init__(parent, textvariable=self.var, **kwargs)
self.var.set(kwargs.get('text', ''))
class Listbox(tk.Listbox):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.var = tk.StringVar()
self.config(listvariable=self.var)
def set_row_colors(self, odd, even):
for i in range(0, len(self.get(0, tk.END))):
color = odd if i % 2 else even
self.itemconfig(i, {'bg': color})
class Scrollbar(ttk.Scrollbar):
def __init__(self, parent, **kwargs):
self.callback = kwargs.pop('callback', None)
super().__init__(parent, **kwargs)
def set(self, low, high):
if float(low) > 0 or float(high) < 1:
ttk.Scrollbar.set(self, low, high)
self.grid()
else:
self.grid_remove()
if self.callback:
self.callback(self)
class Treeview(ttk.Treeview):
def __init__(self, parent, **kwargs):
self.frame = Frame(parent)
self.frame.rowconfigure(0, weight=1)
self.frame.columnconfigure(0, weight=1)
setup = kwargs.pop('setup', {})
data = setup.pop('data', [])
self.columns = setup['columns']
self.headings = setup['headings']
self.scroll = kwargs.pop('scroll', (True, True))
super().__init__(self.frame, **kwargs)
self.detached = []
self.undo_data = {}
self.sorted_columns = {}
self.shift = \
self.popup = \
self.scroll_x = \
self.scroll_y = \
self.selected = \
self.dlg_results = \
self.active_popup_widget = \
self.active_popup_column = \
self.cursor_offset = \
self.menu_background = None
self.style = ttk.Style()
self.indent = self.style.lookup('Treeview', 'indent')
self.rowheight = self.style.lookup('Treeview', 'rowheight')
if setup:
self.setup(setup)
if data:
self.populate('', data)
self.bindings_set()
self.frame.grid(sticky=tk.NSEW)
def setup(self, data):
def set_style():
background = self.style.lookup("TFrame", "background")
self.tag_configure('odd', background=background)
self.tag_configure('even', background='#ffffff')
self.troughcolor = self.style.lookup('TScrollbar.trough', 'troughcolor')
self.menu_background = self.style.lookup('TScrollbar.Heading', 'background')
self.style.configure(".", indicatorsize=self.rowheight / 2 + 1)
def set_popup_menu():
opts = dict(self.style.map('Treeview', 'background'))
background = self.style.lookup('Treeview.Heading', 'background')
popup = self.popup = tk.Menu(
self.winfo_toplevel(),
tearoff=0,
background=background,
foreground='#000000',
activebackground=opts['selected']
)
create_new = tk.Menu(
popup,
tearoff=0,
background=background,
foreground='#000000',
activebackground=opts['selected']
)
popup.add_cascade(label="Insert", menu=create_new)
popup.add_separator()
popup.add_command(label="Cut", command=self.cut)
popup.add_command(label="Copy", command=self.copy)
popup.add_command(label="Paste", command=self.paste)
popup.add_separator()
popup.add_command(label="Delete", command=self.detach)
create_new.add_command(label="Item", command=self.insert_leaf)
create_new.add_separator()
create_new.add_command(label="Folder", command=self.insert_node)
def set_scrollbars():
scroll_x, scroll_y = self.scroll
if scroll_x:
sb_x = self.scroll_x = Scrollbar(self.frame, callback=popup_widget_destroy)
sb_x.configure(command=self.xview, orient=tk.HORIZONTAL)
sb_x.grid(sticky=tk.NSEW, row=980, column=0)
self.configure(xscrollcommand=sb_x.set)
if scroll_y:
sb_y = self.scroll_y = Scrollbar(self.frame, callback=popup_widget_destroy)
sb_y.configure(command=self.yview)
self.configure(yscrollcommand=sb_y.set)
sb_y.grid(sticky=tk.NSEW, row=0, column=990)
def set_rows_columns():
ids = []
columns = len(data['columns'])
for column in range(1, columns):
ids.append(f'#{column}')
self["columns"] = ids
for idx, cfg in enumerate(data['headings']):
_id = cfg['column'] if 'column' in cfg else f'#{idx}'
self.heading(_id, text=cfg['text'], anchor=cfg['anchor'])
self.sorted_columns[f'#{idx}'] = True
for idx, cfg in enumerate(data['columns']):
_id = cfg['column'] if 'column' in cfg else f'#{idx}'
self.column(_id, width=cfg['width'], minwidth=cfg['minwidth'], stretch=cfg['stretch'])
def popup_widget_destroy(_):
if self.active_popup_widget:
self.active_popup_widget.destroy()
self.active_popup_widget = None
set_style()
set_popup_menu()
set_scrollbars()
set_rows_columns()
self.after(1, self.tags_reset)
def next(self, item):
if self.item(item, 'open') and self.get_children(item):
_next = self.get_children(item)[0]
return _next
_next = super(Treeview, self).next(item)
if not _next and self.next(self.parent(item)):
_next = self.next(self.parent(item))
return _next
def prev(self, item):
_prev = super(Treeview, self).prev(item)
if not _prev:
parent = self.parent(item)
_prev = parent if parent else ''
return _prev
def tag_add(self, tags, item):
self.tags_update('add', tags, item)
def tag_remove(self, tags, item=None):
self.tags_update('remove', tags, item)
def tags_reset(self, excluded=None):
def reset(_item):
tags = list(self.item(_item, 'tags'))
for _tag in tags.copy():
if _tag not in exclude:
tags.pop(tags.index(_tag))
self.item(_item, tags=tags)
for node in self.get_children(_item):
reset(node)
def set_tag(_item, _tag):
_tag = 'even' if _tag == 'odd' else 'odd'
self.tag_add(_tag, _item)
self.value_set(_TAGS, str(self.item(_item, 'tags')), _item)
if int(self.item(_item, 'open')):
for node in self.get_children(_item):
_tag = set_tag(node, _tag)
return _tag
exclude = []
if excluded and not isinstance(excluded, tk.Event):
if isinstance(excluded, str):
excluded = (excluded,)
for item in excluded:
if item in excluded:
exclude.append(item)
tag = 'odd'
for item in self.get_children():
reset(item)
tag = set_tag(item, tag)
self.value_set(_TAGS, str(self.item(item, 'tags')), item)
def tag_replace(self, old, new, item=None):
for item in (item,) if item else self.tag_has(old):
if self.tag_has(old, item):
self.tags_update('add', new, item)
self.tags_update('remove', old, item)
def tags_update(self, opt, tags, item):
def get_items(node):
items.append(node)
for node in self.get_children(node):
get_items(node)
if not tags:
return
elif isinstance(tags, str):
tags = (tags,)
if not item:
items = []
for child in self.get_children():
get_items(child)
else:
items = (item,)
for item in items:
_tags = list(self.item(item, 'tags'))
for _tag in tags:
if opt == 'add':
if _tag not in _tags:
_tags.append(_tag)
elif opt == 'remove':
if _tag in _tags:
_tags.pop(_tags.index(_tag))
self.item(item, tags=_tags)
def value_get(self, idx, item):
if not item:
return ''
values = list(self.item(item, 'values'))
if 0 <= idx <= len(values):
return values[idx]
def value_set(self, idx, value, item):
values = list(self.item(item, 'values'))
if idx < len(values):
values[idx] = value
self.item(item, values=values)
def dlg_rename(self, title, message, current_name):
def skip(_=None):
self.dlg_results = _SKIP
dlg.destroy()
def cancel(_=None):
self.dlg_results = _CANCEL
dlg.destroy()
def rename(_=None):
self.dlg_results = dlg.entry.var.get()
dlg.destroy()
root = self.winfo_toplevel()
dlg = RenameDialog(root, width=320, height=150, title=title, message=message)
dlg.update_idletasks()
dlg.label.config(wraplength=dlg.container.winfo_width())
dlg.button_rename.focus()
dlg.entry.var.set(current_name)
dlg.entry.select_range(0, tk.END)
dlg.entry.icursor(tk.END)
dlg.entry.focus_set()
dlg.bind('<Return>', rename)
dlg.bind('<KP_Enter>', rename)
dlg.button_rename.bind('<Button-1>', rename)
dlg.button_rename.bind('<Return>', rename)
dlg.button_rename.bind('<KP_Enter>', rename)
dlg.button_skip.bind('<Button-1>', skip)
dlg.button_skip.bind('<Return>', skip)
dlg.button_skip.bind('<KP_Enter>', skip)
dlg.button_cancel.bind('<Button-1>', cancel)
dlg.button_cancel.bind('<Return>', cancel)
dlg.button_cancel.bind('<KP_Enter>', cancel)
if self.active_popup_widget:
x = self.active_popup_widget.winfo_rootx()
y = self.active_popup_widget.winfo_rooty()
else:
bbox = self.bbox(self.focus())
x, y, _, _ = bbox
x += root.winfo_rootx()
y += root.winfo_rooty()
widest = 0
font = tkfont.nametofont('TkDefaultFont')
for node in self.get_children(self.focus()):
size = font.measure(self.item(node, 'text'))
if size > widest:
widest = size + font.measure('W')
x += (widest + font.measure('W') + self.indent * self.item_depth(self.focus()))
y += self.rowheight + self.rowheight // 2
dlg.geometry(f'{dlg.geometry().split("+", 1)[0]}+{x}+{y}')
root.wait_window(dlg)
return self.dlg_results
def dlg_message(self, title, message):
def ok(_=None):
dlg.destroy()
root = self.winfo_toplevel()
dlg = MessageDialog(root, width=320, height=130, title=title, message=message)
dlg.update_idletasks()
dlg.label.config(wraplength=dlg.container.winfo_width())
dlg.button_ok.focus()
dlg.button_ok.config(command=ok)
dlg.button_ok.bind('<Return>', ok)
dlg.button_ok.bind('<KP_Enter>', ok)
if self.active_popup_widget:
x = self.active_popup_widget.winfo_rootx()
y = self.active_popup_widget.winfo_rooty()
else:
bbox = self.bbox(self.focus())
x, y, _, _ = bbox
x += root.winfo_rootx()
y += root.winfo_rooty()
item = self.identify('item', x, y-self.winfo_rooty())
widest = 0
font = tkfont.nametofont('TkDefaultFont')
for node in self.get_children(self.parent(item)):
size = font.measure(self.item(node, 'text'))
if size > widest:
widest = size + font.measure('W')
x += widest
y += self.rowheight + self.rowheight // 2
dlg.geometry(f'{dlg.geometry().split("+", 1)[0]}+{x}+{y}')
root.wait_window(dlg)
def cut(self, _=None):
def set_selections(_item):
self.tag_add('selected', _item)
for _item in self.get_children(_item):
set_selections(_item)
selections = list(self.selection())
for item in reversed(selections):
if self.parent(item) in selections:
selections.pop(selections.index(item))
else:
set_selections(item)
item = self.focus()
item = self.prev(item)
if not item and self.get_children():
item = self.get_children()[0]
self.undo_data = {}
for node in selections:
self.undo_data[node] = (self.parent(node), self.index(node))
self.detach(*selections)
self.detached = selections
self.focus(item)
self.selection_add(item)
self.tags_reset(excluded='selected')
def copy(self, _=None):
def set_selected(_item):
self.selected.append(_item)
self.tag_add('selected', _item)
self.value_set(_TAGS, str(self.item(_item, 'tags')), _item)
if not self.item(_item, 'open'):
for node in self.get_children(_item):
set_selected(node)
if not self.shift:
for item in self.tag_has('selected'):
self.tag_remove('selected', item)
self.value_set(_TAGS, str(self.item(item, 'tags')), item)
self.selected = []
for item in self.selection():
set_selected(item)
def undo(self, _=None):
for item, (parent, idx) in self.undo_data.items():
self.reattach(item, parent, idx)
self.selection_remove(item)
self.tags_reset()
def paste(self, _=None):
selections = self.detached if self.detached else self.selected
if not self.selected and not self.detached:
selections = self.tag_has('selected')
for dst_item in self.selection():
if not len(selections) or self.value_get(_TYPE, dst_item) != 'Node':
continue
if self.detached:
for item in selections:
self.reattach(item, dst_item, tk.END)
self.detached = False
else:
selected = {}
for item in selections:
parent = self.parent(item)
dst = selected[parent] if parent in selected else dst_item
self.value_set(_MODIFIED, datetime.now().strftime("%Y/%m/%d %H:%M:%S"), item)
iid = self.insert(dst, **self.item(item))
if iid:
self.value_set(_IID, iid, iid)
self.tag_remove('selected', iid)
selected[item] = iid
self.tags_reset(excluded='selected')
self.selection_remove(self.tag_has('selected'))
self.selection_set(self.focus())
def delete(self, *items):
for item in items:
parent = self.parent(item)
if parent:
value = int(self.value_get(_SIZE, parent).split(' ')[0])-1
word = 'item' if value == 1 else 'items'
self.value_set(_SIZE, f'{value} {word}', parent)
super(Treeview, self).delete(*items)
def insert(self, parent, index=tk.END, **kwargs):
kwargs.pop('children', None)
unique_columns = []
for idx, c in enumerate(self.columns):
if 'unique' in c and c['unique']:
unique_columns.append(idx)
for column in unique_columns:
if column:
pass
else:
text = kwargs['text']
children = self.get_children(parent)
column_values = []
for node in children:
column_values.append(self.item(node, 'text'))
for node in children:
while text == self.item(node, 'text'):
result = self.dlg_rename(
'Rename',
f'The name "{text}" already exists, please choose another '
f'name and try again.',
text,
)
if result in (_SKIP, _CANCEL):
return
text = result
kwargs['text'] = text
iid = super(Treeview, self).insert(parent, index, **kwargs)
child_count = len(self.get_children(parent))
if child_count:
word = 'item' if child_count == 1 else 'items'
self.value_set(_SIZE, f'{len(self.get_children(parent))} {word}', parent)
self.see(iid)
return iid
def escape(self, _):
self.tags_reset()
self.selection_remove(*self.selection())
self.selection_set(self.focus())
def control_a(self, _):
def select(_child):
self.selection_add(_child)
for node in self.get_children(_child):
select(node)
for child in self.get_children():
select(child)
def shift_up(self, _):
rowheight = self.style.lookup('Treeview', 'rowheight')
focus = self.focus()
x, y, _, _ = self.bbox(focus)
x += self.winfo_rootx()
_prev = self.identify('item', x, y-rowheight+1)
if _prev:
self.see(_prev)
self.focus(_prev)
self.cursor_offset += 1
if self.cursor_offset > 0:
self.selection_toggle(_prev)
else:
self.selection_toggle(focus)
return 'break'
def shift_down(self, _):
rowheight = self.style.lookup('Treeview', 'rowheight')
focus = self.focus()
x, y, _, _ = self.bbox(focus)
x += self.winfo_rootx()
_next = self.identify('item', x, y+rowheight+1)
if _next:
self.see(_next)
self.focus(_next)
self.cursor_offset -= 1
if self.cursor_offset >= 0:
self.selection_toggle(focus)
else:
self.selection_toggle(_next)
return 'break'
def key_press(self, event):
if 'Shift' in event.keysym:
self.shift = True
self.cursor_offset = 0
def key_release(self, event):
if 'Shift' in event.keysym:
self.shift = False
def expand_tree(self, _):
def func():
item = self.identify('item', self.winfo_pointerx(), self.winfo_pointery()-self.winfo_rooty())
self.value_set(_OPEN, True, item)
self.tags_reset(excluded='selected')
self.after(1, func)
def collapse_tree(self, _=None):
def func():
item = self.identify('item', self.winfo_pointerx(), self.winfo_pointery()-self.winfo_rooty())
self.value_set(_OPEN, False, item)
self.tags_reset(excluded='selected')
self.after(1, func)
def column_expand(self, event):
def walk(_children):
_largest = 0
idx = int(column.lstrip('#'))-1
for child in _children:
if column == '#0':
_text = self.item(child, 'text')
elif len(self.item(child, 'values')) > 1:
_text = self.item(child, 'values')[idx]
else:
continue
_length = font.measure(_text) + (indent * self.item_depth(child)) if column == '#0' else font.measure(_text)
if _length > _largest:
_largest = _length
_children = self.get_children(child)
if not _children or not int(self.item(child, 'open')):
continue
_length = walk(_children)
if _length > _largest:
_largest = _length
return _largest
region = self.identify('region', event.x, event.y)
if region != 'separator':
return
largest = 0
column = self.identify('column', event.x, event.y)
font = tkfont.nametofont('TkTextFont')
font_width = font.measure('W')
row_height = font.metrics('linespace')
indent = row_height + font_width
self.style.configure('Treeview', indent=indent)
for item in self.get_children():
text = self.item(item, 'text') if column == '#0' else self.item(item, 'values')[0]
length = font.measure(text)+indent
largest = length if length > largest else largest
children = self.get_children(item)
if not children or not int(self.item(item, 'open')):
continue
length = walk(children)
if length > largest:
largest = length
self.column(column, width=largest+font_width)
def detach(self, *items):
if not items:
items = self.selection()
self.undo_data = {}
for item in items:
self.undo_data[item] = (self.parent(item), self.index(item))
parent = self.parent(item)
if parent:
value = int(self.value_get(_SIZE, parent).split(' ')[0])-1
word = 'item' if value == 1 else 'items'
self.value_set(_SIZE, f'{value} {word}', parent)
item = self.focus()
item = self.prev(item)
super(Treeview, self).detach(*self.selection())
self.focus(item)
self.selection_add(item)
self.tags_reset(excluded='selected')
def reattach(self, item, parent, index):
for idx, column in enumerate(self.columns):
if 'unique' in column and column['unique']:
if idx:
pass
else:
text = self.item(item, 'text')
children = self.get_children(parent)
column_values = []
for node in children:
column_values.append(self.item(node, 'text'))
for node in children:
while text == self.item(node, 'text'):
result = self.dlg_rename(
'Rename',
f'The name "{text}" already exists, please choose another '
f'name and try again.',
text,
)
if result in (_SKIP, _CANCEL):
return
text = result
self.item(item, text=text)
iid = self.move(item, parent, index)
return iid
def wheel_mouse(self, event):
if not self.item(self.focus(), 'text'):
self.delete(self.focus())
value = -0.1/3 if event.num == 5 else 0.1/3
self.yview('moveto', self.yview()[0] + value)
return 'break'
def button_click(self, _):
if self.active_popup_widget:
item = self.focus()
item_text = self.item(item, 'text')
wdg_text = self.active_popup_widget.var.get().strip(' ')
column = int(self.active_popup_column.lstrip('#'))
unique = self.columns[column].get('unique', False)
self.active_popup_widget.destroy()
self.active_popup_widget = None
if item_text == wdg_text and not item_text:
self.delete(item)
self.tags_reset()
return
if not item_text and not wdg_text:
self.delete(item)
self.tags_reset()
return
if not item_text:
if unique:
for node in self.get_children(self.parent(item)):
if wdg_text == self.item(node, 'text'):
self.delete(item)
self.tags_reset()
return
else:
return
if unique:
for node in self.get_children(self.parent(item)):
if wdg_text == self.item(node, 'text'):
return
if not column and wdg_text:
self.item(self.focus(), text=wdg_text)
else:
self.value_set(column-1, wdg_text, self.focus())
self.active_popup_widget = None
self.tags_reset()
def button_release(self, event):
self.focus(self.identify('item', event.x, event.y))
def button_double_click(self, event):
region = self.identify_region(event.x, event.y)
if region == 'tree' or region == 'cell':
row = self.identify_row(event.y)
column = self.identify_column(event.x)
wdg = self.active_popup_widget = self.popup_widget(row, column)
if wdg:
self.active_popup_column = column
if isinstance(wdg, Entry):
wdg.select_range(0, tk.END)
elif region == 'separator':
self.column_expand(event)
elif region == 'heading':
pass
self.after(1, self.tags_reset)
return 'break'
def item_depth(self, item):
depth = 1
parent = self.parent(item)
while parent:
depth += 1
parent = self.parent(parent)
return depth
def insert_node(self):
item = self.identify('item', self.popup.x, self.popup.y-self.winfo_rooty())
if not item:
parent = ''
idx = tk.END
elif self.value_get(_TYPE, item) == 'Node':
idx = 0
parent = item
else:
idx = self.index(item) + 1
parent = self.parent(item)
iid = self.insert(
parent,
idx,
open=True,
**{'text': '', 'values': (['', 'Node', True, '', '', datetime.now().strftime("%Y/%m/%d %H:%M:%S"), ''])},
)
self.focus(iid)
self.value_set(_IID, iid, iid)
self.tags_reset()
self.active_popup_widget = self.popup_widget(iid, '#0')
def insert_leaf(self):
item = self.identify('item', self.popup.x, self.popup.y-self.winfo_rooty())
if not item:
parent = ''
idx = tk.END
elif self.value_get(_TYPE, item) == 'Node':
idx = 0
parent = item
else:
idx = self.index(item) + 1
parent = self.parent(item)
iid = self.insert(
parent,
idx,
**{'text': '', 'values': (['', 'Leaf', '', '', '0 Kb', datetime.now().strftime("%Y/%m/%d %H-%M-%S"), ''])},
)
self.focus(iid)
self.value_set(_IID, iid, iid)
self.tags_reset()
self.active_popup_widget = self.popup_widget(iid, '#0')
def populate(self, parent, data=()):
for item in data:
iid = self.insert(parent, tk.END, **item)
self.value_set(_IID, iid, iid)
if 'children' in item:
self.populate(iid, item['children'])
def serialize(self):
def get_data(_item, _data):
for node in self.get_children(_item):
_item_data = self.item(node)
_data.append(_item_data)
if self.get_children(node):
_item_data['children'] = []
get_data(node, _item_data['children'])
data = {'headings': self.headings, 'columns': self.columns, 'data': {}}
tree_data = []
for item in self.get_children():
item_data = self.item(item)
if self.get_children(item):
item_data['children'] = []
tree_data.append(item_data)
get_data(item, item_data['children'])
else:
tree_data.append(item_data)
data['data'] = tree_data
return data
def popup_menu(self, event):
region = self.identify_region(event.x, event.y)
if region == 'heading':
return
if self.active_popup_widget:
self.active_popup_widget.destroy()
self.active_popup_widget = None
self.popup.x, self.popup.y = event.x_root, event.y_root
item = self.identify('item', event.x, event.y)
self.focus(item)
self.focus_set()
self.popup.tk_popup(event.x_root, event.y_root, 0)
def popup_widget(self, row, column):
if not row or not column:
return
bbox = self.bbox(row, column)
if not bbox:
return
if self.active_popup_widget:
self.active_popup_widget.destroy()
x_pos, y_pos, width, height = self.bbox(row, column)
item = self.identify('item', x_pos, y_pos+self.rowheight)
y_pos += height // 2
if column == '#0':
col = 0
text = self.item(item, 'text')
x_pos += self.indent // 2
width -= self.indent // 2 + 1
else:
col = int(column.lstrip('#'))
text = self.value_get(col-1, item)
x_pos += 1
wdg = None
mode = self.columns[col].get('mode', tk.WRITABLE)
unique = self.columns[col].get('unique', False)
_type = self.columns[col].get('type', None)
if _type == 'Entry':
def tab(_):
if int(column.lstrip('#')) >= len(self.columns)-1:
self.active_popup_widget = self.popup_widget(self.focus(), '#0')
self.active_popup_column = '#0'
else:
for idx, data in enumerate(self.columns[int(column.lstrip('#'))+1:]):
if 'type' in data:
self.active_popup_widget = self.popup_widget(self.focus(), f'#{idx+1}')
self.active_popup_column = f'#{idx+1}'
self.active_popup_widget.focus_set()
self.active_popup_widget.select_range(0, tk.END)
return 'break'
def update(_):
_item = self.focus()
wdg_text = wdg.var.get().strip(' ')
item_text = self.item(_item, 'text')
if item_text != wdg_text:
if not item_text and not wdg_text:
wdg.destroy()
self.active_popup_widget = None
self.delete(_item)
return
elif item_text and not wdg_text:
self.item(_item, text=item_text)
wdg.destroy()
self.active_popup_widget = None
self.focus_set()
self.focus(_item)
return
if not col:
if unique:
parent = self.parent(_item)
children = self.get_children(parent)
column_values = []
for node in children:
column_values.append(self.item(node, 'text'))
for node in children:
while wdg_text == self.item(node, 'text'):
result = self.dlg_rename(
'Rename',
f'The name "{wdg_text}" already exists, please choose another '
f'name and try again.',
wdg_text,
)
if result == '':
continue
if result in (_SKIP, _CANCEL):
return
wdg_text = result
self.item(item, text=text)
if wdg_text == self.item(node, 'text'):
return
self.item(_item, text=wdg_text)
else:
self.value_set(col-1, wdg.get(), _item)
wdg.destroy()
self.active_popup_widget = None
self.tags_reset()
self.focus_set()
self.selection_set(_item)
def destroy(_=None):
wdg.destroy()
self.active_popup_widget = None
_item = self.focus()
_text = self.item(_item, 'text')
self.tags_reset()
if not _text:
self.delete(item)
self.tags_reset()
self.focus_set()
def control_a(_=None):
def func():
wdg.select_range(0, tk.END)
wdg.icursor(tk.END)
self.after(1, func)
def move_focus(event):
if event.keysym == 'Up':
update(event)
_item = self.focus()
wdg.destroy()
self.active_popup_widget = None
self.focus_set()
prev = self.prev(self.focus())
if prev:
self.selection_set(prev)
self.focus(prev)
else:
update(event)
_item = self.focus()
wdg.destroy()
self.active_popup_widget = None
self.focus_set()
_next = self.next(self.focus())
if _next:
self.selection_set(_next)
self.focus(_next)
if mode == tk.WRITABLE:
wdg = Entry(self)
wdg.place(x=x_pos+4, y=y_pos, anchor='w', width=width-4)
wdg.var.set(text)
wdg.icursor(tk.END)
wdg.focus()
wdg.focus_set()
bindings = {
'<Up>': move_focus,
'<Down>': move_focus,
'<Tab>': tab,
# '<Control-ISO_Left_Tab>': tab,
'<Return>': update,
'<KP_Enter>': update,
'<Escape>': destroy,
'<Control-z>': destroy,
'<Control-a>': control_a,
}
for command, callback in bindings.items():
wdg.bind(command, callback)
elif _type == 'Combobox':
def tab(_):
if int(column.lstrip('#')) >= len(self.columns)-1:
self.active_popup_widget = self.popup_widget(self.focus(), '#0')
else:
for idx, data in enumerate(self.columns[int(column.lstrip('#'))+1:]):
if 'type' in data:
self.active_popup_widget = self.popup_widget(self.focus(), f'#{idx+1}')
self.active_popup_widget.focus_set()
self.active_popup_widget.select_range(0, tk.END)
return 'break'
def update(_):
_text = wdg.get().strip(' ')
if not col:
self.item(self.focus(), text=_text)
else:
self.value_set(col-1, _text, self.focus())
destroy()
self.focus_set()
def destroy(_=None):
wdg.destroy()
self.active_popup_widget = None
self.focus_set()
def control_a(_=None):
def func():
wdg.select_range(0, tk.END)
wdg.icursor(tk.END)
self.after(1, func)
state = '' if mode == tk.WRITABLE else 'readonly'
values = self.columns[col].get('values', '')
wdg = Combobox(self, state=state, values=values)
wdg.place(x=x_pos, y=y_pos, anchor='w', width=width-2)
wdg.var.set(text)
wdg.icursor(tk.END)
bindings = {
'<Tab>': tab,
# '<Control-ISO_Left_Tab>': tab,
'<Return>': update,
'<KP_Enter>': update,
'<Escape>': destroy,
'<Control-z>': destroy,
'<Control-a>': control_a,
}
for command, callback in bindings.items():
wdg.bind(command, callback)
return wdg
def popup_widget_edit(self, _):
self.active_popup_widget = self.popup_widget(self.focus(), '#0')
self.active_popup_widget.select_range(0, tk.END)
self.active_popup_widget.icursor(tk.END)
self.active_popup_widget.focus_set()
self.active_popup_column = '#0'
return 'break'
def popup_destroy(self, _):
if self.active_popup_widget:
self.active_popup_widget.destroy()
self.active_popup_widget = None
def bindings_set(self):
bindings = {
'<Up>': self.popup_destroy,
'<Down>': self.popup_destroy,
'<Key>': self.key_press,
'<Tab>': self.popup_widget_edit,
'<Escape>': self.escape,
'<Return>': self.popup_widget_edit,
'<KP_Enter>': self.popup_widget_edit,
'<Button-1>': self.button_click,
'<Button-4>': self.wheel_mouse,
'<Button-5>': self.wheel_mouse,
'<Shift-Up>': self.shift_up,
'<Shift-Down>': self.shift_down,
'<Control-a>': self.control_a,
'<Control-x>': self.cut,
'<Control-c>': self.copy,
'<Control-v>': self.paste,
'<Control-z>': self.undo,
'<KeyRelease>': self.key_release,
'<ButtonPress-3>': self.popup_menu,
'<Double-Button-1>': self.button_double_click,
'<ButtonRelease-1>': self.button_release,
'<<TreeviewOpen>>': self.expand_tree,
'<<TreeviewClose>>': self.collapse_tree,
}
for command, callback in bindings.items():
self.bind(command, callback)
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T05:48:33.890",
"Id": "478561",
"Score": "0",
"body": "I like test cases that exemplify usage. And [doc strings](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring)."
}
] |
[
{
"body": "<h2>Enumerations</h2>\n<p>You're 99% of the way to a useful <code>Enum</code>, here:</p>\n<pre><code>_IID = 0\n_TYPE = 1\n_OPEN = 2\n_TAGS = 3\n_SIZE = 4\n_MODIFIED = 5\n_DATA1 = 6\n</code></pre>\n<p>I'm not really clear on what they're used for - maybe <code>NodeKey</code>? Put them in an <code>Enum</code>.</p>\n<h2>No-op <code>if</code></h2>\n<pre><code> if platform == "linux" or platform == "linux2":\n self.platform = 'linux'\n</code></pre>\n<p>doesn't need the first predicate; simply</p>\n<pre><code>if platform == 'linux2':\n self.platform = 'linux'\n</code></pre>\n<p>or even</p>\n<pre><code>if 'linux' in platform:\n self.platform = 'linux'\n</code></pre>\n<p>However, it seems you don't even use <code>self.platform</code>, so the works could get deleted.</p>\n<h2>pathlib</h2>\n<p>Rather than using <code>path.join</code>, consider using <code>pathlib.Path</code>, which has a much nicer object-oriented interface for path manipulation.</p>\n<h2>Default for <code>get</code></h2>\n<pre><code>settings.get('focus', None)\n</code></pre>\n<p>does not need to write <code>None</code> since that is the default.</p>\n<h2>Multi-assignment</h2>\n<pre><code> self.popup = \\\n self.menu_background = None\n</code></pre>\n<p>doesn't really have any advantages; just use individual assignment.</p>\n<h2>Single dict</h2>\n<pre><code> bindings = {\n '<ButtonPress-3>': self.popup_menu,\n }\n for command, callback in bindings.items():\n self.bind(command, callback)\n</code></pre>\n<p>is odd. Why not just</p>\n<pre><code>self.bind('<ButtonPress-3>', self.popup_menu)\n</code></pre>\n<p>?</p>\n<p>Even if you had a long series of bindings, a dict would not be appropriate - you could just use a tuple of tuples.</p>\n<h2>More <code>if</code> logic</h2>\n<pre><code> if idx:\n pass\n else:\n</code></pre>\n<p>should just be</p>\n<pre><code>if not idx:\n</code></pre>\n<h2>Event numbers</h2>\n<pre><code>event.num == 5\n</code></pre>\n<p>is mysterious. I'd be surprised if tk did not have a constant for this already, but if it doesn't, you should declare one.</p>\n<h2>kwargs</h2>\n<pre><code> iid = self.insert(\n parent,\n idx,\n open=True,\n **{'text': '', 'values': (['', 'Node', True, '', '', datetime.now().strftime("%Y/%m/%d %H:%M:%S"), ''])},\n )\n</code></pre>\n<p>In this case, there is no advantage to using a dict. Just use regular unquoted kwargs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T16:33:09.643",
"Id": "478618",
"Score": "1",
"body": "Thank you for your input, I'll make them recommendations happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T21:46:40.607",
"Id": "478648",
"Score": "0",
"body": "I have made all the changes you suggested thanks once again. I have updated the code if you have the time please look at it and let me know if I have accomplished the things you spoke of. https://github.com/unodan/TkInter-Treeview-Example-Demo"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T16:19:17.443",
"Id": "243823",
"ParentId": "243799",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T02:42:49.053",
"Id": "243799",
"Score": "3",
"Tags": [
"python",
"tkinter"
],
"Title": "Tkinter treeview"
}
|
243799
|
<p>This is an easy level LeetCode question, obviously not much code to review. I'm posting C++/Java/Python here. If you'd like to review, please do so. Thank you!</p>
<h3>Problem</h3>
<blockquote>
<p>Given an array of integers, return indices of the two numbers such
that they add up to a specific target.</p>
<p>You may assume that each input would have exactly one solution, and
you may not use the same element twice.</p>
<p>Example:</p>
<p>Given nums = [2, 7, 11, 15], target = 9,</p>
<p>Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].</p>
</blockquote>
<h3>C++</h3>
<pre><code>class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int, int> index_map;
for (int index = 0;; index++) {
auto iter = index_map.find(target - nums[index]);
if (iter != index_map.end())
return vector<int> {index, iter -> second};
index_map[nums[index]] = index;
}
}
};
</code></pre>
<h3>Java</h3>
<pre><code>class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int index = 0; index < nums.length; index++) {
if (map.containsKey(target - nums[index])) {
indices[1] = index;
indices[0] = map.get(target - nums[index]);
return indices;
}
map.put(nums[index], index);
}
return indices;
}
}
</code></pre>
<h3>Python</h3>
<pre><code>class Solution:
def twoSum(self, nums, target):
index_map = {}
for index, num in enumerate(nums):
if target - num in index_map:
return index_map[target - num], index
index_map[num] = index
</code></pre>
<h3>Reference</h3>
<ul>
<li><a href="https://leetcode.com/problems/two-sum/" rel="nofollow noreferrer">LeetCode 1: Two Sum</a></li>
<li><a href="https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=most_votes&query=" rel="nofollow noreferrer">LeetCode 1 Discussion Board</a></li>
</ul>
|
[] |
[
{
"body": "<p>I'm answering about <code>java</code> code, your method signature is the following:</p>\n<blockquote>\n<p><code>public int[] twoSum(int[] nums, int target) {}</code></p>\n</blockquote>\n<p>In this way you are bound to create an instance of your <code>Solution</code> class to call the method, without modifying the internal state of your <code>Solution</code> object. It would be better to use <code>static</code> and call the method like this:</p>\n<pre><code>public class Solution {\n public static int[] twoSum(int[] nums, int target) { … your body method }\n}\n\n//in another class\nint[] nums = {2, 7, 11, 15};\nint target = 9;\nint[] result = Solution.twoSum(nums, target);\n</code></pre>\n<p>In the Leetcode contest if I understand well it has been guaranteed there is always a solution to the problem, so you will always find a couple of indexes in the for loop meeting the conditions. In a more general situation where finding a solution cannot be guaranteed it could be better return a couple of indexes like <code>[-1, -1]</code>.\nThen your method could be rewritten in the following way mantaining the same signature of the original method:</p>\n<pre><code>public static int[] twoSum(int[] nums, int target) {\n Map<Integer, Integer> map = new HashMap<>();\n\n for (int index = 0; index < nums.length; index++) {\n final int key = target - nums[index];\n\n if (map.containsKey(key)) {\n return new int[] {map.get(key), index};\n }\n map.put(nums[index], index);\n }\n\n return new int[] {-1, -1};\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T20:24:30.623",
"Id": "478645",
"Score": "1",
"body": "@Emma You are welcome and I'm agree with you, Leetcode in this case could define the problem in a better way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T08:31:07.840",
"Id": "243811",
"ParentId": "243803",
"Score": "6"
}
},
{
"body": "<p>In the C++ solution, the map should be from <code>int</code> to <code>std::size_t</code>, since that's the standard data type for indexes.</p>\n<p>The method signature looks strange: <code>nums</code> should be a <code>const</code> reference, and the return type should just be a <code>std::pair</code>. But that's probably the fault of LeetCode. Or more generally: Don't blindly assume that these coding challenges provide good code to begin with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:45:42.163",
"Id": "478612",
"Score": "5",
"body": "… or that they require good coding skills. (Many of them are basically *puzzles*, and not even programming puzzles but *math* puzzles.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:23:45.110",
"Id": "478768",
"Score": "1",
"body": "Then again, many resource limits are carefully crafted such that the bigger problem instances don't stand a chance to meet the constraints with (notably) sub-optimal asymptotic requirements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T09:09:06.643",
"Id": "243813",
"ParentId": "243803",
"Score": "8"
}
},
{
"body": "<p>Just to add on to the C++ answer.</p>\n<ul>\n<li><p>You're assuming that a solution exists, due to lack of break condition in the loop. That may work for Leetcode; however, that is not a reasonable assumption. If a solution doesn't exist, you're in Undefined Behavior Land by accessing the array out of bounds.</p>\n</li>\n<li><p>You don't need <code>return vector<int>{index, iter-second};</code>. Just <code>return {index, iter->second};</code> works due to implicit construction of vector from an initializer list.</p>\n</li>\n<li><p>Assuming it's possible that a solution doesn't exist, you might want to return an empty vector or a <code>std::optional</code>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T17:46:20.327",
"Id": "243824",
"ParentId": "243803",
"Score": "5"
}
},
{
"body": "<h1>Methods vs. Functions</h1>\n<p>None of your three solutions are object-oriented. Note: there is nothing wrong with that, in fact, the problem domain is really anemic, so there is not much to model with objects anyway.</p>\n<p>However, not being object-oriented, there is no need for objects here. In all three versions you use <em>instance methods</em> (or <em>member functions</em> as C++ calls them). The defining characteristics of instance methods are that they are dispatched ad-hoc (often dynamically) and thus allow for (runtime) ad-hoc polymorphism, and that they have privileged access to the internal representation of the object (via their <em>invisible zeroth <code>this</code> argument</em>, or in Python the very much visible first argument). But, you are not using either of those two features, so there is no need for those instance methods to be … well … instance methods. They should just be functions (or in the case of Java <em>static methods</em>), somewhat like this:</p>\n<pre><code>vector<int> twoSum(vector<int> &nums, int target) { /* … */ }\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>class Solution {\n public static int[] twoSum(int[] nums, int target) { /* … */ }\n}\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>def twoSum(nums, target):\n // …\n</code></pre>\n<h1>Data types</h1>\n<p>There is no restriction in the problem description about the size of the numbers, nor the size of the array. In Java, <code>int</code> can only store numbers from -2147483648 to +2147483647. In C++, <code>int</code> is only guaranteed to be able to store numbers from -32767 to +32767, so if your array is longer than ~30000 items or any of the numbers in the array or the target number are outside of that range, it is not guaranteed to work!</p>\n<p>Python <code>int</code> can be arbitrarily large, so there is no problem, but for Java, you should use <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/math/BigInteger.html\" rel=\"nofollow noreferrer\"><code>java.math.BigInteger</code></a>. C++ doesn't have a suitable type, unfortunately, but you can use third-party libraries such as <a href=\"https://www.boost.org/doc/libs/1_73_0/libs/multiprecision/doc/html/index.html\" rel=\"nofollow noreferrer\"><code>Boost.Multiprecision</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T08:35:22.487",
"Id": "478781",
"Score": "1",
"body": "A bit of nitpicking: Member functions in C++ are statically dispatched unless declared `virtual`. I think your generalization over the three languages is a bit inaccurate there. The conclusion remains nonetheless the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T08:38:53.733",
"Id": "478782",
"Score": "2",
"body": "@EmmaX: Thanks, clarified."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T19:07:25.767",
"Id": "243829",
"ParentId": "243803",
"Score": "3"
}
},
{
"body": "<p>I have one suggestion for the Java version.</p>\n<h2>Instead of using <code>java.util.Map#containsKey</code>, you can use <code>java.util.Map#get</code>.</h2>\n<p>In your code, you can make it short and faster by fetching the value and checking the nullity.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (map.containsKey(target - nums[index])) {\n //[...]\n indices[0] = map.get(target - nums[index]);\n //[...]\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Integer value = map.get(target - nums[index]);\nif (value != null) {\n //[...]\n indices[0] = value;\n //[...]\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T01:55:22.830",
"Id": "243840",
"ParentId": "243803",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243813",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T04:22:00.487",
"Id": "243803",
"Score": "0",
"Tags": [
"python",
"java",
"c++",
"beginner",
"programming-challenge"
],
"Title": "LeetCode 1: Two Sum"
}
|
243803
|
<p>I made the switch from JavaScript to Python lately. This is my first Python project and my first web-scraper. Do I have good practices? And could this be optimized?</p>
<pre><code>from bs4 import BeautifulSoup
import requests
urlHalf = 'codingbat.com'
print("what is your email")
inputOne = input(">")
print("password")
inputTwo = input(">")
post_params = {
"uname": inputOne,
"pw": inputTwo,
}
# urls to use
base_url = "https://codingbat.com"
login_url = "https://codingbat.com/login"
java_url = "https://codingbat.com/java/"
def get_href():
print("Getting directories")
href_array = []
initial = requests.get(base_url)
soup = BeautifulSoup(initial.content, "lxml")
tab_data = soup.find(class_="floatleft")
hrefs = tab_data.find_all(class_="h2")
for href in hrefs:
href_array.append(href.text)
return(href_array)
def gather_links():
directories = get_href()
print("Getting problem links")
link_array = []
for directory in directories:
r = requests.get(java_url + directory)
# get links to problems
content = BeautifulSoup(r.content, "lxml")
links = content.find_all(
"a", href=lambda href: href and "prob" in href)
link_array.append(links)
return(link_array)
def join_links():
linkList = gather_links()
new_link_list = {}
print("Joining links")
for link in linkList:
for each in link:
text = each.text
backUrl = each.get("href")
realUrl = "http://" + urlHalf + backUrl
new_link_list.update({text: realUrl})
return new_link_list
def scrape_data():
f = open('answers/answers.java', 'w')
linkList = join_links()
with requests.Session() as session:
post = session.post(login_url, data=post_params)
for i in linkList:
print("Scraping: " + i)
response = session.get(linkList[i])
content = BeautifulSoup(response.content, "lxml")
indentDiv = content.find(class_="indent")
table = indentDiv.find("form", {"name": "codeform"})
aceDiv = table.find("div", id="ace_div")
f.write("//" + i + ": " + linkList[i] + "\n\n")
f.write(aceDiv.text + "\n")
print("done")
if __name__ == "__main__":
scrape_data()
</code></pre>
|
[] |
[
{
"body": "<h2>Global nomenclature</h2>\n<p><code>urlHalf</code> should be <code>URL_HALF</code>. That said, a better name would be <code>DOMAIN</code>, since that's what that string actually is.</p>\n<p>Further, after declaring this you don't use it correctly; these:</p>\n<pre><code>base_url = "https://codingbat.com"\nlogin_url = "https://codingbat.com/login"\njava_url = "https://codingbat.com/java/"\n</code></pre>\n<p>could be</p>\n<pre><code>BASE_URL = 'https://' + DOMAIN\nLOGIN_URL = BASE_URL = '/login'\nJAVA_URL = BASE_URL + '/java'\n</code></pre>\n<h2>Input</h2>\n<pre><code>print("what is your email")\ninputOne = input(">")\nprint("password")\ninputTwo = input(">")\n</code></pre>\n<p>should not occur at global scope; it should occur in a function. Also, the use of <code>input</code> for passwords is insecure; use <code>getpass</code> instead.</p>\n<h2>Return parens</h2>\n<p>These parens:</p>\n<pre><code>return(href_array)\n</code></pre>\n<p>are redundant.</p>\n<h2>Generator</h2>\n<pre><code>link_array = []\nfor directory in directories:\n # ...\n link_array.append(links)\nreturn(link_array)\n</code></pre>\n<p>can simply be</p>\n<pre><code>for directory in directories:\n # ...\n yield links\n</code></pre>\n<p>or, if you want a "flattened" output that does not have nested lists, use <code>yield from links</code>.</p>\n<h2>File extensions</h2>\n<p>Does this file:</p>\n<pre><code>f = open('answers/answers.java', 'w')\n</code></pre>\n<p>actually receive Java code? It seems not, in which case - use just <code>.txt</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T16:02:58.073",
"Id": "243821",
"ParentId": "243806",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243821",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T06:32:01.937",
"Id": "243806",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Scrape every Java themed codingbat problem set and your personal solutions"
}
|
243806
|
<p>This code is using XPath to expose a library function that can check whether an XML file contains a string or an expression:</p>
<pre class="lang-java prettyprint-override"><code> private XPath xPath = XPathFactory.newInstance().newXPath();
public boolean applyFilter(String xml, String xPathExpression) {
String result = xPath.evaluate(xPathExpression, new InputSource(new StringReader(xml)));
return !(StringUtils.isEmpty(result) || "false".equals(result));
}
</code></pre>
<p>Is there a better way to do that? I'd prefer to not use external libraries here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T10:49:12.500",
"Id": "478583",
"Score": "1",
"body": "Somebody can explain me why has this question being downrated? Is this not the community where to ask those kind of stuff?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:04:27.873",
"Id": "478604",
"Score": "2",
"body": "While I haven't down voted this question yet, I found the question in the Vote to Close queue, the reason for closing the question as off-topic is because there is no context surrounding the function. Basically there isn't enough code here to perform a good code review that points out where improvements can be made. Please see our guidelines for asking in the [help center](https://codereview.stackexchange.com/help/asking)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T16:52:01.757",
"Id": "478619",
"Score": "0",
"body": "I've now read the guidelines, and I don't find a line where this question wouldn't be legitim, please show me where this question brakes guideline"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T17:23:53.440",
"Id": "478623",
"Score": "0",
"body": "https://codereview.meta.stackexchange.com/questions/3649/my-question-was-closed-as-being-off-topic-what-are-my-options/3652#3652"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T17:26:50.027",
"Id": "478624",
"Score": "1",
"body": "Sorry but no! This is Java fully working code, no pseudo code, you are here wrong!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T19:29:31.707",
"Id": "478636",
"Score": "1",
"body": "The problem is, the code is a snippet. There is no context provided, so we can't provide a meaningful review. We need to see how the code is used, what the surroundings of the code look like, where your variables are declared. We also need to know more about the goal of the code, the current description is quite vague."
}
] |
[
{
"body": "<p>Like the other said in the comments, it's a bit hard to do a code review without context; I have a suggestion for you based on the current code.</p>\n<p>Since you seem to use the <code>Apache Commons - lang3</code> library, you can use the <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/BooleanUtils.html#toBoolean-java.lang.String-\" rel=\"nofollow noreferrer\"><code>org.apache.commons.lang3.BooleanUtils#toBoolean</code></a> method to convert the string boolean. This method will return false when empty or null.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean applyFilter(String xml, String xPathExpression) throws XPathExpressionException {\n //[...]\n return !(StringUtils.isEmpty(result) || "false".equals(result));\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean applyFilter(String xml, String xPathExpression) throws XPathExpressionException {\n //[...]\n return !BooleanUtils.toBoolean(result);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T01:36:11.407",
"Id": "243839",
"ParentId": "243809",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243839",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T07:56:32.657",
"Id": "243809",
"Score": "-3",
"Tags": [
"java",
"xpath"
],
"Title": "Java xPath: simple expression evaluation"
}
|
243809
|
<p>I returned to study assembly language. And this is actually my first <em>function</em> written in Yasm. Implementing this function is a suggested project from <a href="http://www.egr.unlv.edu/%7Eed/assembly64.pdf" rel="nofollow noreferrer">this</a> book. I slightly modified the pseudo code presented in that book:</p>
<pre><code>input:
an array of integers 'array'
length of 'array' 'len'
algorithm:
for i := 0 to len-1
min := array[i]
i_min := i
for j := i+1 to len-1
if array[j] < min then
min := array[j]
i_min := j
swap array[i_min] and array[i]
</code></pre>
<p>NOTE: The inner loop starts from <code>i+1</code> so we need the outer loop only up to <code>len-2</code>. However, it is inconvenient because we can't just compare a counter with a decremented variable in a single instruction (as I understand). That is why I just left the outer loop up to <code>len-1</code> and seemingly it overflows but actually it is not a problem, and as a result a dummy swap (the last element with itself) is made as a last step. In the original code the inner loop starts from <code>i</code> (not <code>i+1</code>) which is not necessary, of course, but then the inner loop doesn't overflow, however, <code>len</code> extra operations are performed.</p>
<h1>Sorting function</h1>
<p>I think the code is well commented (maybe even overcommented (: ) so I won't explain it. The only thing I want to highlight is the use of registers instead of stack for local variables.</p>
<pre><code>section .text
global ssort
; Selection sorting algorithm
; Arguments:
; rdi : address of the array (the first element)
; rsi : value of the length
; Local variables:
; registers :
; r10 : counter for the outer loop (i)
; r11 : counter for the inner loop (j)
; r12 : min (minimal element found in the inner loop)
; rbx : i_min (position of min)
; rcx : temporary variable for swapping
ssort:
prologue:
; save registers' values
push r12
push rbx
push rcx
mov r10, 0 ; i = 0
outer_loop:
; for ( i = 0; i < length; i++ )
cmp r10, rsi ; compare i and length
jb continue_outer_loop ; if i < length (unsigned) then continue
jmp epilogue ; else end
continue_outer_loop:
mov r12, qword [rdi + (r10 * 8)] ; min = list[i]
mov rbx, r10 ; i_min = i
mov r11, r10 ; j = i
inner_loop:
; for( j = i+1; j < length; j++ )
inc r11 ; j++
cmp r11, rsi ; compare j and length
jb continue_inner_loop ; ( j < length (unsigned) ) conditional jump (distance limit)
jmp swap_elements ; ( else ) unconditional jump (no distance limit)
continue_inner_loop:
cmp r12, qword [rdi + (r11 * 8)] ; compare min and list[j]
jg update_min ; if min > list[j] then update min
jmp inner_loop ; else check next element
update_min:
mov r12, qword [rdi + (r11 * 8)] ; min = list[j]
mov rbx, r11 ; i_min = j
jmp inner_loop
swap_elements:
; swap min and list[i]
mov rcx, qword [rdi + (r10 * 8)] ; rcx = list[i], use rcx as a temporary variable
mov qword [rdi + (rbx * 8)], rcx ; list[i_min] = list[i]
mov qword [rdi + (r10 * 8)], r12 ; list[i] = min
inc r10 ; i++
jmp outer_loop
epilogue:
; restore initial registers' values
pop rcx
pop rbx
pop r12
ret
</code></pre>
<h1>Test</h1>
<p>I have tested the algorithm on four different arrays : random, one-element, two-element, and sorted (the labels <code>one</code>, <code>two</code>, <code>three</code> and <code>four</code> are for debugging purposes):</p>
<pre><code>section .data
list dq 4, 24, 17, 135, -4, 450, 324, 0, 3
len dq 9
list2 dq 1
len2 dq 1
list3 dq 4, 3
len3 dq 2
list4 dq -1, 0, 1, 2
len4 dq 4
secion .text
global _start
_start:
one:
mov rdi, list
mov rsi, qword [len]
call ssort
two:
mov rdi, list2
mov rsi, qword [len2]
call ssort
three:
mov rdi, list3
mov rsi, qword [len3]
call ssort
four:
mov rdi, list4
mov rsi, qword [len4]
call ssort
_end:
mov rax, sys_exit
mov rdi, EXIT_SUCCESS
syscall
</code></pre>
<p>What do you think?</p>
|
[] |
[
{
"body": "<p>I understand that you've written this code staying close to the high level example, but assembly code is typically not written that way. To me at least this code is less readable than it could be.<br />\nThe code that you have is of course a good starting point, but in my opinion it should not stay the final version.</p>\n<h2>A selection of improvements</h2>\n<p>To clear a register instead of using <code>mov r10, 0</code>, you should write <code>xor r10d, r10d</code>. This is both faster and shorter code.</p>\n<p>In a snippet like:</p>\n<pre><code>cmp r10, rsi\njb continue_outer_loop\njmp epilogue\ncontinue_outer_loop:\n</code></pre>\n<p>you can save yourself from writing the extra label and remove one of the jumps, if you simply <strong>reverse the condition</strong>:</p>\n<pre><code>cmp r10, rsi\njnb epilogue\n</code></pre>\n<p>This is something that you can apply 3 times in your code.</p>\n<blockquote>\n<p>The only thing I want to highlight is the use of registers instead of stack for local variables.</p>\n</blockquote>\n<p>It's certainly a good idea to use registers whenever you can, but here it makes for less readable text. Perhaps you could use the <code>EQU</code> directive to makes things clearer.</p>\n<pre><code>i equ r10 ; counter for the outer loop\nj equ r11 ; counter for the inner loop\nmin equ r12 ; minimal element found in the inner loop\ni_min equ rbx ; position of min\ntemp equ rcx ; temporary variable for swapping\n</code></pre>\n<p>I agree that you've slightly over-commented the source. Some comments were redundant.</p>\n<blockquote>\n<pre><code>mov r12, qword [rdi + (r10 * 8)] ; min = list[i]\n</code></pre>\n</blockquote>\n<p>I don't know YASM, but I think you can drop the <code>qword</code> tag in many instructions where the size is clear from the other operands:</p>\n<pre><code>mov r12, [rdi + (r10 * 8)] ; min = list[i]\n</code></pre>\n<p><code>r12</code> is a qword so the mention of the tag is redundant.</p>\n<h2>My rewrite, more the assembly way</h2>\n<p>See what you do with the <code>EQU</code> idea!</p>\n<pre><code>ssort:\n push r12\n push rbx\n push rcx\n xor r10d, r10d ; i = 0\n outer_loop: ; for ( i = 0; i < length; i++ )\n cmp r10, rsi ; compare i and length\n jnb epilogue ; if i >= length (unsigned) thenend\n mov r12, [rdi + (r10 * 8)] ; min = list[i]\n mov rbx, r10 ; i_min = i\n mov r11, r10 ; j = i \n inner_loop: ; for( j = i+1; j < length; j++ )\n inc r11 ; j++\n cmp r11, rsi ; compare j and length \n jnb swap_elements ; ( j >= length (unsigned) ) unconditional jump (no distance limit)\n cmp r12, [rdi + (r11 * 8)] ; compare min and list[j]\n jng inner_loop ; if min <= list[j] then check next element \n mov r12, [rdi + (r11 * 8)] ; min = list[j]\n mov rbx, r11 ; i_min = j\n jmp inner_loop\n swap_elements: ; swap min and list[i]\n mov rcx, [rdi + (r10 * 8)] ; rcx = list[i], use rcx as a temporary variable\n mov [rdi + (rbx * 8)], rcx ; list[i_min] = list[i]\n mov [rdi + (r10 * 8)], r12 ; list[i] = min\n inc r10 ; i++\n jmp outer_loop\n epilogue:\n pop rcx\n pop rbx\n pop r12\n ret\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T19:51:40.437",
"Id": "478728",
"Score": "0",
"body": "OK. Thank you for answer. One comment per a recommendation. About jump instructions. I do it in that way because of (from the book I referred to) \"...the target label must be within +/- 128 bytes from the conditional jump instruction\" (see comments in the code also). I think that way is safer. Though, probably the linker would throw an error if there was a problem. I mean I did it on purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T20:03:47.640",
"Id": "478732",
"Score": "0",
"body": "@LRDPRDX That's a very old recommendation dating back to the era of the 8086 pc. Since then we have the full range of conditional jumps that can jump all the distance you need. I don't think it's safer using that trick. A good compiler/assembler will choose the optimal form for you automatically, using the shortest encoding possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:49:22.293",
"Id": "243867",
"ParentId": "243815",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T11:11:57.493",
"Id": "243815",
"Score": "4",
"Tags": [
"algorithm",
"sorting",
"assembly",
"x86"
],
"Title": "Selection sort algorithm in x86_64 Yasm assembler"
}
|
243815
|
<p>I recently started doing some competitive programming in C and one of my first requirements was a high-speed token reader (analogous to the java <code>Scanner</code> class' <code>next()</code> function). A few examples of input I am most likely to read are:</p>
<pre><code>5
ccadd
bddcc
</code></pre>
<pre><code>5 4 1
1 2 5
2 3 7
3 4 8
4 5 2
2 3
</code></pre>
<p>The integer/float inputs will be handled using <code>atoi()</code> and <code>atof()</code>, so all I need to develop is a function that will read words from <code>stdin</code>. Here's the first prototype:</p>
<pre><code>#define BUF_SIZE (1 << 10) // approx 2 KiB or 1024 chars
char* next_token() {
char* buf = malloc(BUF_SIZE * sizeof(char));
char cc;
// consume leading whitespaces
while (isspace(cc=getchar())) ;
buf[0] = cc;
int i=1;
int nofs = 1;
while (!isspace(cc=getchar())) {
if (i >= BUF_SIZE*nofs) {
// gracefully extend buffer size
nofs++;
buf = realloc(buf, BUF_SIZE*nofs*sizeof(char));
}
buf[i] = cc;
i++;
}
// trim buffer
buf = realloc(buf, (i+1)*sizeof(char));
buf[i] = '\0';
return buf;
}
int main() {
int T = atoi(next_token());
while (T-- > 0) {
char* word = next_token();
// more logic here
}
}
</code></pre>
<p>Two questions I had with this code are:</p>
<ol>
<li>Is this fast enough? I think the major bottleneck lies with the <code>realloc</code> at the end, where I trim the length. If it's not fast enough, please suggest some optimizations.</li>
<li>Is this compliant with how C is generally written? I'm coming from Java and have little experience with C code. I write some embedded C but that's closer to assembly than it is to this type of code.</li>
</ol>
<p>Any further improvements are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T13:36:13.887",
"Id": "478592",
"Score": "1",
"body": "How fast is _fast enough_? Do you have any measurable requirements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:10:37.143",
"Id": "478605",
"Score": "0",
"body": "Can you quote the original programming challenge? Otherwise I don't consider this particularly off-topic, as long as this represents the solution in its entirety."
}
] |
[
{
"body": "<h2>Alignment</h2>\n<p>This will be an easy win - use <code>aligned_alloc</code> instead of <code>malloc</code>. This is only guaranteed to be available in the standard library as of C11, which you should be using anyway.</p>\n<h2>Exponential reallocation</h2>\n<p>This:</p>\n<pre><code> // gracefully extend buffer size\n nofs++;\n buf = realloc(buf, BUF_SIZE*nofs*sizeof(char));\n</code></pre>\n<p>reallocates with linear growth. Memory is cheap and CPU time is expensive, so reallocate with exponential growth instead. Choosing a growth factor is a little more involved, but growth factors of 1.5 or 2 are not uncommon.</p>\n<h2>Inner assignment</h2>\n<p>Remove the assignment-in-condition from this:</p>\n<pre><code>while (isspace(cc=getchar())) ;\n</code></pre>\n<p>It does not make anything faster, and is a nasty bit of C syntax that makes code more difficult to read, maintain and debug.</p>\n<h2>Use a <code>for</code></h2>\n<pre><code>int i=1;\nwhile (!isspace(cc=getchar())) {\n // ...\n i++;\n}\n</code></pre>\n<p>can be</p>\n<pre><code>for (int i = 1; !isspace(cc); i++) {\n // ...\n cc = getchar();\n}\n</code></pre>\n<p>noting that an initial <code>getchar()</code> would need to precede this loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:44:18.743",
"Id": "478611",
"Score": "1",
"body": "Thanks for the answer. Using C11 is not an option - I have to stick with C99. Also, why the preference for `for` over `while`? K&R seems to use inner assignment similar to what I have done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:48:36.503",
"Id": "478614",
"Score": "0",
"body": "_Using C11 is not an option_ - Fine; there are other options to do aligned allocation; I will leave this as an exercise to you. _K&R seems to use inner assignment_ - That doesn't mean that it's a good idea :) Modern practice is to discourage such a pattern, and most languages do not support such a thing for good reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:49:53.933",
"Id": "478615",
"Score": "0",
"body": "_why the preference for for over while?_ - Because in this case you have a loop counter, and a `for` is designed specifically to frame that situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:29:07.690",
"Id": "478630",
"Score": "0",
"body": "Why didn't you mention checking allocated memory for `NULL`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T02:13:40.400",
"Id": "478659",
"Score": "1",
"body": "Plain old `malloc` is required to return memory aligned to `alignof(max_align_t)` even if the space requested is smaller. That should be plenty of alignment for a short string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:11:50.193",
"Id": "478666",
"Score": "0",
"body": "My instinct (for a non-embedded system) is to reserve an arbitrary initial buffer on the stack (maybe 32KB out of my 8MB limit). That's no-cost, should avoid heap fragmentation, and your final (and only) malloc can be tailor-made and filled with a memcpy."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:31:57.837",
"Id": "243819",
"ParentId": "243817",
"Score": "6"
}
},
{
"body": "<p>It is doubtful that the program is so long that it can't all be included, but you have made an effort to comply with the <a href=\"https://codereview.stackexchange.com/help/how-to-ask\">Code Review guidelines</a>. Just be aware that comments such as <code>// more logic here</code> or <code>// ...</code> will sometimes get the question votes to close.</p>\n<p><strong>Complexity</strong><br />\nYou're a Java programmer so I'm going to assume you understand object oriented programming principles. While the C programming language isn't object oriented, some of the principles can be applied such as the Single Responsibility Principle as applied to functions and modules. Therefore the current function is too complex because it does too much. Input should be in either in the calling function or <code>next_token()</code> should consist of 2 functions, one that does input and one that parses the input for tokens.</p>\n<p><strong>Error Handling</strong><br />\nThere are 2 kinds of errors that can occur in this program, the first is memory allocation errors and the second is input errors. The <code>Xalloc()</code> functions can fail if the system has insufficient memory, while this is rare on modern computers it can still happen, especially in an embedded environment with limited memory. A call to any of the memory allocation functions should always be followed by a test to see if the pointer to the memory is <code>NULL</code> or not. If the pointer is <code>NULL</code> then the memory allocation failed and somewhere in the code the program has to decide what to do, including reporting the memory allocation error.</p>\n<pre><code>char* next_token() {\n char* buf = malloc(BUF_SIZE * sizeof(*buf));\n if (buf == NULL)\n {\n fprintf(stderr, "Memory allocation failed in next_token");\n return buf;\n }\n\n char cc;\n\n // consume leading whitespaces\n while (isspace(cc=getchar())) ;\n\n buf[0] = cc;\n int i=1;\n int nofs = 1;\n while (!isspace(cc=getchar())) {\n if (i >= BUF_SIZE*nofs) {\n // gracefully extend buffer size\n nofs++;\n buf = realloc(buf, BUF_SIZE*nofs*sizeof(*buf));\n if (buf == NULL)\n {\n fprintf(stderr, "Memory allocation failed in next_token");\n return buf;\n }\n\n }\n buf[i] = cc;\n i++;\n }\n // trim buffer\n buf = realloc(buf, (i+1)*sizeof(*buf));\n if (buf == NULL)\n {\n fprintf(stderr, "Memory allocation failed in next_token");\n return buf;\n }\n\n buf[i] = '\\0';\n return buf;\n}\n</code></pre>\n<p>Please note that in the above code I changed <code>sizeof(char)</code> to <code>sizeof(*buf)</code>. This makes the code more maintainable because the type of <code>buf</code> can be changed and the memory allocations don't require additional editing.</p>\n<p>Input errors: If the user types in a <code>CTRL-D</code> on a Unix or Linux system the program will encounter an EOF (end of file) character. It currently can't handle that. This <a href=\"https://stackoverflow.com/questions/47119083/does-isspace-accept-getchar-values\">stackoverflow</a> question covers that in more detail.</p>\n<p><strong>Character Input is Slow</strong><br />\nCharacter input using <code>getchar()</code> is slower than using buffered input and processing character input rather than processing strings after they have been read is slower. Grab as many characters as you can using a fixed size buffer and a call to <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"nofollow noreferrer\">fgets(char *buffer, int buffer_size, FILE *stream)</a>. The function <code>fgets()</code> reads a line at a time <code>buffer_size</code> can be 1K, 2K or 4K or larger + 1 (most lines will be less than 1K). This reduces the memory allocation involved and reads the input faster. You will need a pointer that points to the string starting point after the token. Using <code>fgets()</code> in the main program or in a function that calls the tokenizer will also allow you to handle the EOF situation since <code>fgets()</code> only reads until the end of the file as well as the end of the line.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:27:09.657",
"Id": "243825",
"ParentId": "243817",
"Score": "3"
}
},
{
"body": "<p>I'll comment on C style:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define BUF_SIZE (1 << 10) // approx 2 KiB or 1024 chars\n```n\nThis comment makes no sense. A `char` in C is, by definition, 1 byte. `1 << 10` bytes is exactly 1024 `char`s. I suppose I can understand if you're coming from Java where `char` is a UTF-16 code unit.\n\n```c\nchar* next_token() {\n char* buf = malloc(BUF_SIZE * sizeof(char));\n</code></pre>\n<p>Again, <code>sizeof(char)</code> is <em>defined</em> to be 1. <code>malloc(BUF_SIZE)</code> is sufficient. If you want your code to be robust against someday using, say, <code>wchar_t</code> instead of <code>char</code>, then idiomatic practice instead is to do <code>char* buf = malloc(BUFSIZE * sizeof *buf);</code>.</p>\n<p>Also, you should verify that <code>malloc</code> succeeds.</p>\n<pre class=\"lang-c prettyprint-override\"><code> char cc;\n // consume leading whitespaces\n while (isspace(cc=getchar())) ;\n</code></pre>\n<p>Personally I'd break this up instead of embedding the assignment.</p>\n<pre class=\"lang-c prettyprint-override\"><code> int nofs = 1;\n</code></pre>\n<p>I can't decipher what this variable name means. "No filesytem"? "Number Fs"? "North of South"?</p>\n<p>C is not so archaic that there is some tiny limit on lengths of variable names. Use descriptive names.</p>\n<pre class=\"lang-c prettyprint-override\"><code> buf = realloc(buf, BUF_SIZE*nofs*sizeof(char));\n</code></pre>\n<p>Others have already mentioned that you should grow your buffer exponentially.</p>\n<p><code>x = realloc(x, ...)</code> is an anti-pattern. Always assign to a temporary variable first; otherwise if <code>realloc</code> fails, you've lost your original pointer and will leak the memory.</p>\n<p>As with <code>malloc</code>, <code>sizeof(char)</code> is useless, and you should check for <code>realloc</code> failure.</p>\n<pre class=\"lang-c prettyprint-override\"><code> // trim buffer\n buf = realloc(buf, (i+1)*sizeof(char));\n</code></pre>\n<p>Same thing here as before about <code>realloc</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T06:57:36.957",
"Id": "243845",
"ParentId": "243817",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243819",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T13:34:37.703",
"Id": "243817",
"Score": "6",
"Tags": [
"c",
"programming-challenge",
"strings"
],
"Title": "C: function to read a token from stdin"
}
|
243817
|
<p>I implemented binary logistic regression for a single datapoint trained with the backpropagation algorithm to calculate derivatives for a gradient descent optimizer.</p>
<p>I am primarily looking for feedback on how I approached the functions that return optional derivatives. I used <code>nullptr</code> as a flag to indicate that derivatives are not needed, but was wondering whether the alternatives would be better (i.e., using a boolean flag, using an optional, using a non-const reference, etc.). The derivatives are optional since inference would not need the derivatives. I have left the forward pass functionality out to keep the code a bit smaller.</p>
<p>I am also interested in performance, style, and correct usage of C++ idioms. I am aware that linear algebraic methods would benefit from vectorized methods. For performance concerns, I'm more interested in things like needless copies and redundant computations rather than vectorization opportunities.</p>
<p>Note that I use the naming convention from Andrew Ng's Deep Learning course of the variable name <code>dVAR</code> in a function <code>f</code> to mean the derivative of <code>f</code> with respect to <code>VAR</code>. For example, in <code>double f(double x, double* dx)</code> <code>dx</code><span class="math-container">\$ = \frac{df(x)}{dx}\$</span>.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <array>
#include <cmath>
template<int sz>
class Vec {
public:
Vec<sz>() {}
Vec<sz>(const std::array<double, sz>& storage) : storage_{storage} {}
Vec<sz>(std::array<double, sz>&& storage) : storage_{move(storage)} {}
Vec<sz> operator-(const Vec<sz>& other) const {
std::array<double, sz> result;
for (size_t i = 0; i < storage_.size(); ++i) {
result[i] = storage_[i] - other.storage_[i];
}
return Vec<sz>{result};
}
Vec<sz> operator*(const double scalar) const {
std::array<double, sz> result;
for (size_t i = 0; i < storage_.size(); ++i) {
result[i] = scalar * storage_[i];
}
return Vec<sz>{result};
}
double operator[](const size_t idx) const {
return storage_[idx];
}
bool operator==(const Vec& other) const {
return storage_ == other.storage_;
}
size_t size() const {
return sz;
}
private:
std::array<double, sz> storage_;
};
template<int sz>
Vec<sz> operator*(const double scalar, Vec<sz> v) {
return v * scalar;
}
// Computes the sigmoid function and optionally its derivative.
double sigmoid(const double x, double* dx=nullptr) {
const double ret = 1 / (1 + std::exp(-x));
if (dx) {
*dx = ret * (1 - ret);
}
return ret;
}
// Compute the cross entropy and optionally its derivative with respect to y_hat.
double cross_entropy(const int y, const double& y_hat, double* dy_hat=nullptr) {
const double ret = - (y * std::log(y_hat) + (1 - y) * std::log(1 - y_hat));
if (dy_hat) {
*dy_hat = (y / (1 - y_hat)) + ((1 - y) / y_hat);
}
return ret;
};
// Compute the dot product and optionally its derivative with respect to w.
template<int size>
double dot_product(const Vec<size>& w,
const Vec<size>& x,
Vec<size>* dw=nullptr) {
double ret = 0.0;
for (size_t i = 0; i < w.size(); ++i) {
ret += w[i] * x[i];
}
if (dw) {
*dw = x;
}
return ret;
}
// Do gradient descent of logistic regression updating weights and bias in place.
template<int size>
double logistic_regression(Vec<size>& w,
double& b,
const Vec<size>& x,
const int y,
const int num_epochs=100,
const double learning_rate=0.001) {
double final_loss;
for (int i = 0; i < num_epochs; ++i) {
// Derivatives.
Vec<size> dw;
double dz;
double da;
// Forward pass.
const double z = dot_product(w, x, &dw) + b;
const double a = sigmoid(z, &dz);
const double loss = cross_entropy(y, a, &da);
// Backward pass.
w = w - learning_rate * (dw * dz * da);
b = b - learning_rate * (dz * da);
final_loss = loss;
}
return final_loss;
}
</code></pre>
|
[] |
[
{
"body": "<p>About the <code>Vec</code> class: Every function in this class could be <code>constexpr</code>. (Especially <code>size()</code>.) At least <code>operator==</code> and <code>size()</code> could also be <code>noexcept</code>. <code>constexpr</code> and <code>noexcept</code> could <em>vastly</em> improve code generation in most cases.</p>\n<p>(Not all of the functions should really be <code>noexcept</code>, though. <code>operator[]</code> probably shouldn’t be, for example, because it might fail for out-of-range indexes. That doesn’t mean you should literally throw an exception! A non-<code>noexcept</code> function doesn’t <em>have</em> to throw. You’re just leaving it as an option, maybe just for in debug mode (and in release mode, remove all exceptions for max performance). You should read <code>noexcept</code> as “this function can’t possibly fail” and anything else as “this function can fail, and <em>might</em> throw when it does (or it might not)”.)</p>\n<pre><code>Vec<sz>(const std::array<double, sz>& storage) : storage_{storage} {}\nVec<sz>(std::array<double, sz>&& storage) : storage_{move(storage)} {}\n</code></pre>\n<p>There’s really no point in the second constructor. Arrays are not moveable. The <em>contents</em> of an array might be moveable, but in this case the contents are <code>double</code>s, and those are also not moveable. So you have a copy-only container of copy-only stuff… the moving constructor above ends up doing exactly the same thing as the copying constructor, making it pointless.</p>\n<pre><code>Vec<sz> operator-(const Vec<sz>& other) const {\n</code></pre>\n<p>It’s generally a good idea to make your binary operations non-member functions—it’s generally a good idea to make as many things as possible non-member functions, for the sake of encapsulation.</p>\n<p>The usual way to do this is to define the assignment versions of binary ops in-class, and then write the regular binary ops in terms of the assignment versions. Or in plain C++lish:</p>\n<pre><code>class Type\n{\npublic:\n auto operator+=(Type const& t) -> Type&\n {\n // define += operation...\n return *this;\n }\n\n // rest of class...\n};\n\nauto operator+(Type a, Type const& b) -> Type\n{\n return a += b;\n}\n</code></pre>\n<p>So you should probably write an <code>operator-=</code> for <code>Vec<sz></code>, and then define <code>operator-</code> outside of the class in terms of <code>operator-=</code>. (You probably want an <code>operator-=</code> <em>anyway</em>, for reasons I’ll explain later.)</p>\n<pre><code>Vec<sz> operator-(const Vec<sz>& other) const {\n std::array<double, sz> result;\n for (size_t i = 0; i < storage_.size(); ++i) {\n result[i] = storage_[i] - other.storage_[i];\n }\n return Vec<sz>{result};\n}\n</code></pre>\n<p><code>result</code> seems to be completely superfluous here. You store the calculation results in <code>result</code>, and then copy them into the <code>Vec<sz></code>’s internal <code>storage_</code>… why not skip that step, and store the calculation results directly into the <code>storage_</code>? Like so:</p>\n<pre><code>Vec<sz> operator-(const Vec<sz>& other) const {\n auto result = Vec<sz>{};\n for (size_t i = 0; i < storage_.size(); ++i) {\n result.storage_[i] = storage_[i] - other.storage_[i];\n }\n return result;\n}\n</code></pre>\n<p>With C++17’s guaranteed return value elision, you can end up with no copying at all.</p>\n<pre><code>Vec<sz> operator*(const double scalar) const {\n</code></pre>\n<p>This is another function that would be better as a non-member. In this case, you also have symmetry going on:</p>\n<pre><code>template <int sz>\nauto operator*(Vec<sz> const& v, double scalar) -> Vec<sz> { ... }\ntemplate <int sz>\nauto operator*(double scalar, Vec<sz> const& v) -> Vec<sz> { ... }\n</code></pre>\n<p>You could make one or both of those a friend of the class, or define both in terms of a member function (perhaps named <code>scale()</code>).</p>\n<p><code>operator==</code> should also be a non-member, and it should come along with <code>operator!=</code>. (<code>operator[]</code> has to be a member, of course.)</p>\n<pre><code>double sigmoid(const double x, double* dx=nullptr) {\n</code></pre>\n<p>I’m not a fan of default arguments. They make <em>writing</em> functions easier, but <em>using</em> them harder… which is the worst kind of feature, because you only write a function once, but you use them many times.</p>\n<p>Even worse, in this case you’re actually ruining the function by making it less efficient <em>for every possibly usage</em>. If I don’t want the the derivative, I still have to pay for the extra function parameter and the check. If I do, I’m paying for a mostly unnecessary check (branching is slow!).</p>\n<p>And on top of all that, if you <em>don’t</em> try to cram all possible usage scenarios into a single function, you avoid the entire question of whether to use <code>nullptr</code> or <code>std::optional</code>, and make the function easier to use because you can return the derivative directly:</p>\n<pre><code>double sigmoid(const double x) {\n return 1 / (1 + std::exp(-x));\n}\n\nstd::tuple<double, double> sigmoid_with_derivative(const double x) {\n const double ret = 1 / (1 + std::exp(-x));\n return {ret, ret * (1 - ret)};\n}\n\n// usage:\nauto a = sigmoid(x); // when I don't want the derivative\nauto [a, dx] = sigmoid_with_derivative(x); // when I do want it\n</code></pre>\n<p>The same idea applies to <code>cross_entropy()</code> and <code>dot_product()</code>.</p>\n<pre><code>double cross_entropy(const int y, const double& y_hat, double* dy_hat=nullptr) {\n</code></pre>\n<p>I’m guessing the <code>&</code> here is a typo, but just in case not: there’s (usually!) nothing to be gained by passing built-in types like <code>double</code> by reference.</p>\n<pre><code>template<int size>\ndouble logistic_regression(Vec<size>& w,\n double& b,\n const Vec<size>& x,\n const int y,\n const int num_epochs=100,\n const double learning_rate=0.001) {\n</code></pre>\n<p>Hm… okay, the last two arguments here are probably legitimate use case for default arguments.</p>\n<p>As for the <em>first</em> two arguments… I’m really not a fan of “out” arguments, if that’s what <code>w</code> and <code>b</code> are intended to be. But I don’t know what the intended usage of this function looks like, so I don’t know if maybe this is one of the very, very rare cases where they make sense.</p>\n<p>Assuming that isn’t the case, a better form for this function might be something like:</p>\n<pre><code>template<int size>\nstd::tuple<double, Vec<size>, double>\nlogistic_regression(Vec<size> w,\n double b,\n const Vec<size>& x,\n const int y,\n const int num_epochs=100,\n const double learning_rate=0.001) {\n\n // ... everything else in the function is the same except the last line...\n\n return {final_loss, w, b};\n}\n</code></pre>\n<p>or:</p>\n<pre><code>template<int size>\nstd::tuple<double, Vec<size>, double>\nlogistic_regression(Vec<size> const w_,\n double const b_,\n const Vec<size>& x,\n const int y,\n const int num_epochs=100,\n const double learning_rate=0.001) {\n auto ret = std::tuple{0.0, w_, b_};\n auto&& final_loss = std::get<0>(ret);\n auto&& w = std::get<1>(ret);\n auto&& b = std::get<2>(ret);\n\n // ... everything else in the function is the same except the last line...\n\n return ret;\n}\n</code></pre>\n<p>Just a few final comments:</p>\n<p>It’s good that you’re not fussing over vectorization, because, really, compilers are smart enough to already vectorize your loops. Even in the case that you’re working with a compiler that’s not, it’s pretty trivial to signal you want a loop vectorized with intrinsics or OMP or other means.</p>\n<p>You are correct worry that your biggest performance drain will probably be poor algorithms and/or unnecessary copying. I don’t see any obvious signs of redundant or unnecessary calculations, so you might be okay on that front. That leaves unnecessary copying.</p>\n<p>You’re using arrays for your data types, rather than, say, vectors. That can actually be a performance pessimization, especially if <code>sz</code> is large. Arrays are non-moveable; they can only be copied. Vectors can be copied or moved, and moves are so fast they’re basically free. On the other hand, when vectors <em>do</em> need to be copied, the cost can be many times more than the cost of copying an array, due to the overhead of allocation.</p>\n<p>Note that I’m not suggesting you should use vectors instead! I’m just saying that when using arrays, you can’t count on moves. Every move is actually a copy. So if you <em>are</em> going to use arrays—which is a perfectly sensible thing to do for reasonably small <code>sz</code>—you need to be very careful to avoid <em>both</em> copies <em>and</em> moves.</p>\n<p>You note (via a tag) that you’re using C++17. That’s good! That works out a <em>lot</em> in your favour, because C++17 brought in guaranteed elision. What does that mean?</p>\n<p>It means that for a function like this:</p>\n<pre><code>template <int size>\nauto dot_product_with_derivative(\n Vec<size> const& w,\n Vec<size> const& x)\n -> std::tuple<double, Vec<size>>\n{\n auto ret = std::tuple{0.0, x};\n\n for (std::size_t i = 0; i < size; ++i)\n ret += w[i] * x[i];\n\n return ret;\n}\n</code></pre>\n<p>used like this:</p>\n<pre><code>auto [z, dw] = dot_product_with_derivative(w, x);\n</code></pre>\n<p>there is only a single array copy done (when the array in <code>x</code> is copied into what will eventually be <code>dw</code>). All other temporary/intermediate values are elided away. This is guaranteed by the standard starting C++17.</p>\n<p>The only place I can see where you (might!) have a superfluous copy is in the line:</p>\n<pre><code>w = w - learning_rate * (dw * dz * da);\n</code></pre>\n<p>That’s because <code>(dw * dz * da)</code> has to create a temporary <code>Vec<size></code> (let’s call it <code>tmp1</code>)…</p>\n<p>… and then <code>learning_rate * tmp1</code> has to create <em>another</em> temporary <code>Vec<size></code> (let’s call it <code>tmp2</code>)…</p>\n<p>… and then <code>w - tmp2</code> has to create <em>ANOTHER</em> temporary…</p>\n<p>… when then gets assigned into <code>w</code>.</p>\n<p>That’s <em>THREE</em> temporary <code>Vec<size></code> objects, each of which requires copying an array of <code>doubles</code>.</p>\n<p>A smart compiler might be able to elide away that third temporary… but why risk it? Why not write <code>operator-=</code> and do:</p>\n<pre><code>w -= learning_rate * (dw * dz * da);\n</code></pre>\n<p>But that still leaves 2 temporaries.</p>\n<p>Is there any reason you want to force <code>(dw * dz * da)</code> to be calculated first? That creates a temporary <code>Vec<size></code> that you then multiply with <code>learning_rate</code>.</p>\n<p>Why not reorder your calculation as: <code>(learning_rate * dz * da) * dz</code>?</p>\n<pre><code>w -= (learning_rate * dz * da) * dz;\n</code></pre>\n<p>Now <code>(learning_rate * dz * da)</code> only creates a temporary <code>double</code>… not a temporary <code>Vec<size></code>. A temporary <code>double</code> is basically free.</p>\n<p>Then <code>(learning_rate * dz * da) * dz</code> creates a temporary <code>Vec<size></code>. That’s unavoidable. Let’s call that <code>tmp1</code>.</p>\n<p>And then <code>w -= tmp1</code> creates no temporaries.</p>\n<p>So you’ve gone from:</p>\n<pre><code>// Up to 3 temporaries created:\nw = w - learning_rate * (dw * dz * da);\n</code></pre>\n<p>to:</p>\n<pre><code>// Only 1 temporary created at maximum, guaranteed:\nw -= (learning_rate * dz * da) * dz;\n</code></pre>\n<p>without changing the actual calculation.</p>\n<p>Now, I’m not sure if a smart compiler could do that optimization on its own. I’m not sure how blasé optimizers these days are about ignoring your parentheses, or reordering built-in operations around user-defined operations. Your original line of code <em>might</em> be compiled without all those temporaries. (Probably will, to be honest.) But why risk it? Rewriting <code>x = x - y</code> as <code>x -= y</code> is an optimization as old as time—it’s why <code>operator-=</code> exists in the first place. And reordering your computation so all the <code>double</code> calculations get done first and then only a single <code>Vec<size></code> calculation has to be done is also a trivial thing to do. Even if it ultimately makes no difference (because optimizing compilers are so smart these days), it doesn’t really cost anything.</p>\n<p>Without knowing the expected values for the <code>sz</code> parameter of <code>Vec<sz></code>, I can’t comment on whether using arrays is a good idea. If <code>sz</code> is fairly small, then sure. Even if <code>sz</code> ranges into a hundred or so, maybe, if you’re not making a ton of these objects. But past a certain point, trucking the arrays around will get so unwieldy that it might make more sense to use vectors. With vectors, you would pay a lot more at construction time, and if copying… but you get super-fast moves. Might be worth it, especially if the rest of the code is written to take advantage of moving.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T21:41:42.413",
"Id": "478646",
"Score": "0",
"body": "My primary motivation for using arrays rather than vectors was to avoid the runtime check of ensuring the length of vectors are the same in each function. Is there a clean way to avoid having `if (x.size() != w.size())` and `(size() != other.size())` splattered in all functions that do operations on vectors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:04:24.823",
"Id": "478704",
"Score": "0",
"body": "Sure, you can keep the size as a compile-time constant/template parameter. Just make sure the size is set in the constructors, and then just never change it anywhere else—it becomes a class invariant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T20:19:49.413",
"Id": "478735",
"Score": "0",
"body": "Ah, I see the `sz` and `size` template parameters remain. I had it wrong in my head that those would go away with a refactor from `array` to `vector`!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T20:06:07.010",
"Id": "243832",
"ParentId": "243818",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243832",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T15:23:04.173",
"Id": "243818",
"Score": "5",
"Tags": [
"c++",
"performance",
"c++17",
"machine-learning",
"numerical-methods"
],
"Title": "C++ - Logistic Regression Backpropagation with Gradient Descent"
}
|
243818
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.