body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Please review my System information class.</p>
<p>Systeminfo can be used to retrieve system management data from the BIOS. This data is mostly strings.</p>
<p>Is the code easy to understand and maintainable?</p>
<p>Is the code efficient?</p>
<p>How could it be improved?</p>
<p>systeminfo.hpp:</p>
<pre><code>/*
SystemInfo class is a C++ wrapper for the System Management BIOS data available on PCs
*/
#ifndef SYSTEMINFO_HPP_
#define SYSTEMINFO_HPP_
#include <string>
class Systeminfo {
public:
// System information data retrieved on construction and string members populated
Systeminfo();
// get product family
const std::string get_family() const;
// get manufacturer - generally motherboard or system assembler name
const std::string get_manufacturer() const;
// get product name
const std::string get_productname() const;
// get BIOS serial number
const std::string get_serialnumber() const;
// get SKU / system configuration
const std::string get_sku() const;
// get a universally unique identifier for system
const std::string get_uuid() const;
// get version of system information
const std::string get_version() const;
Systeminfo(Systeminfo const&) = delete;
Systeminfo& operator=(Systeminfo const&) = delete;
private:
std::string family_;
std::string manufacturer_;
std::string productname_;
std::string serialnumber_;
std::string sku_;
std::string uuid_;
std::string version_;
};
#endif // SYSTEMINFO_HPP_
</code></pre>
<p>systeminfo.cpp:</p>
<pre><code>#include "systeminfo.hpp"
#ifndef _WIN32
#error Currently SystemInfo can only be built for the Windows platform
#endif
#include <Windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
namespace {
#pragma pack(push)
#pragma pack(1)
/*
SMBIOS Structure header (System Management BIOS) spec:
https ://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.3.0.pdf
*/
struct SMBIOSHEADER
{
uint8_t type;
uint8_t length;
uint16_t handle;
};
/*
Structure needed to get the SMBIOS table using GetSystemFirmwareTable API.
see https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemfirmwaretable
*/
struct SMBIOSData {
uint8_t Used20CallingMethod;
uint8_t SMBIOSMajorVersion;
uint8_t SMBIOSMinorVersion;
uint8_t DmiRevision;
uint32_t Length;
uint8_t SMBIOSTableData[1];
};
// System Information (Type 1)
struct SYSTEMINFORMATION {
SMBIOSHEADER Header;
uint8_t Manufacturer;
uint8_t ProductName;
uint8_t Version;
uint8_t SerialNumber;
uint8_t UUID[16];
uint8_t WakeUpType; // Identifies the event that caused the system to power up
uint8_t SKUNumber; // identifies a particular computer configuration for sale
uint8_t Family;
};
#pragma pack(pop)
// helper to retrieve string at string offset. Optional null string description can be set.
const char* get_string_by_index(const char* str, int index, const char* null_string_text = "")
{
if (0 == index || 0 == *str) {
return null_string_text;
}
while (--index) {
str += strlen(str) + 1;
}
return str;
}
// retrieve the BIOS data block from the system
SMBIOSData* get_bios_data() {
SMBIOSData *bios_data = nullptr;
// GetSystemFirmwareTable with arg RSMB retrieves raw SMBIOS firmware table
// return value is either size of BIOS table or zero if function fails
DWORD bios_size = GetSystemFirmwareTable('RSMB', 0, NULL, 0);
if (bios_size > 0) {
bios_data = (SMBIOSData*)malloc(bios_size);
// Retrieve the SMBIOS table
DWORD bytes_retrieved = GetSystemFirmwareTable('RSMB', 0, bios_data, bios_size);
if (bytes_retrieved != bios_size) {
free(bios_data);
bios_data = nullptr;
}
}
return bios_data;
}
// locates system information memory block in BIOS table
SYSTEMINFORMATION* find_system_information(SMBIOSData* bios_data) {
uint8_t* data = bios_data->SMBIOSTableData;
while (data < bios_data->SMBIOSTableData + bios_data->Length)
{
uint8_t *next;
SMBIOSHEADER *header = (SMBIOSHEADER*)data;
if (header->length < 4)
break;
//Search for System Information structure with type 0x01 (see para 7.2)
if (header->type == 0x01 && header->length >= 0x19)
{
return (SYSTEMINFORMATION*)header;
}
//skip over formatted area
next = data + header->length;
//skip over unformatted area of the structure (marker is 0000h)
while (next < bios_data->SMBIOSTableData + bios_data->Length && (next[0] != 0 || next[1] != 0)) {
next++;
}
next += 2;
data = next;
}
return nullptr;
}
}
Systeminfo::Systeminfo() {
SMBIOSData* bios_data = get_bios_data();
if (bios_data) {
SYSTEMINFORMATION* sysinfo = find_system_information(bios_data);
if (sysinfo) {
const char* str = (const char*)sysinfo + sysinfo->Header.length;
manufacturer_ = get_string_by_index(str, sysinfo->Manufacturer);
productname_ = get_string_by_index(str, sysinfo->ProductName);
serialnumber_ = get_string_by_index(str, sysinfo->SerialNumber);
version_ = get_string_by_index(str, sysinfo->Version);
// for v2.1 and later
if (sysinfo->Header.length > 0x08)
{
static const int max_uuid_size{ 50 };
char uuid[max_uuid_size] = {};
_snprintf_s(uuid, max_uuid_size, max_uuid_size-1, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
sysinfo->UUID[0], sysinfo->UUID[1], sysinfo->UUID[2], sysinfo->UUID[3],
sysinfo->UUID[4], sysinfo->UUID[5], sysinfo->UUID[6], sysinfo->UUID[7],
sysinfo->UUID[8], sysinfo->UUID[9], sysinfo->UUID[10], sysinfo->UUID[11],
sysinfo->UUID[12], sysinfo->UUID[13], sysinfo->UUID[14], sysinfo->UUID[15]);
uuid_ = uuid;
}
if (sysinfo->Header.length > 0x19)
{
// supported in v 2.4 spec
sku_ = get_string_by_index(str, sysinfo->SKUNumber);
family_ = get_string_by_index(str, sysinfo->Family);
}
}
free(bios_data);
}
}
const std::string Systeminfo::get_family() const {
return family_;
}
const std::string Systeminfo::get_manufacturer() const {
return manufacturer_;
}
const std::string Systeminfo::get_productname() const {
return productname_;
}
const std::string Systeminfo::get_serialnumber() const {
return serialnumber_;
}
const std::string Systeminfo::get_sku() const {
return sku_;
}
const std::string Systeminfo::get_uuid() const {
return uuid_;
}
const std::string Systeminfo::get_version() const {
return version_;
}
</code></pre>
<p>Example program using systeminfo:</p>
<pre><code>#include "systeminfo.hpp"
#include <iostream>
#include <iomanip>
#include <chrono>
int main() {
auto start = std::chrono::high_resolution_clock::now();
Systeminfo info;
std::cout << std::left << ::std::setw(14) << "Manufacturer: " << info.get_manufacturer() << '\n'
<< std::left << ::std::setw(14) << "Product Name: " << info.get_productname() << '\n'
<< std::left << ::std::setw(14) << "Serial No: " << info.get_serialnumber() << '\n'
<< std::left << ::std::setw(14) << "UUID: " << info.get_uuid() << '\n'
<< std::left << ::std::setw(14) << "Version: " << info.get_version() << std::endl;
if (!info.get_family().empty()) {
std::cout << std::left << ::std::setw(14) << "Product family: " << info.get_family() << std::endl;
}
if (!info.get_sku().empty()) {
std::cout << std::left << ::std::setw(14) << "SKU/Configuration: " << info.get_sku() << std::endl;
}
auto end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(end - start).count();
std::cout << "elapsed time for systeminfo: " << elapsed_time_ms << " ms" << std::endl;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Consider making Systeminfo a POD</h1>\n<p>I would separate getting information from the SMBIOS from how to store the result. Make <code>Systeminfo</code> a <a href=\"http://en.wikipedia.org/wiki/Plain_Old_Data_Structures\" rel=\"nofollow noreferrer\">plain old struct</a>:</p>\n<pre><code>struct Systeminfo {\n std::string family;\n std::string manufacturer;\n ...\n};\n</code></pre>\n<p>And move the original constructor into a plain function:</p>\n<pre><code>Systeminfo get_systeminfo() {\n Systeminfo info;\n ...\n info.family = ...;\n info.manufacturer = ...;\n ...\n return info;\n}\n</code></pre>\n<p>The reason is simply because getting the information is a one-shot action, afterwards there is nothing special you can do with the result anymore, so it really doesn't need its own class.</p>\n<h1>Avoid unnecessary <code>#pragma</code>s</h1>\n<p>I would avoid using <code>#pragma pack</code>. While the C standard technically allows a compiler to add an arbitrary amount of padding between members, as long as the alignment rules are satisfied, programs need to be able to interoperate with each other, so there are some exact rules of how a struct should be layed out in memory.\nFor example the <a href=\"https://docs.microsoft.com/en-us/cpp/build/x64-software-conventions?view=vs-2019#types-and-storage\" rel=\"nofollow noreferrer\">C ABI on Windows</a>, Linux and other major desktop operating systems will guarantee that in this case, where the members of the structs you declare are all naturally aligned, they will all be tightly packed together.</p>\n<h1>Add bounds checks</h1>\n<p>It is possible that a BIOS chip is corrupt, or that the manufacturer just put invalid data in it (yes, this is sadly not uncommon). Consider that strings in the BIOS might not be properly NUL-terminated. So when reading the BIOS data, perform bounds checking to ensure you don't read past the end of it.</p>\n<h1>Simplify formatting the output</h1>\n<p>C++ hasn't made formatting strings very easy (although C++20 will fix that with <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"nofollow noreferrer\"><code>std::format()</code></a>). But you can simplify your code so you don't need the calls to <code>std::left</code> and <code>std::setw()</code>; just write:</p>\n<pre><code>std::cout << "Manufacturer: " << info.manufacturer << "\\n"\n << "Product Name: " << info.productname << "\\n"\n << "Serial No: " << info.serialnumber << "\\n";\n << "UUID: " << info.uuid << "\\n"\n << "Version: " << info.version << "\\n";\n</code></pre>\n<p>If you do want to use programatically format the output, then try to create a function to avoid repeating yourself. For example:</p>\n<pre><code>static void format_field(const std::string &name, const std::string &value) {\n std::cout << std::left << std::setw(14) << name << ": " << value << "\\n";\n}\n\nint main() {\n ...\n format_field("Manufacturer", info.manufacturer);\n format_field("Product Name", info.productname);\n ...\n}\n</code></pre>\n<p>That is both much clearer, and whenever you want to change how the output is formatted, you might only have to change one line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T17:03:05.373",
"Id": "488153",
"Score": "0",
"body": "For your bounds checking suggestion, what should I do? Have a maximum read length until find a null char?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:22:43.227",
"Id": "488269",
"Score": "0",
"body": "@arcomber: You could use [ThorsIOUtils](https://github.com/Loki-Astari/ThorsIOUtil/blob/master/src/ThorsIOUtil/Format.h) (if you don't have C++20) `std::cout << IO::make_cppformat(\"%-14s: %d\\n\", name, value);` With a review needed here :-) https://codereview.stackexchange.com/q/188812/507"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:55:59.860",
"Id": "249043",
"ParentId": "249034",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T12:32:49.703",
"Id": "249034",
"Score": "2",
"Tags": [
"c++",
"configuration"
],
"Title": "Systeminfo, a C++ class to retrieve system management data from the BIOS"
}
|
249034
|
<p><strong>Background</strong></p>
<p>The basics of this project are already covered <a href="https://codereview.stackexchange.com/questions/248695/contact-form-with-spam-prevention">here</a>.</p>
<p>I received the suggestions to:</p>
<ul>
<li>not create the exercise with JavaScript.</li>
<li>use pictures instead of plaintext.</li>
</ul>
<p>I tried to implement the suggestions like this:</p>
<p><strong>The code</strong></p>
<p>Example-form:</p>
<pre class="lang-html prettyprint-override"><code><form method="POST" action="../php/send.php" class='input'>
<label>Your Name:</label><br>
<input type="text" name="myName" placeholder="Name" required/><br><br>
<label>Your Email:</label><br>
<input type="text" name="myEmail" placeholder="E-Mail" required/><br><br>
<!-- Honeypott -->
<input type="text" id="website" name="website"/>
<label>Message:</label><br>
<textarea rows="8" name="myMessage" style='width: 100%; resize: none; border: 1px solid Gray; border-radius: 4px; box-sizing: border-box; padding: 10px 10px;' placeholder="Message" required></textarea><br><br>
<input id='exerciseText' name='exerciseText', style='display: none;' value='
<?php
include '../php/randomExercise.php';
$var = randText();
echo $var;
?>'>
</input>
<label id='exercise'>
<?php
echo randExer($var);
?>
</label><br>
<input type='number' id='solution' name='solution' placeholder="Solution" required/>
<div style='display: inline-block; text-align: left;'>
<input type="checkbox" id="consent" name="consent" value="consent" required="">
<label>I agree with saving and sending this message according to the privacy policy.
</label>
</div>
<input style='' type="submit" value="Send"/>
</form>
</code></pre>
<p><code>randomExercise.php</code>:</p>
<pre class="lang-php prettyprint-override"><code><?php
$encryptionPassword = "***";
function randExer($rand) {
//========================
//Change for customization
//========================
//First of all:
//Please change the $encryptionPassword above (16 chars)
//Width of the created image
$width = 200;
//Height of the created image
$height = 50;
//RGB values for the text on the black image
$textColorRed = 255;
$textColorGreen = 255;
$textColorBlue = 255;
//RGB values of the random lines on the image
$linesRed = 192;
$linesGreen = 192;
$linesBlue = 192;
//Value between 1 and 5
$fontSize = 5;
//Coordinates where the text starts
$upperLeftCornerX = 18;
$upperLeftCornerY = 18;
//Text will be rotated by $angle-degrees
$angle = 10;
global $encryptionPassword;
//=============================================
//From here no changes needed for customization
//=============================================
$random = openssl_decrypt($rand,"AES-128-ECB", $encryptionPassword);
//Creates a black picture
$img = imagecreatetruecolor($width, $height);
//uses RGB-values to create a useable color
$textColor = imagecolorallocate($img, $textColorRed, $textColorGreen, $textColorBlue);
$linesColor = imagecolorallocate($img, $linesRed, $linesGreen, $linesBlue);
//Adds text
imagestring($img, $fontSize, $upperLeftCornerX, $upperLeftCornerY, $random . " = ?", $textColor);
//Adds random lines to the images
for($i = 0; $i < 5; $i++) {
imagesetthickness($img, rand(1, 3));
$x1 = rand(0, $width / 2);
$y1 = rand(0, $height / 2);
$x2 = $x1 + rand(0, $width / 2);
$y2 = $y1 + rand(0, $height / 2);
imageline($img, $x1, $x2, $x2, $y2, $linesColor);
}
$rotate = imagerotate($img, $angle, 0);
//Attribution: https://stackoverflow.com/a/22266437/13634030
ob_start();
imagejpeg($rotate);
$contents = ob_get_contents();
ob_end_clean();
$imageData = base64_encode($contents);
$src = 'data:'. mime_content_type($contents) . ';base64,' . $imageData;
return '<img alt="" src="' . $src . '">';
};
function randText() {
global $encryptionPassword;
//Creating random (simple) math problem
$arr = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");
$item1 = $arr[array_rand($arr)];
$item2 = $arr[array_rand($arr)];
$random = $item1 . " + " . $item2;
$encrypted = openssl_encrypt($random,"AES-128-ECB", $encryptionPassword);
return $encrypted;
}
?>
</code></pre>
<p><code>send.php</code></p>
<pre class="lang-php prettyprint-override"><code><?php
//Get simple math-problem (e.g. four + six)
$str = openssl_decrypt($_REQUEST['exerciseText'], "AES-128-ECB", "***");
$first = strpos($str, " ");
//Get first number (e.g. four)
$substr1 = substr($str, 0, $first);
//Get second number (e.g. six)
$substr2 = substr($str, $first + 3, strlen($str) - $first - 3);
$arr = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");
/*
* Convertring strings to numbers, e.g.
* four -> 4
* six -> 6
*/
$x = 0;
$y = 0;
for($i = 0; $i <= 10; $i++) {
if(strcmp($substr1, $arr[$i]) == 0) {
$x = $i;
break;
}
}
for($i = 0; $i <= 10; $i++) {
if(strcmp($substr2, $arr[$i]) == 0) {
$y = $i;
break;
}
}
$z = intval($_POST['solution']);
//Did user enter right solution?
if($z == ($x + $y)) {
//Bot filled the honeypott-tree
if(!empty($_POST['website'])) {
header("Location:/sites/messageError.html");
die();
}
$userName = $_POST['myName'];
$userEmail = $_POST['myEmail'];
$userMessage = $_POST['myMessage'];
//Did user enter a valid email-adress?
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
header("Location:http:///sites/messageError.html");
die();
}
//Creating message
$to = "***";
$subject = "New Contact-form message";
$body = "Content:";
$body .= "\n\n Name: " . $userName;
$body .= "\n\n Email: " . $userEmail;
$body .= "\n\n Message: " . $userMessage;
//Trying to send message
if(mail($to, $subject, $body)){
header("/sites/message.html");
die();
} else{
header("Location:/sites/messageError.html");
die();
}
}
header("Location:/sites/messageError.html");
?>
</code></pre>
<p><strong>Questions</strong></p>
<p>All suggestions are welcome, but I am especially interested in the security of this approach and how to further improve it.</p>
<hr />
<p>Edit: I just created a <a href="https://codeberg.org/philippwilhelm/Simple_Captcha_System" rel="nofollow noreferrer">git-repository</a> and a working <a href="https://demo.philippwilhelm.eu/index.php" rel="nofollow noreferrer">demo</a>. Maybe that's helpful for review.</p>
|
[] |
[
{
"body": "<p>Speaking about security, there are several issues:</p>\n<ul>\n<li><p>As a rule the attacker will go the easy way: send and analyze first request, remember <code>exerciseText</code> and <code>solution</code>, then send an unlimited number of requests from an unlimited number of devices. So, at least, you should use a timestamp to shorten the token's lifetime and tie it to a specific IP.</p>\n</li>\n<li><p>In fact your encryption function makes no sense, because there are only 121 solutions and the attacker will notice very quickly that the <code>solution</code> always has the same value for same <code>exerciseText</code>. Therefore, you should at least append an UUID to your <code>$random</code> variable.</p>\n</li>\n<li><p>Although, in your case the attacker can bypass your CAPTACHA just by sending <code>exerciseText=0&solution=0&...</code>. It's because there are no input validations and as a result your math verification comes down to <code>if(0 == (0 + 0))</code>. Moreover, on improperly configured servers it may lead to Full Path Disclosure.</p>\n</li>\n</ul>\n<p>As a last word I would like to say that it is very difficult to develop a spam free form without storing tokens into sessions or database. Well, your solution may be useful for learning and low traffic websites, but it's useless for popular ones.</p>\n<h2>UPDATE</h2>\n<p>For a full PoC that bypasses CAPTCHA, check this cURL example:</p>\n<pre><code>curl -v https://demo.philippwilhelm.eu/send.php -d "myName=a&myEmail=a@b.c&myMessage=m&exerciseText=0&solution=0&consent=consent"\n</code></pre>\n<p>As a result your server returns following headers:</p>\n<pre><code>< HTTP/1.1 302 Found\n< Date: Thu, 10 Sep 2020 16:17:50 GMT\n* Server Apache is not blacklisted\n< Server: Apache\n< Upgrade: h2\n< Connection: Upgrade\n< Location: https://philippwilhelm.eu/sites/message.html\n< Content-Length: 0\n< Content-Type: text/html; charset=utf-8\n</code></pre>\n<p>Considering that server redirects the request to <code>/message.html</code> it means that message was successfully sent. So, let see what's wrong with your code (I removed your comments and added clarifications for each critical point):</p>\n<pre><code># If attacker submits an empty/invalid `exerciseText` the `openssl_decrypt()` is not able to decrypt message and returns `FALSE` to `$str`\n$str = openssl_decrypt($_REQUEST['exerciseText'], "AES-128-ECB", "***");\n\n$first = strpos($str, " ");\n\n# Both `$substr1` and `$substr2` will be assigned `FALSE` because both `substr()` are trying to extract a portion of string from a `FALSE` value\n$substr1 = substr($str, 0, $first);\n$substr2 = substr($str, $first + 3, strlen($str) - $first - 3);\n\n$arr = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");\n\n# Both `$x` and `$y` will remain equal to zero because in both cases `strcmp()` is not able to "convert strings to numbers"\n$x = 0;\n$y = 0;\n\nfor($i = 0; $i <= 10; $i++) {\n if(strcmp($substr1, $arr[$i]) == 0) {\n # The `$substr1` is `FALSE`, so `$i` is never assigned to `$x`\n $x = $i;\n break;\n }\n}\n\nfor($i = 0; $i <= 10; $i++) {\n if(strcmp($substr2, $arr[$i]) == 0) {\n # The `$substr2` is `FALSE`, so `$i` is never assigned to `$y`\n $y = $i;\n break;\n }\n}\n\n# If attacker submits an empty `solution` the `$z` will be assigned the value `0` (zero)\n$z = intval($_POST['solution']);\n\n# Finally `$z=0; $x=0; $y=0` so the following expression will be always true\nif($z == ($x + $y)) {\n ...\n}\n</code></pre>\n<p>To avoid such vulnerabilities you must validate user input before before using it. So, let's rewrite the lines above to make sure that attacker won't be able to cheat on your validation:</p>\n<pre><code># PHP has built-in functions for obtaining, validating and sanitizing submitted data, therefore in most cases you don't need to use superglobals\n$solution = filter_input(INPUT_POST, 'solution', FILTER_VALIDATE_INT);\n$exerciseText = filter_input(INPUT_POST, 'exerciseText');\n\n# Since in both cases `filter_input()` returns `FALSE` if something is wrong, you should not go further if any of these variables are invalid\nif ($solution === false || $exerciseText === false) {\n die('bad request');\n}\n\n# Next you must make sure that `$exerciseText` has been successfully decrypted, otherwise exit your script\n$str = openssl_decrypt($exerciseText, "AES-128-ECB", "***");\nif (!$str) {\n die('cannot decrypt exercise');\n}\n\n# Define your numbers array\n$arr = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");\n\n# Since the `$str` contains several numbers separated by `+`, just split them and strip spaces\n$words = array_map('trim', explode('+', $str)); //-> ["one", "two"]\n\n# As the numbers match the indexes of `$arr`, you can find them using `array_intersect()`\n$numbers = array_intersect($arr, $words); //-> [1=>"one", 2=>"two"]\n\n# Make sure that it found two numbers\nif (count($numbers) != 2) {\n die('hacking attempt');\n}\n\n# Sum up the indexes for the found numbers\n$sum = array_sum(array_keys($numbers));\n\n# Finally, check if user submitted a correct solution\nif ($solution == $sum) {\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T10:49:10.693",
"Id": "488310",
"Score": "0",
"body": "https://codereview.stackexchange.com/questions/248695/contact-form-with-spam-prevention#:~:text=save%20the%20text%20in%20a%20session%20variable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T12:24:33.447",
"Id": "488314",
"Score": "0",
"body": "I don't really understand the third point. Could you explain where (and how) I should validate the input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:08:17.740",
"Id": "488337",
"Score": "1",
"body": "@PhilippWilhelm I updated my answer and added more details."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T10:21:27.610",
"Id": "249150",
"ParentId": "249036",
"Score": "4"
}
},
{
"body": "<h1>Security</h1>\n<p>The code basically attempts to create a <a href=\"https://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"nofollow noreferrer\">Client-side Request Forgery (CSRF)</a> token. Some frameworks like <a href=\"https://laravel.com\" rel=\"nofollow noreferrer\">laravel</a> provide this functionality <a href=\"https://laravel.com/docs/8.x/csrf\" rel=\"nofollow noreferrer\">by default</a>. It may not be worth the effort of incorporating a framework if all you need is one feature but if there were others then you might consider it.</p>\n<p>Generation of a CSRF token would be much simpler than creating an image an encoding it into string format.</p>\n<p>As <a href=\"https://stackoverflow.com/a/31683058/1575353\">this StackOverflow answer</a> explains a CSRF token can be generated with various techniques. Hopefully the server running the code is using PHP 7.2 or later given <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">Supported versions</a>. Presuming that is the case <a href=\"https://php.net/random_bytes\" rel=\"nofollow noreferrer\"><code>random_bytes()</code></a> to generate a cryptographically secure string of pseudo-random bytes and <a href=\"https://php.net/bin2hex\" rel=\"nofollow noreferrer\"><code>bin2hex()</code></a> can be used to convert that string to a hexadecimal representation. As Victor's answer mentions a session can be used to store the token. A session can be started with <a href=\"https://php.net/session_start\" rel=\"nofollow noreferrer\"><code>session_start()</code></a></p>\n<pre><code>session_start();\n$_SERVER['csrf_token'] = bin2hex(random_bytes(32));\n</code></pre>\n<p>Then that token can be included in the form:</p>\n<pre><code><form method="POST" action="../php/send.php" class='input'>\n <input type="hidden" name="csrf_token" value="<?=$_SERVER['csrf_token']?>" />\n</code></pre>\n<p>Then when the form is submitted, that value can be compared with the session value:</p>\n<pre><code><?php\nif ($_POST['csrf_token'] !== $_SERVER['csrf_token']) {\n header("Location:/sites/messageError.html");\n}\n</code></pre>\n<p>This is especially important if PHP code should be executed before HTML or other output is emitted - e.g. sending headers.</p>\n<h1>Review remarks</h1>\n<h2>PHP within HTML</h2>\n<p>Instead of this:</p>\n<blockquote>\n<pre><code><input id='exerciseText' name='exerciseText', style='display: none;' value='\n <?php\n include '../php/randomExercise.php';\n $var = randText();\n echo $var;\n ?>'>\n</code></pre>\n \n</blockquote>\n<p>The external PHP file can be included at the top of the file:</p>\n<pre><code><?php\ninclude '../php/randomExercise.php';\n?>\n <html> <!-- continue HTML below -->\n</code></pre>\n<p>Then in the form the function can be called using the shortcut syntax for <code>echo</code> - i.e. <code><?= ?></code>:</p>\n<pre><code> <input id='exerciseText' name='exerciseText', style='display: none;' value='<?=randText()?>'>\n</code></pre>\n<h2>HTML</h2>\n<h3>inline styles</h3>\n<p>Many elements have inline styles - e.g.</p>\n<blockquote>\n<pre><code><textarea rows="8" name="myMessage" style='width: 100%; resize: none; border: 1px solid Gray; border-radius: 4px; box-sizing: border-box; padding: 10px 10px;' placeholder="Message" required></textarea><br><br>\n</code></pre>\n</blockquote>\n<p>Those styles could be moved to a <code><style></code> tag or external stylesheet so the markup won't contain so much styling.</p>\n<p>p.s. <code>padding: 10px 10px;</code> can be condensed to <code>padding: 10px;</code></p>\n<h3>email input type</h3>\n<p>There is an input for email address:</p>\n<blockquote>\n<pre><code><input type="text" name="myEmail" placeholder="E-Mail" required/><br><br>\n</code></pre>\n</blockquote>\n<p>The <em>type</em> attribute could be changed to <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email\" rel=\"nofollow noreferrer\"><em>email</em></a> for validation purposes.</p>\n<h2>PHP</h2>\n<h3>Avoid <code>else</code> keyword when not necessary</h3>\n<p>In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about many ways to keep code lean - like avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n<p>It is wise to avoid the <code>else</code> keyword - especially when it isn't needed - e.g. when a previous block contains a <code>return</code> statement or call to <code>die()</code> - for example:</p>\n<blockquote>\n<pre><code> if(mail($to, $subject, $body)){\n header("/sites/message.html");\n die();\n } else{\n header("Location:/sites/messageError.html");\n die();\n }\n</code></pre>\n</blockquote>\n<p>p.s. should there be a <code>Location:</code> here?</p>\n<blockquote>\n<pre><code> header("/sites/message.html");\n</code></pre>\n</blockquote>\n<h3>store encryption password in constant instead of global variable</h3>\n<p>In general usage of global variables is frowned upon for many reasons -e.g. because program state can be unpredictable, testing can be more difficult, etc. (refer to answers to <a href=\"https://softwareengineering.stackexchange.com/q/148108/244085\"><em>Why is Global State so Evil?</em></a> for more information). A constant can be declared with <a href=\"https://php.net/declare\" rel=\"nofollow noreferrer\"><code>declare()</code></a> or the <a href=\"https://php.net/const\" rel=\"nofollow noreferrer\"><code>const()</code></a> keyword.</p>\n<h3>splitting strings</h3>\n<p>In <em>send.php</em> sub-string functions are used to split the string into words. The PHP function <a href=\"https://php.net/explode\" rel=\"nofollow noreferrer\"><code>explode()</code></a> could be used with <a href=\"https://php.net/list\" rel=\"nofollow noreferrer\"><code>list()</code></a> to assign to <code>$substr1</code> and <code>$substr2</code> in a single line.</p>\n<h3>generating number names</h3>\n<p>The method <a href=\"https://www.php.net/manual/en/numberformatter.format.php\" rel=\"nofollow noreferrer\"><code>NumberFormatter::format()</code></a> class and the <a href=\"https://php.net/range\" rel=\"nofollow noreferrer\"><code>range()</code> function</a>\ncould be used to generate the number names in <code>$arr</code>.</p>\n<pre><code>$fmt = new NumberFormatter( 'en', NumberFormatter::SPELLOUT);\n$arr = [];\nforeach(range(0,10) as $number) {\n $arr[] = $fmt->format($number);\n}\n</code></pre>\n<p>Bearing in mind that a beginner might be unfamiliar with such advanced techniques, the array could be generated with <a href=\"https://php.net/array_map\" rel=\"nofollow noreferrer\"><code>array_map()</code></a>:</p>\n<pre><code>$fmt = new NumberFormatter( 'en', NumberFormatter::SPELLOUT );\n$arr = array_map($fmt->format, range(0, 10));\n</code></pre>\n<h3>Searching for numbers by name</h3>\n<p>The PHP function <a href=\"https://php.net/array_search\" rel=\"nofollow noreferrer\"><code>array_search()</code></a> could likely be used to eliminate the <code>for</code> loops to assign values for <code>$x</code> and <code>$y</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T15:38:31.870",
"Id": "249165",
"ParentId": "249036",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249150",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T12:51:14.920",
"Id": "249036",
"Score": "3",
"Tags": [
"beginner",
"php",
"html",
"security"
],
"Title": "Contact form with spam-prevention - follow-up"
}
|
249036
|
<p>In pandas lot's of methods have the keyword argument inplace. This means if <code>inplace=True</code>, the called function will be performed on the object itself, and returns None, on the other hand if <code>inplace=False</code> the original object will be untouched, and the method is performed on the returned new instance. I've implemented it in my projects too, but I ended up with too much repetitive coding, so I decided to make a decorator which gets the job done. It also appends to the method's docstring, if it's formatting follows <a href="https://numpydoc.readthedocs.io/en/latest/format.html" rel="nofollow noreferrer">numpy-style docs</a>. The only thing that needs to be added is <code>return self</code> to every method's end. I think that step also can be skipped with metaclasses, but for the time being it's not implemented.</p>
<pre class="lang-py prettyprint-override"><code>import re
from functools import wraps
from copy import copy
_inplace_doc = """\n\tinplace : bool, optional
Whether to apply the operation on the dataset in an "inplace" manner.
This means if inplace is True it will apply the changes directly on
the current object and returns None. If inplace is False, it will
leave the current object untouched, but returns a copy of it, and
the operation will be performed on the copy. It's useful when
chaining operations on a dataset. See fluent interfacing and
method cascading.\n\n\t"""
def _has_parameter_section(method):
try:
return "Parameters" in method.__doc__
except TypeError:
return False # There's no docstring provided
def _build_doc(method, appendix):
# finding sections (single words above 4+ slashes)
patt = r"(\w+(?=\s*[-]{4,}[^/]))"
splitted_doc = re.split(patt, method.__doc__)
try:
# We try to append to section below Parameters.
target = splitted_doc.index("Parameters") + 1
except ValueError:
return method.__doc__
splitted_doc[target] = splitted_doc[target].rstrip() + appendix
return ''.join(_ for _ in splitted_doc if _ is not None)
def _update_doc(method, doc):
if _has_parameter_section(method):
newdoc = _build_doc(method, doc)
method.__doc__ = newdoc
else:
newdoc = """\n\tParameters
----------""" + _inplace_doc
nodoc_head = (f"Docstring automatically created for {method.__name__}. "
"Parameter list may not be complete.\n")
if method.__doc__ is not None:
method.__doc__ += newdoc
else:
method.__doc__ = nodoc_head + newdoc
def inplacify(method):
"""
Decorator used to allow a function in a class to be called
as `inplace`.
"""
_update_doc(method, _inplace_doc)
@wraps(method)
def wrapper(self, *args, **kwds):
inplace = kwds.pop("inplace", True)
if inplace:
method(self, *args, **kwds)
else:
return method(copy(self), *args, **kwds)
return wrapper
</code></pre>
<p>Test cases:</p>
<pre class="lang-py prettyprint-override"><code>class Dummy:
def __init__(self, x):
self.x = x
@inplacify
def increment(self, value):
self.x += value
return self
@inplacify
def multiply(self, value):
"""
This is some numpy-style doc.
Parameters
----------
value : float
The value ``x`` will be multiplied with it.
Returns
-------
None..
Just another section to see if it's working.
"""
self.x *= value
return self
@inplacify
def subtract(self, value):
"""
This is some numpy-style doc. Without any
sections after Parameters.
Parameters
----------
value : float
The value to subtract from ``x``.
"""
self.x -= value
return self
if __name__ == "__main__":
a = Dummy(1)
a.increment(1)
assert a.x == 2
b = a.increment(2, inplace=False)
assert a.x == 2
assert b.x == 4
print(help(a.increment))
a.multiply(1)
assert a.x == 2
b = a.multiply(2, inplace=False)
assert a.x == 2
assert b.x == 4
print(help(a.multiply))
a.subtract(1)
assert a.x == 1
b = a.subtract(2, inplace=False)
assert a.x == 1
assert b.x == -1
print(help(a.subtract))
</code></pre>
<p>I know there are few missing things: no type hints, no documentation for internal methods.
Any criticism/improvement is appreciated.</p>
|
[] |
[
{
"body": "<p>Minor, but here:</p>\n<pre><code>''.join(_ for _ in splitted_doc if _ is not None)\n</code></pre>\n<p><code>_</code> should be reserved for when you need to bind a object to a name, but don't need the variable. <a href=\"https://stackoverflow.com/q/5893163/3000206\">Here</a> is a good resource on the topic. You are in fact using <code>_</code> though as both the final result and in the check, so I'd give it a proper name.</p>\n<p>If none of the valid strings are falsey (empty), you can also use <a href=\"https://docs.python.org/3/library/functions.html#filter\" rel=\"nofollow noreferrer\"><code>filter</code></a> here with <code>None</code> as the function:</p>\n<pre><code>''.join(filter(None, splitted_doc))\n</code></pre>\n<p>This will remove <em>all falsey</em> elements; not just <code>None</code>s. That shouldn't affect anything though since the <code>"".join</code> will effectively get rid of any empty strings anyway.</p>\n<hr />\n<p>Also, not directly related to the code, but "splitted" doesn't sound idiomatic. I'd call it just <code>split_doc</code>.</p>\n<hr />\n<p>I'd be careful about repeated concatenation of strings using <code>+</code>. Each concatenation requires making a copy of the accumulated string. Performance <em>likely</em> won't be a concern here, but I would consider changing this so it instead <code>append</code>s each piece to a list, then <code>join</code>s the list in the end to create the string all at once. This is Python's equivalent of the <code>StringBuilder</code> that some other languages have.</p>\n<p>You can see from some quick benchmarking in Python 3.8 that it can make a fair difference:</p>\n<pre><code>from timeit import timeit\n\ndef repeated_concat(n):\n acc = ""\n for _ in range(n):\n acc = acc + "a"\n return acc\n\ndef repeated_concat_pe(n):\n acc = ""\n for _ in range(n):\n acc += "b"\n return acc\n\ndef join_concat_li(n):\n return "".join(["c" for _ in range(n)])\n\ndef join_concat_ge(n):\n return "".join("d" for _ in range(n))\n\nN = int(3e5)\nTRIALS = int(1e3)\n\nprint(timeit(lambda: repeated_concat(N), number=TRIALS))\nprint(timeit(lambda: repeated_concat_pe(N), number=TRIALS))\nprint(timeit(lambda: join_concat_li(N), number=TRIALS))\nprint(timeit(lambda: join_concat_ge(N), number=TRIALS))\n\n40.2907047\n40.597058800000006\n13.207587099999998\n19.380548700000006\n</code></pre>\n<p>Also, apparently list comprehensions can perform better than a generator expression when <code>join</code>ing? I'm going to have to test that more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T14:53:14.633",
"Id": "488015",
"Score": "0",
"body": "I wasn't aware of the `str` concatenation performance, thank you for pointing that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T15:30:37.437",
"Id": "488018",
"Score": "0",
"body": "@PéterLeéh Just for completeness, I added some quick timings for comparison. You'd want to test your exact scenario though to be sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:39:21.123",
"Id": "488025",
"Score": "0",
"body": "I think that the difference between list comprehension and generator expression is somehow due to the fact that `str.join` puts it into a list right away if it is a generator. But I never quite got why this means such a drastic performance difference, especially since you include the list comprehension in the timing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:45:53.223",
"Id": "488026",
"Score": "1",
"body": "@Graipher Ahh, that could be it. I didn't expect `join` to force the iterable into a list first. It might skip that step if the argument is already a list, which means that if you use a gen expression, there's the overhead of the generator + the creation of a list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:54:22.237",
"Id": "488029",
"Score": "1",
"body": "@Graipher That does appear to be it. [`join` first passes the iterable to a helper](https://github.com/python/cpython/blob/22748a83d927d3da1beaed771be30887c42b2500/Objects/stringlib/join.h#L25), and that helper [does an immediate return if the iterable is a list](https://github.com/python/cpython/blob/8182cc2e68a3c6ea5d5342fed3f1c76b0521fbc1/Objects/abstract.c#L1981), otherwise it [forces it into a list](https://github.com/python/cpython/blob/8182cc2e68a3c6ea5d5342fed3f1c76b0521fbc1/Objects/abstract.c#L1995)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T14:45:43.623",
"Id": "249038",
"ParentId": "249037",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T14:11:27.497",
"Id": "249037",
"Score": "5",
"Tags": [
"python",
"numpy"
],
"Title": "Inplace operations for a class with numpy-style docs"
}
|
249037
|
<p>I wrote a login system for an app I am developing, but I'm not really happy with the code I have at the moment. I feel like there is a better way at tackling a problem like this. In particular I'm not happy with the way my callback method has to be called specifically on the ui thread, I thought maybe there is a better way of doing that.
I have 2 fields; username and password</p>
<ul>
<li>The user presses the login button</li>
<li>A new thread is started that handles the connecting to a web page</li>
<li>The webpage tries to find a row that matches with the username and password</li>
<li>The page outputs a 0 on success and 1 on failure</li>
<li>The app calls the callback with the output of the webpage</li>
<li>The callback runs on the main thread and decides what to do (next activity or a Toast)</li>
</ul>
<p>These are the most important methods in my LoginActivity class</p>
<pre><code>private boolean emptyField() {
if (usernameEt.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill in a username", Toast.LENGTH_SHORT).show();
return true;
}
if (passwordEt.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill in a password", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private void login() {
if (emptyField()) {
return;
}
setEnabled(false);
new Login().makeRequest(new Callback() {
@Override
public void onComplete(Result result) {
setEnabled(true);
if (result instanceof Result.Success) {
Intent dsp = new Intent(LoginActivity.this, MainActivity.class);
startActivity(dsp);
} else {
Result.Error error = (Result.Error) result;
Toast.makeText(getApplicationContext(), error.message, Toast.LENGTH_SHORT).show();
}
}
}, usernameEt.getText().toString(), passwordEt.getText().toString());
}
private void setEnabled(boolean enabled) {
usernameEt.setEnabled(enabled);
passwordEt.setEnabled(enabled);
buttonLogin.setEnabled(enabled);
}
</code></pre>
<p>The login class that handles the complete login sequence</p>
<pre><code>public class Login {
public void makeRequest(final Callback callback, final String username, final String password) {
new Thread(new Runnable() {
@Override
public void run() {
final Result result = makeSynchronousRequest(username, password);
callback.execute(result);
}
}).start();
}
public Result makeSynchronousRequest(String username, String password) {
String urlString = "http://10.0.2.2/login.php";
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") +
"&&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
try (OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream())) {
wr.write(data);
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
StringBuilder sb = new StringBuilder();
String line;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String returnData = sb.toString();
switch (Integer.parseInt(returnData)) {
case 0:
return new Result.Success<>("");
case 1:
return new Result.Error("Username and password do not match");
}
return new Result.Error("Something unexpected happened: " + returnData);
}
} catch (SocketTimeoutException e) {
return new Result.Error("The login page is currently offline");
} catch (IOException e) {
e.printStackTrace();
return new Result.Error(e.getMessage());
}
}
}
</code></pre>
<p>Result class</p>
<pre><code>public abstract class Result {
private Result() {}
public static final class Success<T> extends Result {
public T data;
public Success(T data) {
this.data = data;
}
}
public static final class Error extends Result {
public String message;
public Error(String message) {
this.message = message;
}
}
}
</code></pre>
<p>Callback class</p>
<pre><code>public abstract class Callback {
public abstract void onComplete(Result result);
public void execute(final Result result) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
onComplete(result);
}
});
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have read your question since a few days. Given that nobody else has something to say, you can guess that your code is quite good.</p>\n<p>I do not develop on Android so I cannot say anything about your concern of the way the callback method has to be called specifically on the ui thread. However I can give you some hints on your code:</p>\n<p>Be coherent and use meaningful method names; <code>emptyField</code> looks like it will clear the fields while it will validate them and display a message. You should rename it to something more clear on what it will do.</p>\n<p>Apply the Single responsibility principle. The <code>emptyField</code> method validate and display a message. Try to create two separate methods, one to validate and another to display the errors. By doing this you will hopefully create one method that display all the errors at once, this is better for the user experience.</p>\n<p>The Single responsibility principle also apply to your <code>Login</code> class. Try to move all the code used to communicate with the server to another class. Keep only the formatting and parsing logic in the <code>Login</code> so that you can easily create other kind of "requests" later without duplicating the communication code. There are libraries aimed to communicate with a server, you should consider using one if you plan to send more requests to your server.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T11:55:13.083",
"Id": "249213",
"ParentId": "249039",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T15:19:07.587",
"Id": "249039",
"Score": "2",
"Tags": [
"java",
"multithreading",
"android",
"callback"
],
"Title": "Login system using callbacks in android"
}
|
249039
|
<p>I wrote this log function and it works but is there a better way to write into the file stream and console at the same time?</p>
<pre><code>
//The function
void log(int lvl, const char * format, ...) {
va_list args;
va_start(args, format);
//If lvl < 0 the prefix will not be used
if (lvl>=lINFO) {
time_t now = time(NULL);
struct tm tm = *localtime(&now);
//Printing to the console
printf("[%d-%02d-%02d %02d:%02d:%02d %s] [%s] : ",
tm.tm_year+1900,
tm.tm_mon+1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
__log_name,
parse_lvl(lvl)
);
//Printing into the file
//Checking if NULL(if yes the file wont be used)
if(__log_filestream)
fprintf(__log_filestream,
"[%d-%02d-%02d %02d:%02d:%02d %s] [%s] : ",
tm.tm_year+1900,
tm.tm_mon+1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
__log_name,
parse_lvl(lvl)
);
}
//Printing to the console
vprintf(format, args);
printf("\n");
//Printing into the file
if (__log_filestream) {
vfprintf(__log_filestream, format, args);
fprintf(__log_filestream, "\n");
}
va_end(args);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>You're doing <code>printf</code> and <code>fprintf</code> <em>twice</em> for the same arguments.</p>\n<p>So, it's replicating code.</p>\n<p><code>*printf</code> is somewhat heavyweight. So, I'd do <code>sprintf</code> [or <code>snprintf</code>] to a buffer (e.g):</p>\n<pre><code>len = sprintf(buf,...);\n</code></pre>\n<p>And then do:</p>\n<pre><code>fwrite(buf,1,len,stdout);\nif (__log_filestream)\n fwrite(buf,1,len,__log_filestream);\n</code></pre>\n<p>The overhead of using the buffer is less than calling a <code>printf</code> function twice. I'd repeat the same buffering for the <code>vprintf/vfprintf</code></p>\n<hr />\n<p>Or, better yet, just keep concatenating to the buffer and do a single [pair of] <code>fwrite</code> at the end. This is [yet] better performance.</p>\n<p>And, this is especially helpful if there are multiple threads doing logging because the given log message will come out on a single line (e.g.):</p>\n<pre><code>threadA timestamp | threadA message\nthreadB timestamp | threadB message\n</code></pre>\n<p>With two separate writes to a stream, two threads could intersperse partial parts of their message [not nearly as nice]:</p>\n<pre><code>threadA timestamp\nthreadB timestamp\nthreadA message\nthreadB message\n</code></pre>\n<p>Note that this is enough to guarantee that we see nice/whole lines. But, it doesn't prevent a race for the ordering of two lines for each stream. That is, we could have [on <code>stdout</code>]:</p>\n<pre><code>threadA line\nthreadB line\n</code></pre>\n<p>But, it might not prevent [on the logfile stream]:</p>\n<pre><code>threadB line\nthreadA line\n</code></pre>\n<p>So, we could wrap the <code>fwrite</code> calls in a mutex. Or, we could just wrap the calls in a <code>flockfile(stdout)</code> / <code>funlockfile(stdout)</code> pairing (See: <code>FORCE_SEQUENTIAL</code> in the example below)</p>\n<hr />\n<p>If this function is the <em>only</em> function writing to the logfile and/or <code>stdout</code>, you might get even better performance by using <code>write</code> instead of <code>fwrite</code> [YMMV]</p>\n<hr />\n<p>Here's how I would refactor the code [and, if you're paranoid, you could use <code>snprintf</code>]:</p>\n<pre><code>// The function\nvoid\nlog(int lvl,const char *format,...)\n{\n va_list args;\n char buf[1000];\n char *cur = buf;\n\n // If lvl < 0 the prefix will not be used\n if (lvl >= lINFO) {\n time_t now = time(NULL);\n struct tm tm;\n localtime_r(&now,&tm);\n\n // Printing to the console\n cur += sprintf(cur,"[%d-%02d-%02d %02d:%02d:%02d %s] [%s] : ",\n tm.tm_year + 1900,tm.tm_mon + 1,tm.tm_mday,\n tm.tm_hour,tm.tm_min,tm.tm_sec,\n __log_name,parse_lvl(lvl));\n }\n\n va_start(args, format);\n cur += sprintf(cur,format,args);\n va_end(args);\n\n *cur++ = '\\n';\n *cur = 0;\n\n size_t len = cur - buf;\n\n // lock [either] stream to force both streams to come out "atomically" in\n // the same order\n#ifdef FORCE_SEQUENTIAL\n flockfile(stdout);\n#endif\n\n // Printing to the console\n fwrite(buf,1,len,stdout);\n\n // Printing into the file\n if (__log_filestream)\n fwrite(buf,1,len,__log_filestream);\n\n#ifdef FORCE_SEQUENTIAL\n funlockfile(stdout);\n#endif\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:41:50.620",
"Id": "249053",
"ParentId": "249042",
"Score": "3"
}
},
{
"body": "<h1>API</h1>\n<p>You only provide one function, but it seems worthwhile documenting the expectations:</p>\n<ul>\n<li><code>log(level, format, ...)</code></li>\n<li><code>level</code> appears to expect a set of pre-defined values, notably <code>lINFO</code>. Is there an enum somewhere? Should the type of <code>level</code> by an enum typedef?</li>\n<li><code>format</code> should not include a trailing newline</li>\n</ul>\n<h1>Implementation</h1>\n<h2>Comments</h2>\n<p>Your comments seem to indicate the code you wish you had written. Perhaps you should trust your instincts?</p>\n<p>In general, comments that describe what is happening are bad comments: the <em>code</em> describes what is happening! These types of comments only serve to drift slowly out of date, forgetting to mention things that are added later. Eventually, they turn into a sort of dotty grandmother, who remembers what you were like at version 1, but doesn't remember that you're integrated with another package now, with one major plugin already and a new one on the way...</p>\n<p>Instead, write comments to draw attention to things that might be non-obvious, or to highlight negative information (Negative as in "the dog that didn't bark", like the <code>default</code> in a switch statement except at a higher level).</p>\n<h2>Organization</h2>\n<p>I meant it when I said you should trust your instincts! If you're writing a comment to give a name to more than one line of code, maybe that code is a function.</p>\n<p>(And dundernames*, like <code>__log_filestream</code>, are reserved. Don't use them.)</p>\n<pre><code>void log ... etc ...\n{\n if (level >= lINFO) {\n time_t now = time(NULL);\n struct tm tm = *localtime(&now);\n\n log_prefix_to_stream(stdout, lvl, &tm);\n log_prefix_to_stream(log_filestream, lvl, &tm);\n }\n\n va_list args;\n va_start(args, format);\n\n log_vprint_to_stream(lvl, format, args, stdout);\n log_vprint_to_stream(lvl, format, args, log_filestream);\n\n va_end(args);\n}\n</code></pre>\n<p>And seeing that refactoring puts two things in my head: first, that the prefix should probably be a function by itself, and second that the doubled printing lines could probably go into a single function, if only we were smart enough!</p>\n<p>Something like this:</p>\n<pre><code>void log ... etc ...\n{\n if (lvl >= lINFO) \n log_prefix(lvl);\n\n va_list args;\n va_start(args, format);\n\n log_vprintf(format, args);\n log_append_newline();\n\n va_end(args);\n}\n</code></pre>\n<p>Which then leads to <code>log_prefix</code> wanting to call <code>log_vprint</code>, but needing an intermediate function to make a va_list:</p>\n<pre><code>void log_printf(format, ...);\n</code></pre>\n<p>Which might call <code>log_vprintf</code>, in the interest of DRY, and we've found the missing <code>if</code> statement(s)!</p>\n<pre><code>void log_vprintf(format, args)\n{\n if (log_filestream != NULL)\n vfprintf(log_filestream, format, args);\n vfprintf(stdout, format, args);\n}\n</code></pre>\n<p>=====</p>\n<p>(*): "dundernames" are <strong>d</strong>ouble-<strong>under</strong>score-<strong>names</strong> -- that is, names that start with '__'</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T21:56:21.877",
"Id": "249057",
"ParentId": "249042",
"Score": "2"
}
},
{
"body": "<p><strong>Time detail</strong></p>\n<p>When the clock goes from daylight savings time to standard time, the below code can print the same time that was reported one hour earlier.</p>\n<pre><code>//Printing to the console\nprintf("[%d-%02d-%02d %02d:%02d:%02d %s] [%s] : ",\n tm.tm_year+1900,\n tm.tm_mon+1,\n tm.tm_mday,\n tm.tm_hour,\n tm.tm_min,\n tm.tm_sec,\n __log_name,\n parse_lvl(lvl)\n);\n</code></pre>\n<p>To help distinguish times, consider printing <code>tm.tm_isdst</code>.</p>\n<p>Alternatively, research <code>strftime()</code> and <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">IS0 8601</a>.</p>\n<pre><code>char buf[100];\nstrftime(buf, sizeof buf, "%FT%T%Z", &tm);\nprintf("[%s %s] [%s] : ", buf, __log_name, parse_lvl(lvl));\n</code></pre>\n<hr />\n<p>Or use UTC and skip timezones</p>\n<pre><code>time_t now = time(NULL);\nstruct tm tm = *gmtime(&now);\nchar buf[100];\nstrftime(buf, sizeof buf, "%FT%TZ", &tm);\nprintf("[%s %s] [%s] : ", buf, __log_name, parse_lvl(lvl));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T20:30:58.803",
"Id": "249098",
"ParentId": "249042",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249053",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:49:10.703",
"Id": "249042",
"Score": "3",
"Tags": [
"c",
"file",
"logging"
],
"Title": "C Logging Function"
}
|
249042
|
<p>technical interview question i got from daily interview pro</p>
<p>A palindrome is a sequence of characters that reads the same backwards and forwards. Given a string, s, find the longest palindromic substring in s.</p>
<p>Example:</p>
<pre><code>
Input: "banana"
Output: "anana"
Input: "million"
Output: "illi"
</code></pre>
<p>i was wondering if there is any way to optimize the code more</p>
<p>Also is using built in functions such as join(),index() and so on not preferred for a coding interview ?Because by using it it makes it so much easier in python compared to languages like java</p>
<pre><code>class Solution:
def checkOddChars(self,lst):
ls = []
for i in lst:
if lst.count(i) == 1:
ls.append(i)
return ls
def checkPalindrome(self,lst):
return lst[:] == lst[::-1]
def longestPalindrome(self, s):
lst = list(s)
while lst:
if self.checkPalindrome(lst) :
return(''.join(lst))
oddChars = self.checkOddChars(lst)
if lst[0] in oddChars:
del lst[0]
if lst[len(lst)-1] in oddChars:
del lst[len(lst)-1]
return('List is empty')
# Test program
s = "tracecars"
print(str(Solution().longestPalindrome(s)))
# racecar
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T15:59:39.890",
"Id": "488139",
"Score": "0",
"body": "@superbrain What may be \"obviously wrong\" for you might not be for OP. The point you give is good, but we're trying to convey our messages with a nicer tone :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T20:47:47.170",
"Id": "488164",
"Score": "0",
"body": "@IEatBagels Alright alright... though I do find it hard to believe that they passed the site's test suite with that."
}
] |
[
{
"body": "<pre><code>def checkPalindrome(self,lst):\n return lst[:] == lst[::-1]\n</code></pre>\n<p>This is an extremely expensive implementation. <code>lst[:]</code> is needlessly creating a copy of <code>lst</code>, then <code>lst[::-1]</code> creates a <em>second</em> complete copy of <code>lst</code> (but reversed). There are many ways of approaching this, but I would go for something like this:</p>\n<pre><code>def checkPalindrome(self, lst):\n return all(start == end\n for start, end in zip(lst, reversed(lst)))\n</code></pre>\n<p>It <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a>s <code>lst</code> with a <a href=\"https://docs.python.org/3/library/functions.html#reversed\" rel=\"nofollow noreferrer\"><code>reversed</code></a> list iterator:</p>\n<pre><code>>>> lst = "abcd"\n>>> list(zip(lst, reversed(lst)))\n[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]\n</code></pre>\n<p>Then checks to see if <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> the pairs are equal. If they are, the list is a palindrome. This method is still inefficient though since only half of each needs to be checked. It can be further improved by introducing <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a> to get a "view" of the first half of the zipped lists:</p>\n<pre><code>from itertools import islice\n\ndef checkPalindrome(self, lst):\n half_pair_view = islice(zip(lst, reversed(lst)), len(lst) // 2 + 1)\n return all(start == end for start, end in half_pair_view)\n</code></pre>\n<p><code>islice</code> is like normal list slicing except instead of creating a copy, it just allows you to iterate over a limited portion of the original iterable.</p>\n<p>This code is more efficient because every function involved here is "lazy": they do only as much work as they need to. <code>reversed</code>, <code>zip</code>, <code>islice</code>, and the generator expression all return an iterator that can produce elements (but do little work up front). <code>all</code> also exits as soon as it gets a Falsey result, so it's comparable to a <code>for</code> loop that contains a <code>break</code> in some branches. This is key here because we only want to do as much work as is necessary to determine whether not they're palindromes. Making two full copies of the list does a large amount of work; far more than is required to check if the string is a palindrome.</p>\n<hr />\n<p><code>checkOddChars</code> is a textbook use-case for a list comprehension:</p>\n<pre><code>def checkOddChars(self, lst):\n return [i for i in lst if lst.count(i) == 1]\n</code></pre>\n<p>If you ever find yourself initializing an empty list, then iterating over another iterable and adding to the list, you likely want a comprehension.</p>\n<p>This is quite an expensive function too. <code>count</code> needs to iterate the entire list each time; once for every element in <code>lst</code>. This also double counts any repeated elements. I'm not sure off the top of my head what a better solution is though.</p>\n<hr />\n<pre><code> del lst[0]\n</code></pre>\n<p>This is also <em>quite</em> expensive. Ideally, you shouldn't delete from a list except for at the very end. Lists don't support efficient deletes, and the closer to the beginning of the list you delete from, the worse it is. I'd switch to using a <a href=\"https://docs.python.org/3.8/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>dequeue</code></a> instead of a list, which avoids the overhead of popping from the beginning.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:42:08.447",
"Id": "488051",
"Score": "0",
"body": "You appear to be a bot :-). Suggesting mechanical improvements but not realizing that their solution is wrong, not even that `== 1` doesn't check oddness..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:43:35.027",
"Id": "488052",
"Score": "1",
"body": "@superbrain I admit, I didn't check correctness. For most reviews I do, I simply scan over the code and when something jumps out at me, I make note of it. If I need to dig into functionality to suggest an improvement, I do to the extent that's necessary. So yes, I did do this review as a context-less bot would."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:45:21.710",
"Id": "488054",
"Score": "0",
"body": "By \"odd chars\" though, I figured that was just weird phrasing, and that a character is considered to be \"odd\" (not in the numerical sense) if it's only in the string once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:45:59.623",
"Id": "488055",
"Score": "0",
"body": "Btw, I'd mention that `all` stops early if it can. That's rather crucial. If it didn't, then I'm pretty confident that `lst == lst[::-1]` would be faster. Especially if they did it with a string instead of a list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:48:11.657",
"Id": "488056",
"Score": "0",
"body": "Ah, ok. That kind of oddness. If that were the case, `if lst[0] not in lst[1:]:` might be good. Or `if lst.count(lst[0]) == 1:`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T17:59:05.710",
"Id": "249045",
"ParentId": "249044",
"Score": "8"
}
},
{
"body": "<p><strong>Take full advantage of the language</strong>. You ask whether one should use handy built-in functions and methods during a\ncoding interview. Absolutely! Interviewers want to see, among other things,\nthat you are fluent in the language(s) where you claim fluency. Write natural,\nidiomatic code -- not code you think the interviewer wants to see. There can be\nsome pretty big differences of opinion about what constitutes "good" code\nacross different teams and even among interviewers on the same team. Unless\nthey give you specific instructions, write good code as you understand it. And\nif a team really wants to see Python that looks like Java, perhaps it's not a\ngood fit for you anyway.</p>\n<p><strong>No pointless classes</strong>. Speaking of which, what is the purpose of <code>Solution</code>? Until the problem calls\nfor a class, don't force one. Just write a ordinary functions. Interviewers can\nalways ask follow-up questions if they want to see you build a class. Again,\nwrite natural, readable code to the best of your ability.</p>\n<p><strong>Never optimize blindly</strong>. You also ask whether there is "any way to optimize the code more".\nWhen I interview\nprogrammers, one of the key things I want to learn is whether they have\n<strong>common sense</strong>. Other than for educational purposes, there's very little to\nbe gained from optimization in the abstract. A person can spend a lot of time\nand energy optimizing for irrelevant things if they don't appreciate the larger\ncontext. Optimization for what -- memory, speed, maintainability? During an\ninterview, never engage optimization discussions without asking clarifying\nquestions: what are the primary goals of the code, how big will the inputs be,\nhow fast does it need to be to keep users happy, and so forth.</p>\n<p><strong>Optimize for correctness first</strong>. Your current\nimplementation hangs on many input strings (for example, <code>aabb</code>).\nThe problem is that the algorithm has no way to advance when the both the first and last\ncharacters in the surviving <code>lst</code> are not singletons. One way or another, <code>lst</code>\nmust change on each iteration under your current design. That suggests that the\nconditional checks at the end of the <code>while</code> loop take an <code>if-elif-else</code> form.\nBut it's not obvious what to put in the <code>else</code> block. Naively throwing away the\nfirst character or the last character will fail (consider inputs like <code>aaabb</code>\nand <code>aabbb</code>). Perhaps someone smarter than I can repair your current design,\nbut I'm not hopeful.</p>\n<p><strong>Develop a habit for testing</strong>. You spent a fair bit of effort on your code,\nbut your question lacks evidence of testing. When I'm interviewing someone or\ndeveloping a new piece of code, I want an easy way to test it out. When working\non my computer, I'll use a legitimate testing tool (usually <a href=\"https://docs.pytest.org/en/latest/\" rel=\"nofollow noreferrer\">pytest</a>), but when\nposting an example or question for others, I will often roll the tests into a\nrunnable demo of some kind. For example:</p>\n<pre><code>def main():\n TESTS = {\n 'abba': 'abba',\n '': None, # Free thinkers say it should be ''\n 'x': 'x',\n 'banana': 'anana',\n 'tracecars': 'racecar',\n 'aabbb': 'bbb',\n 'aaabb': 'aaa',\n }\n for word, expected in TESTS.items():\n got = longest_palindrome(word)\n print(got == expected, got, expected)\n</code></pre>\n<p><strong>Classic solutions</strong>:</p>\n<ul>\n<li>Brute force with 3 nested loops: <code>O(n^3)</code>.</li>\n<li>Dynamic programming using a grid of partial solutions: <code>O(n^2)</code>.</li>\n<li><a href=\"https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-1/\" rel=\"nofollow noreferrer\">Manacher's Algorithm</a>, which is both clever and a head scratcher: <code>O(n)</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T20:11:48.587",
"Id": "488058",
"Score": "1",
"body": "I'll just note that the `Solution` class is pointless, but it's a requirement for a challenge website (leetcode I believe)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T20:48:26.160",
"Id": "488062",
"Score": "0",
"body": "Oh no you didn't! Wanted to upvote but then saw you deny the empty string's palindromeness (palindromicness? palindromicity? :-)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T21:06:41.613",
"Id": "488063",
"Score": "3",
"body": "@superbrain I wondered about that. Is there a World Palindrome Association that rules on such matters? I mean, I taught my child to starting counting from zero, so I'm sympathetic to your cause."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T21:19:49.263",
"Id": "488064",
"Score": "1",
"body": "I actually googled that, didn't find one :-). But it's definitely a palindrome. I'm more certain about that than I am about it not being a cube, and I'm in the World Cube Association."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T18:26:42.423",
"Id": "488158",
"Score": "0",
"body": "Thanks this helps a lot , I tried adding another function to consider for the inputs that it hangs on but it was getting very lengthy and difficult. I'm Just going to do using the classic solutions u mentioned"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T20:10:03.960",
"Id": "249055",
"ParentId": "249044",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "249055",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T17:16:22.553",
"Id": "249044",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"interview-questions"
],
"Title": "Find longest Palindromic substring"
}
|
249044
|
<p>For my first Raku program, I thought it might be a fun challange to port over a program I'd written in C# about two years ago, and I was right: it was.</p>
<p>There's just one problem: while the C# program runs in 5 seconds, the Raku program takes nearly 5 <em>minutes</em>. I think the Raku program is doing more or less the same as the C# code, and so it should be equally fast (or equally slow, depending on how you look at it).</p>
<p>Here's my code:</p>
<pre><code>use v6;
class Point {
has Num $.x;
has Num $.y;
method is-inside-unit-circle(--> Bool) {
$!x²+$!y² <= 1;
}
}
sub random-points(Int $count --> Seq) {
gather for 0..^$count {
take Point.new(x => 1.rand.Num, y => 1.rand.Num);
}
}
sub compute-pi(Int $batch --> Seq) {
my Num $total = 0e0;
my Num $count = 0e0;
gather for 0..^∞ {
my Seq $pointsInside = random-points($batch).grep: *.is-inside-unit-circle;
$total += $batch;
$count += $pointsInside.elems;
my Num $ratio = $count / $total;
take $ratio * 4;
}
}
{ say "π ≈ $_" } for compute-pi(100_000).head(500);
</code></pre>
<p>And here's part of the output:</p>
<pre><code>% time raku estimation.raku
π ≈ 3.12912
π ≈ 3.12874
π ≈ 3.1326533333333333
…
π ≈ 3.1419357429718877
π ≈ 3.1419323446893785
π ≈ 3.14193696
raku estimation.raku 272,98s user 1,78s system 100% cpu 4:34,76 total
</code></pre>
<p>My two questions are:</p>
<ol>
<li>How can I make it faster?</li>
<li>Is my code idiomatic, and how could I make it more idiomatic?</li>
</ol>
<hr />
<p>For completeness' sake, here's the C# code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
internal readonly struct Point
{
private readonly double _x;
private readonly double _y;
internal Point(double x, double y)
{
_x = x;
_y = y;
}
internal bool IsInsideUnitCircle()
{
return Math.Pow(_x, 2) + Math.Pow(_y, 2) <= 1;
}
}
internal class PointGenerator
{
private readonly Random _random;
public PointGenerator() => _random = new Random();
public IEnumerable<Point> GeneratePoints(int count)
{
for (var i = 0; i < count; i++)
{
yield return new Point(_random.NextDouble(), _random.NextDouble());
}
}
}
private static IEnumerable<double> ComputePi(int batch)
{
var pointGenerator = new PointGenerator();
var total = 0.0;
var count = 0.0;
while (true)
{
var pointsInside = pointGenerator.GeneratePoints(batch)
.Where(point => point.IsInsideUnitCircle());
total += batch;
count += pointsInside.Count();
var ratio = count / total;
yield return ratio * 4;
}
}
private static void Main()
{
foreach (var estimate in ComputePi(100_000).Take(500))
{
Console.WriteLine($"π ≈ {estimate}");
}
}
}
</code></pre>
<p>And part of its output:</p>
<pre><code>% time dotnet run -c Release
π ≈ 3,13948
π ≈ 3,13904
π ≈ 3,138786666666667
…
π ≈ 3,1415373493975904
π ≈ 3,14154501002004
π ≈ 3,14155416
dotnet run -c Release 5,43s user 0,30s system 103% cpu 5,555 total
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:45:08.263",
"Id": "488053",
"Score": "5",
"body": "This comment will be about raw Rakudo 2020.07 performance vs C# for \"Bob's Struct Bench Press\". Raku was something like 20x - 30x slower. A couple months ago myself and a friend (\"bobthecimmerian\"; I don't know if they've got an SE account) explored a very vaguely similar (C# vs Raku) coding comparison (as a tangent in a perl fora). It's hard to say what parts if any of it you would find valuable but here's a link to [part way in](https://www.reddit.com/r/perl/comments/hf3jlx/announcing_perl_7/fwurfae). Back up or skip forward for more than a boatload of context, further details, and tangents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:40:27.397",
"Id": "488236",
"Score": "2",
"body": "I know nothing of Raku so can't address your main concerns. In regards to the C# code, your version runs in 4.1 seconds on my PC, but I have a modified version based on yours that runs in less than 1.3 seconds. I hesitate to post as an answer since that was not your stated area of interest."
}
] |
[
{
"body": "<p>You can speed it up as follows</p>\n<pre><code>use v6;\n\nclass Point {\n has Num $.x;\n has Num $.y;\n\n method is-inside-unit-circle(--> Bool) {\n $.x²+$.y² <= 1;\n }\n}\n\nsub random-points(Int $count --> RaceSeq) {\n [^$count].race.map({ Point.new(x => 1.rand, y => 1.rand) });\n}\n\nsub compute-pi(Int $batch --> Seq) {\n my Num $total = 0e0;\n my Num $count = 0e0;\n\n gather while True {\n my RaceSeq $pointsInside = random-points($batch).race.grep: *.is-inside-unit-circle;\n\n $total += $batch;\n $count += $pointsInside.elems;\n my Num $ratio = $count / $total;\n\n take $ratio * 4;\n }\n}\n\nsay "π ≈ $_" for compute-pi(100_000).head(500);\n</code></pre>\n<p>Output:</p>\n<pre><code>real 2m53,695s\nuser 9m16,476s\nsys 0m6,780s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T11:28:12.970",
"Id": "488311",
"Score": "4",
"body": "Welcome to the Code Review site. Good answer might not contain any code at all, but must contain one or more meaningful observations about the code. Code only alternate solutions are that might be good answers on stackoverflow.com are considered poor answers on Code Review and may get down voted or deleted by the community. Please try to explain what makes your code better (faster) than the original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T07:39:11.397",
"Id": "249148",
"ParentId": "249048",
"Score": "-1"
}
},
{
"body": "<p>Though the main question is how to have <code>Raku</code> perform faster, I am going to address performance with the <code>C#</code> code. <strong>Do not mark this an the accepted answer</strong> <em><strong>unless</strong></em> you can apply similar changes to your <code>Raku</code> code.</p>\n<p>You added the <code>C#</code> code for completeness. I will not offer a CR of syntax or style but will address performance. On my particular PC, your code runs in 4 seconds but with the changes below it runs consistently less than 1.3 seconds.</p>\n<p><strong>Use simple squaring instead of Math.Pow</strong></p>\n<pre><code>internal bool IsInsideUnitCircle() => (_x * _x) + (_y * _y) <= 1;\n</code></pre>\n<p><strong>PointGenerator <em>could</em> be a static class</strong></p>\n<p>You are calling this 500 times, which means <code>_random</code> is created 500 times. Creating a <code>new Random()</code> is not a super fast operation. If you intentionally wanted a new random every 200_000 times (that is 100_000 iterations calling NextDouble() twice per <code>Point</code>). If you think you can live with seeding <code>_random</code> only once, you can make this class and its methods & properties static too.</p>\n<p><strong>Some LINQ is sluggish</strong></p>\n<p>In the <code>ComputerPi</code> method, I will avoid 2 LINQ calls: <code>Where()</code> and <code>Count()</code>. In my example, I am using a static <code>PointGenerator</code> class. You can change this to non-static as you originally had.</p>\n<pre><code>private static IEnumerable<double> ComputePi(int count)\n{\n int total = 0; // not a double like the original post\n int inside = 0; \n while (true)\n {\n foreach (var point in PointGenerator.GeneratePoints(count))\n {\n // Avoid using the LINQ Where() and Count() methods\n if (point.IsInsideUnitCircle())\n {\n inside++;\n }\n }\n\n total += count;\n yield return 4.0 * (double)inside / (double)total;\n }\n}\n</code></pre>\n<p><strong>Do you want to time your entire app or just the computing PI part?</strong></p>\n<p>You are currently measuring how long your entire application runs. If you wanted to measure just the part where PI is being estimated, you could alter <code>Main</code>:</p>\n<pre><code>// I will only time how long it takes to estimate PI, not how long it takes to write results to the console.\nvar sw = Stopwatch.StartNew();\nvar estimates = ComputePi(100_000).Take(500).ToList();\nsw.Stop();\n\nfor (var i = 0; i < estimates.Count; i++)\n{\n Console.WriteLine($"trial = {i}, π ≈ {estimates[i]}, delta = {(Math.PI - estimates[i])}");\n}\n\nConsole.WriteLine($"Elapsed time: {sw.Elapsed}");\n</code></pre>\n<p>Note I display a little something extra to the console window. This does have a blocking issue in that ALL calculations will have to completely run BEFORE you see anything at the console. This could impart a false sense that the application is frozen.</p>\n<p>Again, altering <code>Main</code> is purely optional but it did shave 0.1+ seconds off my timings (relative to my PC). You could try this a few times on your PC to measure the difference, and then return to your original <code>Main</code> so that you have the benefit of scrolling messages as they occur.</p>\n<p><strong>Little things add up</strong></p>\n<p>These are all little things but LOTS of little things done wrong can add up to slower performance just like LOTS of little things done right can add to performance savings. In my case, I was able to run your Monte Carlo simulation in 1/3 the time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:18:30.587",
"Id": "488331",
"Score": "3",
"body": "Now the run time is down to 1.5 seconds (according to `Stopwatch`). Amazing!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:22:12.740",
"Id": "249155",
"ParentId": "249048",
"Score": "3"
}
},
{
"body": "\n<p>You <code>random-points</code> sub has a few things which can be removed or simplified.</p>\n<ul>\n<li><code>1.rand</code> returns a <code>Num</code>, so there is no reason to call the method <code>.Num</code> on its result.</li>\n<li>Rather than <code>gather for take</code> you can use the <code>xx</code> operator.</li>\n<li>You only want a positive number for the count, so declare that with <code>UInt</code></li>\n</ul>\n\n<pre class=\"lang-raku prettyprint-override\"><code>sub random-points(UInt $count --> Seq) {\n Point.new(x => 1.rand, y => 1.rand) xx $count\n}\n</code></pre>\n<p><code>xx</code> seems to be on the order of 10× faster than <code>gather for take</code>.<br />\nThe reason is mostly that <code>take</code> works by throwing a <code>CONTROL</code> and <code>gather</code> captures that message.<br />\nOn my computer that change alone takes it from nearly 9 minutes (8m49.881s) to around 2 and a half minutes (2m27.582s). (The other changes have no meaningful effect on the run time.)</p>\n<p>The sweet spot for the <code>gather take</code> feature is where there isn't already a built-in for what you are doing, and the speed doesn't matter as much as the ease of writing it.</p>\n<p>You could go to the work of creating your own <code>Iterator</code> class which could speed it up. That is why <code>xx</code> is so much faster, there is already an <code>Iterator</code> class that was created specifically for it.</p>\n<p>(Note that I did actually test to see if writing a new <code>Iterator</code> class would help. It didn't help, in fact it was slower.)</p>\n<hr />\n<p>There are similar issues in <code>compute-pi</code>.</p>\n<p>To start off, there are improvements to be made to <code>gather for 0..^∞</code>.</p>\n<ol>\n<li>Don't mix <code>Int</code> and <code>Num</code> endpoints for <code>Range</code> objects if you can help it. <code>0e0..∞</code></li>\n<li>Don't use <code>for</code> for infinite loops, just use <code>loop</code></li>\n</ol>\n\n<pre class=\"lang-raku prettyprint-override\"><code>gather loop {\n\n ...\n\n take $ratio * 4;\n}\n</code></pre>\n<p>I would not store the filtered <code>random-points</code> <code>Seq</code> in a variable, because the only thing you need from it is the count.</p>\n<pre class=\"lang-raku prettyprint-override\"><code>my Int $points-inside = +random-points($batch).grep: *.is-inside-unit-circle;\n</code></pre>\n<p>The prefix <code>+</code> operator just coerces to a <code>Numeric</code> value. Obviously the only number that makes sense for a <code>Seq</code> is the same as <code>.elems</code>, the count of elements.<br />\n<code>.elems</code> could potentially return a <code>Num</code>, specifically <code>Inf</code>. Considering that would break the rest of the code anyway, I think it's fine to store it in an <code>Int</code> scalar.</p>\n<hr />\n<p>Ok now that we are done with the more obvious cleanups we can try to make it faster.</p>\n<p>Thankfully changing from <code>gather for take</code> in <code>random-points</code> to <code>xx</code> helped a lot. (No other change had any meaningful change on the amount of time taken.)</p>\n<p>The first thing I did at this point was to run the profiler</p>\n<pre class=\"lang-none prettyprint-override\"><code>raku --profile test.raku\n</code></pre>\n<p>There were no obvious slow parts of our code. In fact a good ⅔ of the run time was in the Raku runtime, not our code.</p>\n<p>So let's add parallelism to see if we can reduce the time by using more CPU cores.</p>\n<p>We could just make the sequence returned from <code>random-points</code> a <code>race</code> sequence to see if it helps.</p>\n<pre class=\"lang-raku prettyprint-override\"><code>my Int $pointsInside = +random-points($batch).race.grep(*.is-inside-unit-circle);\n</code></pre>\n<p>After that change it now takes 4 minutes, almost twice the time it took from before that change.<br />\nI did mess around with the <code>batch</code> and <code>degree</code> arguments to <code>race</code>, but no combination seemed to improve it meaningfully. At best I made it match the original timing.</p>\n<p>So now we know that was a dead-end. <code>random-points.grep</code> was already about as fast as possible.</p>\n<hr />\n<p>So let's add the asynchrony to <code>compute-pi</code> instead.</p>\n<p>One obvious thing we could do is have a bunch of threads creating the sequences of <code>random-points.grep</code>.</p>\n<p>Of course we don't know how many we need to create. So let's give that as an argument.</p>\n<pre class=\"lang-raku prettyprint-override\"><code>sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {\n</code></pre>\n<p>Now we want to have an existing sequence that we can call <code>race</code> on.</p>\n<pre class=\"lang-raku prettyprint-override\"><code>my \\batches = ^$batch-count;\n</code></pre>\n<p>Add <code>race</code> to it.<br />\n(We don't care about the order of <code>random-points.grep</code> values we get.)</p>\n<pre class=\"lang-raku prettyprint-override\"><code>my \\batches = (^$batch-count).race(batch => 1);\n</code></pre>\n<p>The reason for the <code>batch</code> argument of <code>1</code> is that we know each <code>random-points.grep</code> takes a long time, so we don't want it to batch them together. We also don't want to wait for 64 of them to be calculated before we get any results.</p>\n<p>Now to turn that into the sequence of values that we want by using <code>map</code>.</p>\n<pre class=\"lang-raku prettyprint-override\"><code>my \\batches = (^$batch-count).race(batch => 1).map: {\n +random-points($batch-size).grep(*.is-inside-unit-circle)\n}\n</code></pre>\n<p>Rather than have an infinite loop, we will loop over those batches</p>\n<pre class=\"lang-raku prettyprint-override\"><code>gather for batches -> Int $pointsInside {\n</code></pre>\n<p>So the last part of the file now looks like this:</p>\n<pre class=\"lang-raku prettyprint-override\"><code>sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {\n\n my \\batches = (^$batch-count).race(batch => 1).map: {\n +random-points($batch-size).grep(*.is-inside-unit-circle)\n }\n\n my Num $total = 0e0;\n my Num $count = 0e0;\n\n gather for batches -> Int $pointsInside {\n\n $total += $batch;\n $count += $pointsInside;\n my Num $ratio = $count / $total;\n\n take $ratio * 4;\n }\n}\n\n{ say "π ≈ $_" } for compute-pi(100_000, 500);\n</code></pre>\n<p>It now takes just over a minute (1m13.905s) with a cpu time of over 5 minutes (5m19.237s).<br />\nWhich means we have more than 400% utilization. Which is fairly good on a 4 core CPU, with hyperthreading.</p>\n<hr />\n<p>We can gain a bit more if we use native <code>num</code> variables instead of boxed <code>Num</code> variables.</p>\n<p>You have to be careful with this as you can actually make it take more time if the value ends up needing to be boxed for an operation.</p>\n<pre class=\"lang-raku prettyprint-override\"><code>class Point {\n has num $.x;\n has num $.y;\n ...\n}\n\n...\n\nsub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {\n\n my \\batches = (^$batch-count).race(batch => 1).map: {\n random-points($batch-size).grep(*.is-inside-unit-circle).Num\n }\n\n my num $total = 0e0;\n my num $count = 0e0;\n\n gather for batches -> num $pointsInside {\n\n $total += $batch;\n $count += $pointsInside;\n my num $ratio = $count / $total;\n\n take $ratio * 4;\n }\n}\n</code></pre>\n<p>That final change brings it down to about 42 seconds (0m42.771s) with 4 minutes of CPU time (4m0.929s).<br />\nWhich also seems to increase the CPU utilization up over 500%.</p>\n<hr />\n<p>The biggest improvement was going from <code>gather for take</code> to just <code>xx</code>. Which I'd argue was warranted just for how much it improved the clarity of the code. The other changes were of minimal benefit.</p>\n<p>I think to get any significant improvement would require improving the compiler, runtime, or the VM.</p>\n<p>Really what we ended up with is fairly fast considering how much of higher level language Raku is than C#, and how few people are working on it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T20:04:14.867",
"Id": "249240",
"ParentId": "249048",
"Score": "7"
}
},
{
"body": "<p>My original run time with your sample code is a consistent 5 minutes, 10 seconds.</p>\n<p>You seem to have stumbled across a performance regression or something with exponentiation, because if I change <code>$!x²+$!y² <= 1</code> to <code>(($!x * $!x) + ($!y * $!y)) <= 1</code> it cuts 40 seconds off down to 4 minutes, 30 seconds. I'll see about filing an issue over that.</p>\n<p>Your function compute-pi creates a Seq, and inside it calls random-points to make a Seq. So your ending\n<code>compute-pi(100_000).head(500)</code> will run the 'gather' construct inside random-points 500 times, generating a Seq 100_000 units long each time.</p>\n<p>If instead you just have it return a number representing the number of randomly generated points that fit into a circle, on my machine that cuts execution time from just over 4 minutes, 30 seconds to 1 minute, 40 seconds:</p>\n<pre><code>sub inside-points(Int $count --> Num) {\n my Num $tot = 0e0;\n for 0..^$count {\n if Point.new(x => 1e0.rand, y => 1e0.rand).is-inside-unit-circle() {\n $tot++;\n }\n } \n $tot;\n}\n# and then further down, inside compute-pi:\nmy Num $pointsInside = inside-points($batch);\n$total += $batch;\n$count += $pointsInside;\n</code></pre>\n<p>The next swap to make for performance is to swap out Raku's "Num" - similar to Double in Java or C# - for num64, which is a native 'double' in C# or Java. You can just do a find/replace on the code and switch Num to num64. That cuts the execution time for me from 100 seconds to 50. I'm not going to post that change here.</p>\n<p>The final change is to eliminate object creation. You can remove the Point type entirely, and change the function random-points to:</p>\n<pre><code>sub inside-points(Int $count --> num64) {\n my num64 $tot = 0e0;\n my num64 $x; \n my num64 $y; \n for 0..^$count {\n $x = 1e0.rand;\n $y = 1e0.rand;\n # again, avoid the performance hit of $x²+$y²\n if (($x * $x) + ($y * $y)) <= 1e0 {\n $tot++;\n }\n }\n $tot;\n}\n</code></pre>\n<p>That cuts the execution time to 6 seconds on my machine.</p>\n<p>If performance is an issue, you can write Raku code in this kind of imperative style and it seems to work pretty well. But that said, I like your original implementation better. Your use of a Point type and sequences makes the intent easier to follow than in mine.</p>\n<p>Edit: bonus round, I decided to try to see if I could speed it further by using concurrency. This version runs in about 4 seconds on my machine. Uncommenting the lines with the <code>$totalcalcs</code> variable will use it to prove that the program is still running properly, meaning it doesn't skip any loops.</p>\n<p>I use asynchronous promises to breakup the calculation of random values into batches. I tried different batch sizes and 8_000 seems to give the best result.</p>\n<pre><code># my atomicint $totalcalcs = 0;\nsub inside-points-wrapped(Int $count --> num64) {\n my num64 $tot = 0e0;\n my num64 $x;\n my num64 $y; \n for 0..^$count {\n $x = 1e0.rand;\n $y = 1e0.rand;\n if (($x * $x) + ($y * $y)) <= 1e0 {\n $tot++;\n }\n # $totalcalcs⚛++;\n }\n $tot;\n}\n\nmy \\batch_size = 8_000;\nsub inside-points(int $count --> num64) {\n my $loops = $count div batch_size;\n my $rem = $count mod batch_size;\n my @inner_batches = batch_size xx $loops;\n @inner_batches.push($rem);\n my Promise @promises;\n for @inner_batches -> $batch {\n @promises.push(start { inside-points-wrapped($batch); });\n }\n my @result = await @promises; \n [+] @result;\n}\n\nsub compute-pi(Int $batch --> Seq) {\n my num64 $total = 0e0;\n my num64 $count = 0e0;\n\n gather for 0..^∞ {\n my num64 $pointsInside = inside-points($batch);\n $total += $batch;\n $count += $pointsInside;\n my num64 $ratio = $count / $total;\n take $ratio * 4e0;\n }\n}\n{ say "π ≈ $_" } for compute-pi(100_000).head(500);\n# say $totalcalcs;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T17:37:58.370",
"Id": "249281",
"ParentId": "249048",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:39:00.747",
"Id": "249048",
"Score": "4",
"Tags": [
"raku"
],
"Title": "How can I make my program that calculates π faster?"
}
|
249048
|
<p>This is web exercise 3.1.41. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>The <a href="https://en.wikipedia.org/wiki/Scytale" rel="nofollow noreferrer">scytale cipher</a> is one of the first cryptographic devices used for
military purposes. (See <a href="https://rads.stackoverflow.com/amzn/click/com/0385495323" rel="nofollow noreferrer" rel="nofollow noreferrer">The Code Book</a>.) It
was used by the Spartans in the fifth century BCE. To scramble the
text, you print out every kth character starting at the beginning,
then every kth character starting at the second character, and so
forth. Write a program implements this encryption scheme.</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>public class ScytaleCipher
{
public static String encrypt(String text, int kth)
{
int textLength = text.length();
String encrypted = "";
for (int i = 0; i < kth; i++)
{
for (int j = 0; i+j < textLength; j += kth)
{
encrypted += String.valueOf(text.charAt(i+j));
}
}
return encrypted;
}
public static String decrypt(String text, int kth)
{
return encrypt(text, kth-1);
}
public static void main(String[] args)
{
int kth = Integer.parseInt(args[0]);
String message = "";
while (!StdIn.isEmpty())
{
String word = StdIn.readString();
message += word;
}
// to encrypt
System.out.println(encrypt(message, kth));
// to decrypt
//System.out.println(decrypt(message, kth));
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdIn.html" rel="nofollow noreferrer">StdIn</a> is a simple API written by the authors of the book. I checked my program and it works.</p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Use <code>java.lang.StringBuilder</code> to concatenate String in a loop.</h2>\n<p>It's generally more efficient to use the builder in a loop, since the compiler is unable to optimize it by itself while translating your code into bytecode; The compiler will not use the <code>java.lang.StringBuilder</code> in complex loops and your method will take more time and more memory to execute, since the String Object is immutable (a new instance will be created each iteration).</p>\n<pre class=\"lang-java prettyprint-override\"><code>StringBuilder encrypted = new StringBuilder();\nfor (int i = 0; i < kth; i++) {\n for (int j = 0; i + j < textLength; j += kth) {\n encrypted.append(text.charAt(i + j));\n }\n}\nreturn encrypted.toString();\n</code></pre>\n<h2>When concatenating a primitive into a string, you don’t need to convert it.</h2>\n<p>You can add the primitive (int, double, float, char, ect) directly into the string by using the <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html\" rel=\"nofollow noreferrer\">assignment operators</a> (+, +=).</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>encrypted += String.valueOf(text.charAt(i+j));\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>encrypted += text.charAt(i+j);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T21:35:38.367",
"Id": "249056",
"ParentId": "249051",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:27:44.160",
"Id": "249051",
"Score": "3",
"Tags": [
"java",
"beginner"
],
"Title": "Implementation of Scytale cipher (encryption and decryption)"
}
|
249051
|
<p>This is web exercise 3.1.45. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a program that reads in a list of words from the command line
and prints <code>true</code> if they form a word chain and <code>false</code> otherwise. In a
word chain, adjacent words must differ in exactly one letter, e.g.,
HEAL, HEAD, DEAD, DEED, DEER, BEER.</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>public class WordChainChecker
{
public static boolean checkWordCouple(String word1, String word2)
{
int counter = 0;
int wordLength = word1.length();
for (int i = 0; i < wordLength; i++)
{
if (word1.charAt(i) != word2.charAt(i)) counter++;
}
if (counter > 1) return false;
else return true;
}
public static void main(String[] args)
{
String word1 = StdIn.readString();
String word2 = StdIn.readString();
boolean truth = true && checkWordCouple(word1,word2);
while (!StdIn.isEmpty())
{
word1 = StdIn.readString();
truth = truth && checkWordCouple(word1,word2);
word2 = word1;
}
System.out.println(truth);
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdIn.html" rel="noreferrer">StdIn</a> is a simple API written by the authors of the book. I checked my program and it works.</p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Simplify the boolean conditions.</h2>\n<p>Generally, when you are returning both <code>true</code> and <code>false</code> surrounded by a condition, you know you can refactor the logic of the expression.</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (counter > 1) return false;\nelse return true;\n</code></pre>\n<p>can be changed into</p>\n<pre class=\"lang-java prettyprint-override\"><code>return counter <= 1;\n</code></pre>\n<p>By changing the range, we can make the condition shorter.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>boolean truth = true && checkWordCouple(word1,word2);\n</code></pre>\n<p>can be changed into</p>\n<pre class=\"lang-java prettyprint-override\"><code>boolean truth = checkWordCouple(word1,word2);\n</code></pre>\n<p>The <code>and</code> operator is useless (<code>true && false == false</code> and <code>true && true == true</code>) and is equivalent to a single boolean given by the <code>checkWordCouple</code> method.</p>\n<h2>Use the simplified operator when possible.</h2>\n<p><strong>EDIT: As stated in the comments of this answer, the use of the Bitwise AND assignment operator is not recommended in this case.</strong></p>\n<blockquote>\n<p>Java gives you plenty of\n<a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html\" rel=\"nofollow noreferrer\">operators</a>\nto do multiple operations.</p>\n<p>In your case, you can use the <code>Bitwise AND assignment operator</code> (<code>&=</code>)\ninstead of reassigning the boolean each time with the result of <code>ruth && checkWordCouple(word1,word2)</code>. <code>java truth = truth && checkWordCouple(word1,word2); </code></p>\n<p>into</p>\n<p><code>java truth &= checkWordCouple(word1,word2); </code></p>\n<p>This operator will assign itself the result of the <code>previous value && current</code>.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:39:08.723",
"Id": "488111",
"Score": "1",
"body": "I agree with \"simplifying the boolean conditions\", but replacing the **logical** *and* `&&` with the **bitwise** *and* assignment `&=` sounds like a mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T15:04:53.043",
"Id": "488134",
"Score": "0",
"body": "The bitwise will only be false when the `checkWordCouple` method return false and the value will be kept until the end of the loop (any false value found in the loop, and the final condition will stay false until the end). I don’t think this is a mistake, since both of the results will be similar. `truth = truth && checkWordCouple(word1,word2)` == `truth &= checkWordCouple(word1,word2);` [15.22.2. Boolean Logical Operators](https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.22.2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:39:32.960",
"Id": "488148",
"Score": "2",
"body": "@Stef Both the bitwise-and (`&`) and logical-and (`&&`) can be used with `boolean` values in Java. However, when bitwise-and is used, it does not perform short-circuit evaluation. `false && checkWordCouple(word1, word2)` will never call `checkWordCouple()`, where as `false & checkWordCouple(word1, word)` will always call it, as will `truth &= checkWordCouple(word1, word2);`, so `&&` should be preferred if the call has no side-effects to optimize performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:42:26.393",
"Id": "488149",
"Score": "0",
"body": "Totally forgot about the `short-circuit`, my bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:51:10.133",
"Id": "488150",
"Score": "0",
"body": "Other than playing Code-Golf, using the binary operators with `boolean` values doesn't have much value ... with the exception of xor. There is no logical-xor operator (`^^`), but the binary-xor operator (`^`) does work with `boolean`. There is no short-circuit evaluation possible for xor, so making the single character, non-short-circuiting `^` operator work for `boolean` values, is perhaps the justification for also allowing `&` and `|` to work."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T22:07:59.287",
"Id": "249058",
"ParentId": "249052",
"Score": "6"
}
},
{
"body": "<h1>Requirements</h1>\n<h2>Number of words</h2>\n<p>Are you guaranteed to have at least 2 words? If so, you could simplify your loop, by removing the first read; the loop will take care of the second & subsequent words:</p>\n<pre><code> String word2 = StdIn.readString();\n boolean truth = true;\n while (!StdIn.isEmpty())\n {\n String word1 = StdIn.readString();\n truth = truth && checkWordCouple(word1,word2);\n word2 = word1; \n }\n</code></pre>\n<p>Although now if given a single word, it will produce <code>true</code>. This may be an improvement, but you’d need to check the exact requirements to be sure.</p>\n<h2>Word Length</h2>\n<p>Is <code>HEAD</code>, <code>HEAL</code>, <code>TEA</code>, <code>TO</code> a word chain? Your program says it is!</p>\n<p>What about <code>HEAD</code>, <code>HEAL</code>, <code>HEALTHY</code>? That input causes your program to crash!</p>\n<p>Your program should handle mismatched word length, unless the problem statement guarantees all inputs will be the same length.</p>\n<h2>Number of Differences</h2>\n<p>The problem description says:</p>\n<blockquote>\n<p>In a word chain, adjacent words must differ in <strong>exactly</strong> one letter</p>\n</blockquote>\n<p>but <code>HEAD</code>, <code>HEAD</code>, <code>HEAD</code>, <code>HEAD</code> is reported as "true". Clearly, <code>counter > 1</code> is not the correct "false" condition. Borrowing Doi9t's suggestion, and further improving it, the correct line would read:</p>\n<pre><code>return counter == 1;\n</code></pre>\n<h1>Self Documenting Code</h1>\n<p>You read <code>word1</code>, then <code>word2</code>, and compare the first to the second (let’s call that “forward”), then read a third into <code>word1</code>, and compare the third to the second (comparison in the “reverse” direction). You are testing for one difference, so it works, but what if you were checking for one additional character? By reversing the word order, you’d actually be testing for character removal!</p>\n<p>Instead of <code>word1</code> & <code>word2</code>, maybe <code>previous_word</code> and <code>next_word</code> would help keep things clearer.</p>\n<pre><code> String previous_word = StdIn.readString();\n boolean truth = true;\n while (!StdIn.isEmpty())\n {\n String next_word = StdIn.readString();\n truth = truth && checkWordCouple(previous_word, next_word);\n previous_word = next_word; \n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T09:38:35.763",
"Id": "488098",
"Score": "0",
"body": "I checked my program with \"Head Tea To\" and \"Head Heal Healthy\" and it produces error. Could you please explain more? Do you mean that I should add exception handling to produce meaningful errors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:51:23.620",
"Id": "488124",
"Score": "1",
"body": "Sorry. \"HEAD HEAL TEA TO\" will incorrectly produce \"true\" not crash; forgot the first two words are compared in a different order from the rest. No — I wouldn't add exception handling. But I would add do something differently in `checkWordCouple`. You get the length of `word1`, and then blindly assume `word2` is the same length. Perhaps you could check that? Would it make sense to return `false` if they don't match?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:58:13.053",
"Id": "488127",
"Score": "0",
"body": "I think so, if word1.length() != word2.length() it should return false."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T13:16:35.263",
"Id": "488224",
"Score": "0",
"body": "Great review, one question. Any reason why suggesting to use `previous_word` instead of `previousWord`? Given that OP is already using camel case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T13:30:10.333",
"Id": "488227",
"Score": "0",
"body": "@Marc Certainly: I'm posting from an iPhone, and keeping track of everything in my head while posting is hard. Ok, perhaps not the best of reasons..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T23:22:17.193",
"Id": "249060",
"ParentId": "249052",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "249060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:31:30.833",
"Id": "249052",
"Score": "6",
"Tags": [
"java",
"beginner"
],
"Title": "Implementing a word-chain checker"
}
|
249052
|
<p>I'm in the process of making my first GUI with Python. I'm trying to make something for work, so I've replaced all the info with fruits. It just lets the user tick some boxes, then creates a word doc</p>
<p>It's quite messy, and the variable names will be renamed later. But what I wanted to ask about was the functions I've defined. I wasn't sure whether to define the ship_collect and ship_click function within the FruitClass class, or outside of it.</p>
<p>I figured it made more sense to put it outside, that way the function only gets defined once. Whereas if I defined it inside in the class, it would be defined every time an instance gets created, taking up more memory - is this correct or am I totally wrong here?</p>
<p>Additionally, I thought the functions would have to be defined before the class, since some the widgets defined in the class use them for commands...</p>
<p>If the functions are defined outside the class, would it make more sense to create the widgets (for example .ent_qty) within the functions, or within the class? Again I thought outside made more sense, as it seemed more sensible to define these widgets only if the original checkbox gets ticked.</p>
<pre><code>import tkinter as tk
from tkinter import ttk
from docx import Document
def ship_collect(fruit_object):
'''Function to make additional checkbuttons appear if the first column boxes get ticked.'''
if fruit_object.chkVal.get() == True:
# quantity
fruit_object.lbl_qty = tk.Label(master=fruit_object.frm, text="Quantity: ", bg="red")
fruit_object.ent_qty = tk.Entry(master=fruit_object.frm, width=10, bg="blue")
fruit_object.lbl_qty.grid(row=1, column=0, sticky='e')
fruit_object.ent_qty.grid(row=1, column=1, sticky='w', padx=(0,20))
# shipping/collect
fruit_object.chkVal_ship = tk.BooleanVar()
fruit_object.chkVal_ship.set(False)
fruit_object.chk_ship = tk.Checkbutton(master=fruit_object.frm, text="ship", variable=fruit_object.chkVal_ship, bg="green", command=lambda fruit_object=fruit_object:ship_clicked(fruit_object))
fruit_object.chk_ship.grid(row=0,column=2, sticky='w')
fruit_object.chkVal_collect = tk.BooleanVar()
fruit_object.chkVal_collect.set(False)
fruit_object.chk_collect = tk.Checkbutton(master=fruit_object.frm, text="collect", variable=fruit_object.chkVal_collect, bg="yellow")
fruit_object.chk_collect.grid(row=1,column=2, sticky='w')
else:
fruit_object.chk_ship.grid_forget()
fruit_object.chk_collect.grid_forget()
fruit_object.lbl_qty.grid_forget()
fruit_object.ent_qty.grid_forget()
fruit_object.combo_ship.grid_forget()
def ship_clicked(fruit_object):
''' Create drop-down menus if ship button gets clicked'''
if fruit_object.chkVal_ship.get() == True:
fruit_object.combo_ship = ttk.Combobox(master=fruit_object.frm,
values=[
"Next day - £5",
"Standard - £2"],
state="readonly")
fruit_object.combo_ship.grid(row=0, column=3)
fruit_object.combo_ship.current(0)
class FruitClass:
def __init__(self, fruitname):
self.fruitname = fruitname
self.chkVal = tk.BooleanVar()
self.chkVal.set(False)
self.frm = tk.Frame(master=frm_fruits)
self.chk = tk.Checkbutton(master=self.frm, text=self.fruitname, variable=self.chkVal, command = lambda self=self: ship_collect(self))
self.chk.grid(row=0,column=0, sticky='w')
self.frm.columnconfigure(0, weight=1, minsize=80)
window = tk.Tk()
lbl_fruits = tk.Label(master=window, text="Select fruits:")
lbl_fruits.grid(row=0, sticky="w")
frm_fruits = tk.Frame(master=window)
frm_fruits.grid(row=1, column=0)
# use a list of fruit names to create a dict of objects
objectNames = ('apple','banana','orange','pear','mango')
objectDictionary = {}
for name in objectNames:
objectDictionary[name] = FruitClass(fruitname=name)
# append each fruit frame (containing checkboxes) to the window
for i, k in enumerate(objectDictionary):
objectDictionary[k].frm.grid(row=i, column=0, sticky='w', pady=(0,10))
def onSubmit():
myDoc = Document()
myTable = myDoc.add_table(1,3)
heading_cells = myTable.rows[0].cells
heading_cells[0].text = 'Fruit'
heading_cells[1].text = 'Quantity'
heading_cells[2].text = 'Delivery'
# check which boxes were ticked, add these to the table in word
for name, obj in objectDictionary.items():
if obj.chkVal.get() == True:
cells = myTable.add_row().cells
cells[0].text = name
cells[1].text = str(obj.ent_qty.get())
if obj.chkVal_ship.get() == True:
cells[2].text = obj.combo_ship.get()
myTable.style = 'LightShading-Accent1'
myDoc.save('shopping.docx')
btn_submit = tk.Button(
master=window,
text="Submit",
command=onSubmit
)
btn_submit.grid(row=3, column=3)
window.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T20:16:55.190",
"Id": "488059",
"Score": "1",
"body": "Have you tried to measure the performance difference between defining it inside the class versus outside the class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T14:54:49.730",
"Id": "488133",
"Score": "0",
"body": "No, not entirely sure how to do that, still just a beginner. I just thought there might be a standard for where to define these types of functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T19:10:35.497",
"Id": "488160",
"Score": "0",
"body": "For timing code performance I would recommend this subject: [Python Timer Functions: Three Ways to Monitor Your Code](https://realpython.com/python-timer/). Armed with this knowledge you will be able to easily measure performance of chosen portions of code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T20:03:15.530",
"Id": "249054",
"Score": "4",
"Tags": [
"python",
"tkinter"
],
"Title": "Tkinter - functions inside or outside of class?"
}
|
249054
|
<p>Here is the raw data</p>
<pre><code>anycasestr = "<div style="color: rgb(51, 51, 51); background-color: rgb(253, 246, 227); font-family: Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 12px; line-height: 18px;"><div>refinement</div><div>decent</div><div>elegant</div></div>";
</code></pre>
<p>to extract all the textcontent to an array like ["refinement", "decent", "elegant"]</p>
<p>I wrote this code (jquery has been included)</p>
<pre><code>htmlObject = $(anycasestr);
arr = Array.prototype.slice.call(htmlObject[0].getElementsByTagName("div"));
arr_page = [];
for (i = 0; i < 3; i++) {
arr_page.push(arr[i].textContent);
}
</code></pre>
<p>It produces what I want.</p>
<p>I'm just concerned if it is implemented in an elegant way. Could someone take a look at it?</p>
<p>For example, should I have used xpath or something, in terms of computational concerns?</p>
|
[] |
[
{
"body": "<p><strong>Declare your variables</strong> - whenever you assign to or reference a variable without defining it first, you will either (1) implicitly create a property on the global object (which can result in weird bugs), or (2) throw an error, if you're running in strict mode. You currently aren't defining any of your variables. Fix it by putting <code>const</code> (or, when needed, <code>let</code>) in front of them when assigning to them for the first time, eg <code>const htmlObject = $(anycasestr);</code>.</p>\n<p><strong>jQuery or DOM methods?</strong> You're using jQuery to turn the string into a jQuery collection of elements, but then you're using <code>getElementsByTagName</code> to select children. If you're using jQuery, you can be concise and consistent to use it to select the <code><div></code> children.. To find children of an element which match a particular tag name, call <code>.find</code> on the jQuery collection - then, you can use <code>.map</code> to turn the found jQuery elements into a collection of just the text of the elements:</p>\n<pre><code>const $parent = $(anycasestr);\nconst arr = $parent.find('div')\n .map((_, child) => child.textContent)\n .get(); // turn the jQuery collection of strings into an array of strings\n</code></pre>\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 anycasestr = `<div style=\"color: rgb(51, 51, 51); background-color: rgb(253, 246, 227); font-family: Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 12px; line-height: 18px;\"><div>refinement</div><div>decent</div><div>elegant</div></div>`;\nconst $parent = $(anycasestr);\nconst arr = $parent.find('div')\n .map((_, child) => child.textContent)\n .get(); // turn the jQuery collection of strings into an array of strings\nconsole.log(arr);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Or, you can use DOMParser instead. Using DOMParser rather than jQuery to turn the text into a collection of elements can avoid accidental execution of malicious scripts. Example exploit using jQuery:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const anycasestr = `<img src=\"\" onerror=\"alert('evil')\">`;\nconst $parent = $(anycasestr);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>With DOMParser:</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 anycasestr = `<div style=\"color: rgb(51, 51, 51); background-color: rgb(253, 246, 227); font-family: Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 12px; line-height: 18px;\"><div>refinement</div><div>decent</div><div>elegant</div></div>`;\nconst doc = new DOMParser().parseFromString(anycasestr, 'text/html');\nconst arr = [...doc.querySelectorAll('div > div')]\n .map(div => div.textContent);\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The query string <code>div > div</code> selects <code><div></code> elements which are direct children of another <code><div></code>. It works exactly the same way as CSS selectors. <code>querySelectorAll</code> is a great tool for concise selection of elements - it can be easier to write and understand at a glance than other methods (like your original <code>htmlObject[0].getElementsByTagName("div")</code>).</p>\n<p><code>Array.prototype.slice.call</code> is a bit verbose - on non-ancient environments, you can use spread syntax instead, like I did above. Creating an array all at once by mapping is also somewhat more elegant than declaring an array then <code>.push</code>ing onto it.</p>\n<p>If you had more <code><div></code> children and wanted to take only the text from the first 3 of them, it'd be more functional to <code>.slice</code> the array of elements instead of putting an iteration count in a <code>for</code> loop:</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 anycasestr = `<div style=\"color: rgb(51, 51, 51); background-color: rgb(253, 246, 227); font-family: Menlo, Monaco, &quot;Courier New&quot;, monospace; font-size: 12px; line-height: 18px;\">\n <div>refinement</div>\n <div>decent</div>\n <div>elegant</div>\n <div>don't include me</div>\n <div>don't include me</div>\n <div>don't include me</div>\n</div>`;\nconst doc = new DOMParser().parseFromString(anycasestr, 'text/html');\nconst arr = [...doc.querySelectorAll('div > div')]\n .slice(0, 3)\n .map(div => div.textContent);\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<blockquote>\n<p>in terms of computational concerns?</p>\n</blockquote>\n<p>Unless the stuff that needs to be parsed is <em>unreasonably large</em>, performance for this sort of thing is not a concern; better to write clean, readable, maintainable code. <em>If</em> you later find that something is taking longer to run than is ideal, you can identify the bottleneck and then figure out how to fix it. (But this almost certainly won't be the bottleneck.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:37:57.697",
"Id": "488375",
"Score": "0",
"body": "You can actually use the OP technique of calling prototype functions straight on `NodeList`s (such as those returned by `querySelectorAll`): `const map = fun => iter => Array.prototype.map.call(iter, fun); map(el => el.textContent)(document.querySelectorAll('div > div'))`. I believe all the `iter` needs to have for it to work is a `.length` (so e.g. `String`s should work also)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:39:20.637",
"Id": "488376",
"Score": "0",
"body": "Yes, that's possible too. I personally prefer using spread because it's terser and moderately easier to read."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T01:12:21.367",
"Id": "249062",
"ParentId": "249061",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T00:55:17.227",
"Id": "249061",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "extract all textcontent in htmlcollection to array with javascript"
}
|
249061
|
<p>I am currently going through and implementing basic algorithms and data structures as I feel I didn't learn enough about this during my Data Structures and Algorithms unit. So far I've done the following algorithms, yet to get to data structures.</p>
<h2>Sorting</h2>
<ul>
<li>Bucket</li>
</ul>
<pre><code>import random
#toSort = [round(random.uniform(0.10, 0.99), 2) for _ in range(20)]
toSort = [round(random.uniform(0.10, 0.99), 2) for i in range(10, 0, -1)]
print(toSort)
def bucket_sort(array):
buckets = [[] for i in range(len(array))]
sorted_buckets = []
for index in range(len(array)):
bucket_num = len(array) * array[index]
print(bucket_num)
buckets[int(bucket_num)].append(array[index])
for bucket in buckets:
insertion_sort(bucket)
for bucket in buckets:
if len(bucket) == 0:
continue
elif len(bucket) > 1:
for num in bucket:
sorted_buckets.append(num)
else:
sorted_buckets.append(bucket[0])
return sorted_buckets
def insertion_sort(array):
for unsorted_val in range(1, len(array)):
val = array[unsorted_val]
val_index = unsorted_val
while val_index > 0 and array[val_index - 1] > val:
array[val_index] = array[val_index - 1]
val_index -= 1
array[val_index] = val
toSort = bucket_sort(toSort)
</code></pre>
<ul>
<li>Insertion</li>
<li>Merge</li>
<li>Quick</li>
<li>Selection</li>
</ul>
<h2>Searching</h2>
<ul>
<li>Binary</li>
<li>Linear</li>
</ul>
<h2>Merging</h2>
<ul>
<li>ArrayMerge</li>
</ul>
<p>I was planning to include the code for the rest of the algorithms I've implemented but I have found code reviews for those already so I do not want to double up on the questions.</p>
<p>However, I did want to ask this on the meta page but I didn't have enough reputation to post. If I were to go through and update my code with the suggestions in the other code reviews, would it be okay for me to post here with my implementation and ask for further review?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T07:13:22.677",
"Id": "488086",
"Score": "1",
"body": "Welcome to CodeReview@SE - especially to post *your* implementation of algorithms featured time and again (one per question, if not for comparison). For parts of run time environments, there even is the [tag:reinventing-the-wheel] tag for this. Heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) (First thing to improve would be the title of this question.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T07:19:55.573",
"Id": "488088",
"Score": "0",
"body": "@greybeard Sorry I understood the rest of your question, but mind re-stating this part? \"especially to post your implementation of algorithms featured time and again\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T07:25:19.677",
"Id": "488089",
"Score": "2",
"body": "It is quite alright to ask for a review of *your* implementation, without regard that there are umpteen reviews for different ones of the same algorithm. In my book, (non-trivial) differences in code layout or code comments are enough. (`rest of [my] question` ? I didn't ask anything.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T07:29:15.647",
"Id": "488090",
"Score": "0",
"body": "Cool thank you for that, and yeah haha meant to write \"comment/answer\" instead. So to clarify, etiquette is to ask for a review of one program per question?"
}
] |
[
{
"body": "<p>You have implemented an unusual bucket sort. First, the logic to compute the\nbucket number makes assumptions about the values themselves and will fail on\nmany types of numbers (for example, positive integers). And second, if <code>N</code> is the size\nof the input list, you are creating <code>N</code> buckets. Typically, bucket sort uses a\nnumber of buckets that is smaller than <code>N</code>. A common approach is to make an initial pass\nover the values to find their min and max. Then each bucket will have a\nspan of <code>(MAX - MIN) / K</code>, where <code>K</code> is the number of buckets\n(which might be set either by the caller or by the code based on <code>N</code>).\nFor any <code>x</code> value, I think its bucket index would be\n<code>min(K - 1, int((x - MIN) / SPAN))</code> (you should double check that).</p>\n<p>My other comments relate to code readability and simplicity.</p>\n<p>Use convenience variables to eliminate repeated calculations, such as\n<code>len(array)</code>. If you need it multiple times, create a variable and lighten the\nvisual weight of your code.</p>\n<p>Organize your code into commented "paragraphs" -- one paragraph per\nsmall step in the logic of your algorithm (shown below).</p>\n<p>If you need to iterate over values in a collection, do it directly, not\nindirectly via indexes. Use <code>for x in xs</code> not <code>for i in range(len(xs)</code>. If the\nalgorithm requires both values an indexes, use <code>enumerate()</code>. Only iterate\nover indexes if you don't actually need the values or if the algorithm's\nreadability is simpler that way (for example, in your\n<code>insertion_sort()</code> function).</p>\n<p>Your code to reassemble the sorted buckets it overly complicated --\nspecifically, the size of the buckets is not important. The work can be done\neither with a list comprehension (as shown) or the equivalent use of 2 <code>for</code>\nloops.</p>\n<p>Consider using a naming convention that I learned from functional programming:\n<code>xs</code> for a collection of things and <code>x</code> for one thing.\nIts extendable (<code>ys</code> and <code>y</code>, <code>zs</code> and <code>z</code>, etc) and\nit works quite nicely in\ngeneric situations like this where we know nothing about the substantive\nmeaning of the values. This also lightens up the code weight -- enhancing\nreadability without any loss of understandability.</p>\n<p>The variable naming in <code>insertion_sort()</code> is backwards. You iterate over the\nindexes but call each index an <code>unsorted_val</code>. If it's an index, just call it\n<code>index</code> or, even better, <code>i</code> (a convention everyone understands). Then if you\nalso need the value, get it with <code>xs[i]</code>. Again, notice how these short\nvariable naming conventions can often enhance readability -- especially if the\nscope is small and well defined.</p>\n<p>Finally, it is unusual to modify an index value during an\niteration over indexes, as you do in <code>insertion_sort()</code>. It forces\nyour reader to puzzle things over. I've seen more intuitive insertion\nsort implementations. For comparison, see the this <a href=\"https://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow noreferrer\">pseudo-code</a>.\nNote how the use of "swap" in that alternative implementation really\nhelps the reader understand what's going on. Either adjust your\ncode or add some guidance to your reader.</p>\n<p>Here's an edit focused on the readability and simplicity issues only:</p>\n<pre><code>def bucket_sort(xs):\n # Convenience variables.\n N = len(xs)\n\n # Put values into buckets.\n buckets = [[] for _ in range(N)]\n for x in xs:\n i = int(N * x)\n buckets[i].append(x)\n\n # Sort each bucket.\n #\n # To keep hammering the point, `b` is a better variable\n # name than `bucket` within this tiny, well-defined context.\n for b in buckets:\n insertion_sort(b)\n \n # Return the sorted values.\n return [\n x\n for b in buckets\n for x in b\n ]\n\ndef insertion_sort(xs):\n # Only stylistic edits here.\n for i in range(1, len(xs)):\n x = xs[i]\n while i > 0 and xs[i - 1] > x:\n xs[i] = xs[i - 1]\n i -= 1\n xs[i] = x\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T06:30:51.640",
"Id": "488309",
"Score": "0",
"body": "Hi thank you for the detailed reply, really appreciate it! I like the idea of using x in xs notation for sets of data. I also like organising the code into paragraphs as it gives me a better understanding of the algorithm itself. Would you be able to elaborate a little on how I can calculate K from N? and would you recommend having K just given to the function instead as it allows more flexibility to the caller?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:52:13.703",
"Id": "488320",
"Score": "0",
"body": "@VehicularIT If you're trying to making this function truly general purpose and robust, you probably should do some internet searching to see what the computer-science experts advise regarding bucket sizing. However, if you're just wanting a practical approach and you're mostly doing this for basic algorithm study, you could take a simpler approach. For example, make `k` an optional function argument, and then set it with a very basic rule based on `N`. Here's one that might not be very good, but it conveys the spirit: `k = k or min(N // 3, 10)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T21:08:07.450",
"Id": "249099",
"ParentId": "249066",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249099",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T06:57:50.890",
"Id": "249066",
"Score": "3",
"Tags": [
"python",
"algorithm",
"sorting",
"bucket-sort"
],
"Title": "Sorts and data structures: a bucket sort"
}
|
249066
|
<h2>Introduction</h2>
<p>I've improved, IMO, Laravel's base Model and FormRequest. It's working as expected. But, before actually implementing this any further in my application, i want to have my classes checked on any problems i did'nt oversee. Also any suggestions for improvements are welcome. And feel free to use it in your application.</p>
<hr />
<h2>FormRequest</h2>
<p><strong>Improvements</strong></p>
<ul>
<li>Easy to use attribute manipulation before validation. Just overwrite the <code>beforeValidation()</code> in your ModelRequest</li>
<li>Policy setup is required by default. If no policy is defined, an error will be thrown. This is done because it's often forgot to implement while this is beïng a serious security risk.</li>
<li>Rules are now defined on the model.</li>
<li>If authorization and validation are required for the request, is defined on the model.</li>
</ul>
<p><strong>Code</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\App\Foundation;
use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;
class FormRequest extends BaseFormRequest
{
/**
* The attributes that should be modified before passing it to the validator.
*
* @var array
*/
public function beforeValidation()
{
return [
//
];
}
/**
* Modify the attributes as defined in beforeValidation() before validation
*
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function getValidatorInstance()
{
$this->merge($this->beforeValidation());
return parent::getValidatorInstance();
}
/**
* The rules that should apply on the request which are defined in the model
*
* @return array
*/
public function rules()
{
return $this->getModel()->rules();
}
/**
* Determine if the request is authorized.
* Authorization should be handled in policies.
*
* @return bool
*/
public function authorize()
{
if ($this->getModel()->authorization && is_null(policy(get_class($this->getModel())))) {
throw new Exception('There are no policies set for '.get_class($this->getModel()).'. You should set the policies in AuthServiceProvider.php');
}
return true;
}
}
</code></pre>
<p><strong>Usage:</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\Http\{namespace};
use App\App\Foundation\FormRequest;
use App\Domain\{namespace};
class {Model}Request extends FormRequest
{
/**
* Return a new model instance
*
* @return Model
*/
public function getModel()
{
return new {Model};
}
}
</code></pre>
<hr />
<h2>Model</h2>
<p><strong>Improvements</strong></p>
<ul>
<li>Defining if validation and authorization are required for the corresponding model. Defaults to true. Setting it to false is usually only done for debugging purposes. You can overwrite the <code>$validation</code> and <code>$authorization</code> properties on your model.</li>
<li>If no validation rules are set and the <code>$validation</code> property is not set to false, an error will be thrown when trying to create/update the corresponding model.</li>
<li>Validation rules can be set per request type (post, put/patch, delete). If validation needs to apply on both store and update requests, just overwrite the <code>validation()</code> method in your model. Else overwrite the <code>defaultValidation()</code>, <code>storeValidation()</code>, <code>updateValidation()</code> and <code>deleteValidation()</code> methods.</li>
<li>Mass assignment protection disabled by default. Only <code>id</code> property is guarded.</li>
<li>All date and datetime columns will be automaticly casted to a Carbon instance. No need to set the <code>$dates</code> or <code>$casts</code> property. If you need additional casts, overwrite the <code>casts()</code> method (instead of property).</li>
<li>The default connection will be set automaticly. When using relations on multiple different connections, laravel does'nt know which connection to use by default and needs to be explicitly defined on the model.</li>
</ul>
<p><strong>Code</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\App\Foundation;
use Illuminate\Database\Eloquent\Model as BaseModel;
class Model extends BaseModel
{
/**
* Construct the Model instance and setup the properties
*
* @return void
*/
public function __construct()
{
$this->casts = array_merge(
$this->getCastableDateColumns(), $this->casts()
);
$this->connection = config('database.default');
}
/**
* The attributes that are not mass assignable.
*
* @var array
*/
protected $guarded = [
'id',
];
/**
* Determine if validation is required.
*
* @var bool
*/
public $validation = true;
/**
* Determine if authorization is required.
*
* @var bool
*/
public $authorization = true;
/**
* The attributes that should be casted to a given data type.
*
* @return array
*/
public function casts()
{
return [];
}
/**
* The rules that should apply on the request.
* This method is staticly beïng called from within the FormRequest
*
* @return array
*/
public static function rules()
{
$self = new static;
if ($self->validation && empty($self->validation())) {
throw new Exception('There are no validation rules set for '.get_class($self).'. Validation can be disabled by overwriting the $validation property.');
}
return $self->validation();
}
/**
* The validation rules that should apply on the request
* If no rule seperation (store/update) is required, the validation method
* can be overwritten so that it returns the validation rules.
*
* @return array
*/
public function validation()
{
$request = request();
if ($request->method() == 'POST')
{
return array_merge(
$this->defaultValidation(),
$this->storeValidation()
);
}
elseif ($request->method() == 'PUT' || $request->method() == 'PATCH')
{
return array_merge(
$this->defaultValidation(),
$this->updateValidation()
);
}
elseif ($request->method() == 'DELETE')
{
return $this->deleteValidation();
}
}
/**
* The validation rules that should apply on both POST and PUT/PATCH requests
* Can be used when separating validation logic based on the request type (POST, PUT/PATCH or DELETE)
* If no seperation is required, the validation() method can be overwritten.
*
* @return array
*/
public function defaultValidation()
{
return [];
}
/**
* The validation rules that should only apply on store (POST) requests
*
* @return array
*/
public function storeValidation()
{
return [];
}
/**
* The validation rules that should only apply on update (PUT/PATCH) requests
*
* @return array
*/
public function updateValidation()
{
return [];
}
/**
* The validation rules that should only apply on delete (DELETE) requests
*
* @return array
*/
public function deleteValidation()
{
return [];
}
public function getCastableDateColumns()
{
$tableColumns = \DB::getDoctrineSchemaManager()->listTableColumns($this->getTable());
$castableDateTypes = [
'Doctrine\DBAL\Types\DateTimeType' => 'datetime',
'Doctrine\DBAL\Types\DateType' => 'date',
];
$castableDateColumns = [];
foreach ($tableColumns as $column) {
if (in_array(get_class($column->getType()), array_keys($castableDateTypes))) {
$castableDateColumns[$column->getName()] = $castableDateTypes[get_class($column->getType())];
}
}
return $castableDateColumns;
}
}
</code></pre>
<p><strong>Usage:</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\Domain\{namespace};
use App\App\Foundation\Model;
class {Model} extends Model
{
public function validation()
{
return [
//
];
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>What PHP version is this code for? i.e. in PHP 7.4 you can add type hints in the code, hence removes a need for that info in the docblocks.</p>\n</li>\n<li><p>Not quite sure why you would need <code>getCastableDateColumns()</code>, I never had a need for this in my projects. Also, another alternative might be to use Laravel's built-in functionality - <a href=\"https://laravel.com/docs/7.x/eloquent-mutators#date-mutators\" rel=\"nofollow noreferrer\">https://laravel.com/docs/7.x/eloquent-mutators#date-mutators</a></p>\n</li>\n<li><p>Not quite sure why you would want to format validation data using <code>beforeValidation()</code>? I would be concerned on how data within <code>beforeValidation()</code> is handled in case someone sends malicious information. But, it would be nice to use it for the setup of some sort before validation starts.</p>\n</li>\n<li><p>Regarding defining rules in the model, I used a similar technique to define fields that can be accessed externally for queries, i.e. I would give FE ability to query field X when endpoint is linked to a specific model.</p>\n</li>\n</ol>\n<p>I found that whilst this technique is nice for a smaller project, for larger projects it proved to be a headache, since some routes might require ability to query field X and some don't. In the end I am now defining a default list that is rather generic & then have a decorator class to extend those defaults.</p>\n<p>What I am trying to say is that this will not scale - your models will bloat and will have restricted usage. You'd be better off having a separate class with those rules for specific use cases, which will then extend your base class.</p>\n<p>Another issue is that you may want to manipulate those rules, i.e. I you are trying to create a book and additionally to sending data regarding a book you need to send categories, you'd endup with something like below:</p>\n<pre><code>public function rules()\n{\n $categoryModel = Category::class;\n\n return $this->getModel()->rules() + [\n 'categories' => ['array'],\n 'categories.*' => [\n 'int',\n "exists:{$categoryModel}",\n ]\n ];\n}\n</code></pre>\n<p>Also, what if for whatever reason, one route should allow you to submit one of the fields that you have within the rules array? e.g. users vs admins.</p>\n<ol start=\"5\">\n<li><p>Not quite sure about <code>casts()</code> method either, as you mentioned, Laravel does casting already. In Laravel 8 you can even cast data into DTO's or ValueObjects.</p>\n</li>\n<li><p><code>$this->connection = config('database.default');</code> this is not extendable. For someone who works with multiple databases this is a no go.</p>\n</li>\n</ol>\n<p>FYI Laravel has non-existent support for queries between multiple databases either. Database names are not applied correctly when using eloquent or DB. If you start a query on DB A to perform an action in DB B, Laravel will try performing that action in DB A on the table from DB B.</p>\n<hr />\n<p>In summary, I would personally use what you wrote as a base class for form requests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T13:31:57.707",
"Id": "489694",
"Score": "1",
"body": "Thanks for the effort. I will later today take my time to give a reaction so i can explain the chooices i've maked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T11:59:58.510",
"Id": "490097",
"Score": "0",
"body": "`getCastableDateColumns()` checks the table structure for `date` and `datetime` type of fields. So this way all date fields automaticly gets casted to a Carbon instance without the need of defining it inside the `casts`-property. In answer to your suggestion of the `dates` property, its better practice to use the `casts`-property over the `dates`-property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:06:09.633",
"Id": "490101",
"Score": "0",
"body": "In reaction to point 3, `beforeValidation()` can be used to format a property before passing it to the validator. This can be handy for in example a postal code. If `1234AB`, `1234 AB`, `1234ab` and `1234 ab` all should be accepted, this can be automaticly formatted using `strtoupper(str_replace(\" \",\"\",$postalcode))` and then passed to the validator. This also helps for data consistency in the database. The user must not be annoyed with errors when we can fix the input very easily. Another example could be to format a phone number before passing it to the validator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:11:36.693",
"Id": "490102",
"Score": "0",
"body": "As of the rules inside the model, you can easily overwrite the `defaultValidation()`, `storeValidation()`, `updateValidation()` and `deleteValidation()`. If thats not enough, just overwrite the `validation()` method in the mode or overwrite the rules() method in the form request. I dont see anything being wrong using your `rules()` code example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:15:27.013",
"Id": "490103",
"Score": "0",
"body": "The `casts()` method can be used if additional fields should be casted. If you would overwrite the `casts`-property, the date fields would'nt be automaticly casted to Carbon instances. Check whats happening in the models constructor. The `$casts`-property is set based on a `array_merge` of `casts()` (should return an array) and `getCastableDateColumns()` (which returns something like `['start_date', 'end_date']`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:17:45.067",
"Id": "490104",
"Score": "0",
"body": "In reaction to point 6, i'm actually using multiple databases. When using multiple databases, `$this->connection` should _always_ be set, even for the models which should use the default connection. If the model should not use the default connection, you can just set the `$connection` property in the model. So it is extendible just fine. (it should be set due to buggy behavior of laravel while using relationships between multiple databases)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:41:42.503",
"Id": "490644",
"Score": "0",
"body": "Regarding point 3 - my personal preference is to let FE to handle this type of thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:43:34.323",
"Id": "490645",
"Score": "0",
"body": "Regrading `rules()` code example: I personally find it a \"hassle\" should I need to delete some of the default rules. I guess `Arr::forget()` would make that task easier, but either way, I prefer to extend for the most part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:46:12.703",
"Id": "490646",
"Score": "0",
"body": "Regarding `casts()`: model meant to reflect what you have in the table, due to which I am not sure where additional fields would come from."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:51:05.113",
"Id": "490648",
"Score": "0",
"body": "Regarding point 6: I assume that any model class that extends `App\\App\\Foundation\\Model` class is part of default connection. The first time I looked through your code I thought that you were setting default connection in a base model... hence why I brought it up since __construct() will override whatever is set in the child model for `$connection`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:09:18.257",
"Id": "490650",
"Score": "1",
"body": "Regarding point 6: http://phpfiddle.org/main/code/w4q5-z281"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:11:50.980",
"Id": "490676",
"Score": "0",
"body": "the casts property is auto filled with all date and datetime fields which are available in the table. But if you want to cast other properties as well, for example an boolean value in the database, you can add that to the casts() method as well. This because casts is not only for dates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:15:33.760",
"Id": "490677",
"Score": "0",
"body": "Thanks for the fiddle! I was'nt aware of this behavior."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-23T13:18:28.697",
"Id": "249737",
"ParentId": "249068",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T08:29:16.507",
"Id": "249068",
"Score": "1",
"Tags": [
"php",
"laravel"
],
"Title": "Improvements on Laravel's base Model and FormRequest"
}
|
249068
|
<p>I have a situation when there could be and could not be values in database, which is why i return optional, so the response object that goes back to the UI could be different depending on the existing or not values.</p>
<p>Examples :</p>
<pre><code> new UserLogsResponse(auditEntity.get().getTimestamp(), latestRetrievedDocumentDateAndTime.get(),emailFromAuditMessage, tokeDateAndTimeStamp)
</code></pre>
<p>As you can see it where it says object.get() its me getting value from the optional.</p>
<p>I would like to avoid numerous if blocks saying if value is Present then add object to the response constructor so currently I am not checking the optional with is present and passing values to the constructor of a response object and inside the constructor i do certain checks and based on checks i either return null or do some operations with not null value and its fine it does the job, however code does not looks good since it highlights get() in optional objects when i do not proceed with checks before passing it to my response object.</p>
<pre><code>@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserLogsResponse {
private final String latestSentEmailStamp;
private final String latestDocumentRetrievalStamp;
private final String privateEmail;
private final String loginTimeStamp;
public UserLogsResponse(LocalDateTime latestSentEmailStamp, LocalDateTime latestDocumentRetrievalStamp, String privateEmail, LocalDateTime loginTimeStamp) {
this.latestSentEmailStamp = latestSentEmailStamp == null ? null : LocalDateFormatter.ddMMyyAtHHmm(latestSentEmailStamp);
this.latestDocumentRetrievalStamp = latestDocumentRetrievalStamp == null ? null : LocalDateFormatter.ddMMyyAtHHmm(latestDocumentRetrievalStamp);
this.privateEmail = privateEmail == null ? null : new Email(privateEmail).hideSomeEmailCharacters();
this.loginTimeStamp = loginTimeStamp == null ? null : LocalDateFormatter.ddMMyyAtHHmm(loginTimeStamp);
}
}
public UserLogsResponse getUserLogs(HttpServletRequest request) {
UserEntity userEntity = currentUser.get();
Optional<LocalDateTime> tokeDateAndTimeStamp = tokenService.getPreviousLoginStamp(request,userEntity, LocalDateTime.now());
Optional<LocalDateTime> latestRetrievedDocumentDateAndTime = auditRepository.getLatestRetrievalDocumentDateAndTime(userEntity.getId());
Optional<AuditEntity> auditEntity = auditRepository.getLatestSendEmailDateAndTime(userEntity.getId());
String emailFromAuditMessage = new AuditMessageExtractor(auditEntity.get().getMessage()).extractEmail();
return tokeDateAndTimeStamp.map(localDateTime -> new UserLogsResponse(auditEntity.get().getTimestamp(), latestRetrievedDocumentDateAndTime.get(), emailFromAuditMessage, localDateTime))
.orElseGet(() -> new UserLogsResponse(auditEntity.get().getTimestamp(), latestRetrievedDocumentDateAndTime.get(),emailFromAuditMessage, null));
}
</code></pre>
<p>Would appreciate any suggestions, as I said everything works and its good but if i was another developer and saw optional objects without ifPresent check it would be confusing.</p>
|
[] |
[
{
"body": "<p>Ah sorry guys i found a solution:</p>\n<p>Will simply do the following and null checks will be handled in constructor</p>\n<pre><code> LocalDateTime tokeDateAndTimeStamp = tokenService.getPreviousLoginStamp(request,userEntity, LocalDateTime.now()).orElseGet(null);\n LocalDateTime latestRetrievedDocumentDateAndTime = auditRepository.getLatestRetrievalDocumentDateAndTime(userEntity.getId()).orElseGet(null);\n AuditEntity auditEntity = auditRepository.getLatestSendEmailDateAndTime(userEntity.getId()).orElseGet(null);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T10:44:01.233",
"Id": "249072",
"ParentId": "249070",
"Score": "1"
}
},
{
"body": "<p>While this appears to make the code simpler, it does have the effect of coupling the <code>UserLogsResponse</code> class to both the token service and the audit repository, which makes it harder to test without mocking or stubbing. Also, do you really want the <code>@Setter</code> annotation? Should those items be read-only after the constructor has run?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T11:14:25.940",
"Id": "488105",
"Score": "0",
"body": "Yes regarding the setter you are right, does not need to be there."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T11:02:17.020",
"Id": "249074",
"ParentId": "249070",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T10:26:05.480",
"Id": "249070",
"Score": "2",
"Tags": [
"java",
"optional"
],
"Title": "Treating Optional values"
}
|
249070
|
<p>I am studying algorithms and I did this "Union Find Like" algorithm.</p>
<p>I have one array of objects with a reference and I make the union pointing to the same reference instead of have two int[] with numbers and weights.</p>
<ul>
<li>Its not necessary to initialize the array.</li>
<li>You will have a maximum of N/2 extra objects ( if you do a union in pairs ), but in an array with a lot of unions you will have just a few objects (only the R roots) with only references pointing to the same object.</li>
<li>It's a linear time.</li>
</ul>
<p>Can I have some feedback about this idea?</p>
<p>Thanks.</p>
<pre><code>public class UnionFind {
public static class Pointer {
Pointer pointerForJoin;
}
// number of elements in array
private static final int N = 10;
private static Pointer[] connection = new Pointer[N];
private static void union(int a, int b) {
if(connection[a] != null && connection[b] != null) {
if(connection[a].pointerForJoin != connection[b].pointerForJoin )
connection[a].pointerForJoin = connection[b].pointerForJoin = connection[a];
} else if(connection[a] != null) {
connection[b] = connection[a];
} else if(connection[b] != null) {
connection[a] = connection[b];
} else {
connection[a] = connection[b] = new Pointer();
connection[a].pointerForJoin = connection[b].pointerForJoin = connection[a];
}
}
private static boolean isConnected(int a, int b) {
if (a == b) return true;
if(connection[a] == null || connection[b] == null) return false;
return connection[a].pointerForJoin == connection[b].pointerForJoin;
}
public static void main(String[] args) {
union(1,2);
union(2,3);
union(5,6);
union(8,9);
union(8,2);
System.out.println(isConnected(8,3)); //true
System.out.println(isConnected(8,2)); //true
System.out.println(isConnected(9,1)); //true
System.out.println(isConnected(1,6)); //false
System.out.println(isConnected(1,7)); //false
System.out.println(isConnected(0,0)); //true
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T23:47:51.503",
"Id": "488169",
"Score": "0",
"body": "Please do not edit the question especially the code after an answer has been posted, because all reviewers/answerers need to be able to see the same code. Read [what to do or not to do when your question is answered](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>First of all, I like the idea and the implementation.</p>\n<p>I have refactored it a bit and came up with that:</p>\n<p><em>isConnected</em>: Extract connection[a] and connection[b] in local variables and simplify the condition.\nEclipse can assist you with the first step, the second one I did manually.</p>\n<pre><code> private static boolean isConnected(int a, int b) {\n if (a == b) {\n return true;\n } else {\n final var pa = connection[a];\n final var pb = connection[b];\n return pa != null && pb != null && pa.pointerForJoin == pb.pointerForJoin;\n }\n }\n</code></pre>\n<p>In union I did the same with the local variables (beware of the assignments in the array.\nThen I used nested IFs, which make the program flow easier to read.</p>\n<p>This results in:</p>\n<pre><code>private static void union(int a, int b) {\n final var pa = connection[a];\n final var pb = connection[b];\n if(pa != null) {\n if (pb != null) {\n if(pa.pointerForJoin != pb.pointerForJoin)\n pa.pointerForJoin = pb.pointerForJoin = pa;\n } else {\n connection[b] = pa;\n }\n } else {\n // pa == null\n if(pb != null) {\n connection[a] = pb;\n } else {\n connection[a] = connection[b] = new Pointer();\n connection[a].pointerForJoin = connection[a];\n }\n }\n}\n</code></pre>\n<p>The next step is to use a helper class instead of static variables, like that:</p>\n<pre><code>public class UnionFind {\n \n public static class Pointer {\n Pointer pointerForJoin;\n }\n \n private final Pointer[] connection;\n \n public UnionFind(int n) {\n connection = new Pointer[n];\n }\n \n private void union(int a, int b) {\n final var pa = connection[a];\n final var pb = connection[b];\n if(pa != null) {\n if (pb != null) {\n if(pa.pointerForJoin != pb.pointerForJoin)\n pa.pointerForJoin = pb.pointerForJoin = pa;\n } else {\n connection[b] = pa;\n }\n } else {\n // pa == null\n if(pb != null) {\n connection[a] = pb;\n } else {\n connection[a] = connection[b] = new Pointer();\n connection[a].pointerForJoin = connection[a];\n }\n }\n }\n \n private boolean isConnected(int a, int b) {\n if (a == b) {\n return true;\n } else {\n final var pa = connection[a];\n final var pb = connection[b];\n return pa != null && pb != null && pa.pointerForJoin == pb.pointerForJoin;\n }\n }\n \n public static void main(String[] args) {\n var uf = new UnionFind(10);\n uf.union(1,2);\n uf.union(2,3);\n uf.union(5,6);\n uf.union(8,9);\n uf.union(8,2);\n \n System.out.println(uf.isConnected(8,3)); //true\n System.out.println(uf.isConnected(8,2)); //true\n System.out.println(uf.isConnected(9,1)); //true\n System.out.println(uf.isConnected(1,6)); //false\n System.out.println(uf.isConnected(1,7)); //false\n System.out.println(uf.isConnected(0,0)); //true\n }\n}\n</code></pre>\n<p>You see how you can create multiple instances of <code>UnionFind</code>? You can even set a capacity at runtime.</p>\n<p>I will leave the addition of the missing JavaDoc to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T20:18:44.483",
"Id": "488163",
"Score": "0",
"body": "I was trying to make a proof of concept of an alternative way (maybe better?) to implement Union Find and I didnt worry about refactoring the code before send it. I should have done that. Thanks for your feedback I will make the changes. ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T18:51:13.543",
"Id": "249094",
"ParentId": "249071",
"Score": "2"
}
},
{
"body": "<p>As soon as you said it's linear time, it was clear that something is wrong. Quick glance at the code showed no loops or recursion, so it was clear that it's indeed linear time and that your algorithm doesn't work.</p>\n<p>Here's an example you fail, you report <code>false</code> even though <code>3</code> and <code>5</code> should be connected due to <code>union(3,1)</code> and <code>union(1,5)</code>:</p>\n<pre><code> public static void main(String[] args) { \n union(1,2);\n union(3,4);\n union(5,6);\n union(3,1);\n union(1,5);\n \n System.out.println(isConnected(3,5));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T00:04:30.880",
"Id": "488171",
"Score": "0",
"body": "It was not a joke, it was a terrible mistake. Thanks for your time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T21:43:34.847",
"Id": "249100",
"ParentId": "249071",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T10:37:08.463",
"Id": "249071",
"Score": "2",
"Tags": [
"java",
"algorithm",
"union-find"
],
"Title": "Different approach Union Find"
}
|
249071
|
<p>Hello I've just finished coding one of my first websites.
And I would love some feedback. I know that I really need to improve my design and improve my code and for that I need some tips from you guys</p>
<p>The webiste (hosted on github.io) can be viewed <a href="https://fluffes.github.io/Minihouse/" rel="nofollow noreferrer">here</a>, and the code itself is also available on <a href="https://github.com/fluffes/Minihouse" rel="nofollow noreferrer">Github</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,
*::after,
*::before {
margin: 0;
padding: 0;
text-decoration: none;
font-family: 'Roboto', sans-serif;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html {
background-color: #EBEBEB;
scroll-behavior: smooth;
overflow-x: hidden;
}
.container {
margin: 0 auto;
width: 100%;
}
@media (max-width: 576px) {
.container {
width: 100%;
}
}
@media (max-width: 768px) {
.container {
max-width: 540px;
}
}
@media (max-width: 992px) {
.container {
max-width: 720px;
padding: 30px 20px;
}
}
@media (max-width: 1200px) {
.container {
max-width: 960px;
}
}
@media (min-width: 1200px) {
.container {
max-width: 1140px;
}
}
@media (min-width: 112.5em) {
.container {
max-width: 1440px;
}
}
section {
padding: 80px 0;
}
@media (max-width: 1200px) {
section {
padding: 50px 0;
}
}
.section-header {
font-size: 48px;
font-weight: bold;
color: rgba(0, 0, 0, 0.2);
scroll-margin-top: 1rem;
}
@media (max-width: 1200px) {
.section-header {
font-size: 32px;
}
}
@media (max-width: 576px) {
.section-header {
font-size: 26px;
text-align: center;
}
}
@media (max-width: 992px) {
.section-header {
text-align: center;
}
}
.header__logo {
font-size: 20px;
font-weight: bold;
}
.header__logo span {
color: black;
font-family: 'Righteous', cursive;
}
.header__logo-link {
color: #810a51;
}
.header__link {
font-size: 17px;
font-weight: 500;
color: #000000;
}
.hamburger {
display: none;
}
@media (max-width: 768px) {
.hamburger {
display: inline-block;
}
}
.hamburger__wrapper {
width: 30px;
height: 100%;
display: inline-block;
position: relative;
cursor: pointer;
z-index: 200;
}
.hamburger__bar {
width: 100%;
height: 4px;
background-color: black;
position: absolute;
left: 0;
top: 50%;
-webkit-transform: translatey(-50%);
transform: translatey(-50%);
-webkit-transition: all .3s;
transition: all .3s;
}
.hamburger__bar::before {
top: -8px;
}
.hamburger__bar::after {
top: 8px;
}
.hamburger__bar::before, .hamburger__bar::after {
content: '';
width: 100%;
height: 4px;
background-color: black;
position: absolute;
left: 0;
-webkit-transition: all .3s;
transition: all .3s;
}
.hamburger__nav {
position: fixed;
width: 50%;
height: 100%;
background-color: #fff;
z-index: 100;
right: 0;
top: 0;
-webkit-transform: translateX(100%);
transform: translateX(100%);
-webkit-transition: all .4s;
transition: all .4s;
}
@media (max-width: 576px) {
.hamburger__nav {
width: 100%;
}
}
.hamburger__menu {
list-style: none;
margin-top: 150px;
display: inline-block;
width: 100%;
text-align: center;
}
.hamburger__link {
font-size: 25px;
font-weight: 500;
color: #000000;
margin-top: 30px;
border-bottom: 1px solid black;
width: 100%;
display: inline-block;
}
.hamburger__link:active .hamburger__nav {
display: none;
}
.hamburger__checkbox {
display: none;
}
.hamburger__checkbox:checked ~ .hamburger__nav {
-webkit-transform: translateX(0);
transform: translateX(0);
}
.hamburger__checkbox:checked + .hamburger__wrapper .hamburger__bar::before {
-webkit-transform: translatey(8px) rotate(45deg);
transform: translatey(8px) rotate(45deg);
}
.hamburger__checkbox:checked + .hamburger__wrapper .hamburger__bar::after {
-webkit-transform: translatey(-8px) rotate(-45deg);
transform: translatey(-8px) rotate(-45deg);
}
.hamburger__checkbox:checked + .hamburger__wrapper .hamburger__bar {
background: transparent;
}
.header .container {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
height: 10vh;
}
@media (max-width: 768px) {
.header .container {
position: fixed;
top: 0;
left: 0;
background-color: #EBEBEB;
z-index: 100;
height: 5vh;
}
}
.header__logo {
-webkit-box-flex: 2;
-ms-flex: 2;
flex: 2;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
}
.header__logo-link {
margin-left: 10px;
display: inline-block;
}
.header__menu {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
list-style: none;
}
@media (max-width: 768px) {
.header__menu {
display: none;
}
}
.header__link {
position: relative;
}
.header__link::after {
position: absolute;
content: '';
width: 100%;
height: 2px;
background-color: #810a51;
left: 0;
-webkit-transition: -webkit-transform 1s ease-in-out;
transition: -webkit-transform 1s ease-in-out;
transition: transform 1s ease-in-out;
transition: transform 1s ease-in-out, -webkit-transform 1s ease-in-out;
-webkit-transform: scale(0);
transform: scale(0);
}
.header__link:hover::after {
-webkit-transform: scale(1);
transform: scale(1);
}
.header__socials {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: end;
-ms-flex-pack: end;
justify-content: flex-end;
}
@media (max-width: 992px) {
.header__socials {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
}
@media (max-width: 768px) {
.header__insta {
display: none;
}
}
nav, .header__socials {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
@media (max-width: 1200px) {
nav, .header__socials {
-webkit-box-flex: 2;
-ms-flex: 2;
flex: 2;
}
}
.landing-page .container {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
height: 90vh;
}
@media (max-width: 768px) {
.landing-page .container {
margin-top: 10vh;
}
}
@media (max-width: 992px) {
.landing-page .container {
height: auto;
padding-top: 50px;
padding-bottom: 50px;
}
}
@media (max-width: 576px) {
.landing-page .container {
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-ms-flex-pack: distribute;
justify-content: space-around;
height: 90vh;
}
}
.plant {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: end;
-ms-flex-pack: end;
justify-content: flex-end;
height: 100%;
}
.plant__tree {
display: none;
}
.plant__thin {
width: 80%;
}
@media (max-width: 1200px) {
.plant__thin {
display: none;
}
}
@media (min-width: 112.5em) {
.plant__thin {
width: 100%;
}
}
@media (max-width: 1200px) {
.plant {
height: auto;
}
.plant__tree {
display: block;
}
}
@media (max-width: 576px) {
.info {
text-align: center;
margin-bottom: 40px;
}
}
.info__header {
font-size: 32px;
font-weight: 500;
}
@media (max-width: 576px) {
.info__header {
font-size: 26px;
}
}
.info__header span {
color: #810a51;
}
.info__hr {
border: 2px solid black;
width: 225px;
margin-top: 20px;
}
@media (max-width: 576px) {
.info__hr {
margin: 20px auto 0;
border-width: 1px;
}
}
.info__desc {
font-size: 16px;
margin-top: 20px;
}
.info__button {
display: inline-block;
border: solid 2px #810a51;
padding: 18px 52px;
background-color: #810a51;
color: white;
font-size: 16px;
font-weight: 500;
margin-top: 38px;
cursor: pointer;
-webkit-transition: all 0.5s ease;
transition: all 0.5s ease;
border-radius: 5px;
-webkit-box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}
@media (max-width: 992px) {
.info__button {
padding: 9px 26px;
}
}
.info__button:hover {
-webkit-transform: translateY(-5px);
transform: translateY(-5px);
}
.info__button:active {
-webkit-transform: translateY(5px);
transform: translateY(5px);
}
.about {
background-color: white;
}
.about__wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
margin-top: 50px;
}
@media (max-width: 992px) {
.about__wrapper {
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
}
.about__desc {
font-size: 16px;
}
@media (max-width: 992px) {
.about__desc {
text-align: center;
}
}
.about__desc:not(:first-child) {
font-size: 16px;
margin-top: 25px;
}
@media (max-width: 576px) {
.about__desc {
width: 100%;
}
}
.about__desc--bold {
font-weight: 500;
}
.about__hr {
height: 3px;
background-color: black;
border: none;
margin-top: 20px;
}
@media (max-width: 992px) {
.about__hr {
display: none;
}
}
.about__text {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
.about__img {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: end;
-ms-flex-pack: end;
justify-content: flex-end;
}
@media (max-width: 992px) {
.about__img {
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
}
.about__img img:last-child {
display: none;
}
@media (max-width: 1200px) {
.about__img img:last-child {
display: block;
}
}
@media (max-width: 576px) {
.about__img img:last-child {
display: none;
}
}
@media (max-width: 992px) {
.about__img img:last-child {
display: none;
}
}
.about__img img:first-child {
width: 75%;
}
@media (max-width: 1200px) {
.about__img img:first-child {
display: none;
}
}
@media (max-width: 992px) {
.about__img img:first-child {
display: inline-block;
margin-top: 50px;
width: 65%;
}
}
@media (max-width: 576px) {
.about__img img:first-child {
display: none;
}
}
.benefits-wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
margin-top: 50px;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
}
.benefits-boxes {
width: 100%;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
position: relative;
}
@media (min-width: 112.5em) {
.benefits-boxes {
width: 620px;
height: 620px;
display: -ms-grid;
display: grid;
-ms-grid-columns: 300px 300px;
grid-template-columns: 300px 300px;
grid-row: auto auto;
grid-column-gap: 20px;
grid-row-gap: 20px;
}
}
@media (max-width: 1200px) {
.benefits-boxes {
display: -ms-grid;
display: grid;
-ms-grid-columns: (minmax(250px, 1fr))[auto-fill];
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-column-gap: 20px;
grid-row-gap: 20px;
}
}
@media (max-width: 992px) {
.benefits-boxes {
margin: 0 auto;
width: 530px;
height: 530px;
display: -ms-grid;
display: grid;
-ms-grid-columns: 250px 250px;
grid-template-columns: 250px 250px;
grid-column-gap: 20px;
grid-row-gap: 20px;
}
}
@media (max-width: 576px) {
.benefits-boxes {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
height: auto;
width: auto;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
}
.benefits-boxes__box {
width: 250px;
height: 250px;
border-radius: 10px;
background-color: white;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
.benefits-boxes__box img {
margin-bottom: 15px;
width: 60px;
height: 70px;
}
.benefits-boxes__box .img-switch-2 {
display: none;
}
.benefits-boxes__box--black {
background-color: #413D3D;
color: #FFFFFF;
}
@media (min-width: 112.5em) {
.benefits-boxes__box--switch-1 {
background-color: #413D3D;
color: #FFFFFF;
}
.benefits-boxes__box--switch-1 .img-switch {
display: none;
}
.benefits-boxes__box--switch-1 .img-switch-2 {
display: block;
}
}
@media (max-width: 992px) {
.benefits-boxes__box--switch-1 {
background-color: #413D3D;
color: #FFFFFF;
}
.benefits-boxes__box--switch-1 .img-switch {
display: none;
}
.benefits-boxes__box--switch-1 .img-switch-2 {
display: block;
}
}
@media (max-width: 576px) {
.benefits-boxes__box--switch-1 {
background-color: white;
color: black;
}
.benefits-boxes__box--switch-1 .img-switch {
display: block;
}
.benefits-boxes__box--switch-1 .img-switch-2 {
display: none;
}
}
@media (min-width: 112.5em) {
.benefits-boxes__box--switch-2 {
background-color: white;
color: black;
}
.benefits-boxes__box--switch-2 .img-switch {
display: none;
}
.benefits-boxes__box--switch-2 .img-switch-2 {
display: block;
}
}
@media (max-width: 992px) {
.benefits-boxes__box--switch-2 {
background-color: white;
color: black;
}
.benefits-boxes__box--switch-2 .img-switch {
display: none;
}
.benefits-boxes__box--switch-2 .img-switch-2 {
display: block;
}
}
@media (max-width: 576px) {
.benefits-boxes__box--switch-2 {
background-color: #413D3D;
color: #FFFFFF;
}
.benefits-boxes__box--switch-2 .img-switch {
display: block;
}
.benefits-boxes__box--switch-2 .img-switch-2 {
display: none;
}
}
@media (min-width: 112.5em) {
.benefits-boxes__box {
width: 300px;
height: 300px;
}
}
@media (max-width: 1200px) {
.benefits-boxes__box:last-child {
margin-top: 25px;
}
}
@media (max-width: 992px) {
.benefits-boxes__box:last-child {
margin-top: 0px;
}
}
@media (max-width: 576px) {
.benefits-boxes__box:not(:first-child) {
margin-top: 20px;
}
}
.benefits-boxes__title {
font-size: 20px;
font-weight: bold;
position: relative;
}
.benefits-boxes__desc {
font-size: 13px;
font-weight: 300;
margin-top: 10px;
}
.benefits-img {
display: none;
}
@media (min-width: 112.5em) {
.benefits-img {
display: block;
}
}
.ideas {
background-color: white;
}
.ideas-box {
margin-top: 50px;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.ideas-box__column {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
.ideas-box__column--1 {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
@media (max-width: 576px) {
.ideas-box__column--1 {
display: block;
}
}
.ideas-box__column--2 {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: end;
-ms-flex-pack: end;
justify-content: flex-end;
}
@media (max-width: 1200px) {
.ideas-box__column--2 {
display: none;
}
}
.ideas-box__column--2 img {
height: 80%;
}
.ideas-box__left {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
padding-right: 25px;
}
@media (max-width: 576px) {
.ideas-box__left {
margin-bottom: 35px;
text-align: center;
}
}
.ideas-box__right {
-webkit-box-flex: 2;
-ms-flex: 2;
flex: 2;
padding-bottom: 25px;
}
.ideas-box__content {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
}
.ideas-box__content:not(:first-child) {
margin-top: 50px;
}
.ideas-box__circle {
background-color: #810a51;
width: 50px;
height: 50px;
border-radius: 50%;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
.ideas-box__header {
font-size: 25px;
font-weight: 500;
}
@media (max-width: 576px) {
.ideas-box__header {
font-size: 21px;
}
}
.ideas-box__title {
width: 80%;
font-size: 20px;
font-weight: normal;
margin-left: 10px;
position: relative;
}
@media (max-width: 576px) {
.ideas-box__title {
font-size: 18px;
}
}
.ideas-box__title::after {
content: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry';
position: absolute;
width: 100%;
margin-top: 5px;
font-size: 13px;
font-weight: 300;
top: 100%;
left: 0;
}
.ideas-box__desc {
margin-top: 10px;
font-size: 13px;
font-weight: 300;
}
.ideas-box__wrapper {
border-left: 1px solid black;
padding-left: 25px;
}
@media (max-width: 576px) {
.ideas-box__wrapper {
border-left: none;
padding-left: 0;
}
}
.footer .container {
padding-top: 80px;
padding-bottom: 80px;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
position: relative;
}
@media (max-width: 1200px) {
.footer .container {
padding-top: 50px;
padding-bottom: 50px;
}
}
@media (max-width: 1200px) {
.footer .container {
display: -ms-grid;
display: grid;
-ms-grid-columns: (1fr)[2];
grid-template-columns: repeat(2, 1fr);
-ms-grid-rows: (1fr)[2];
grid-template-rows: repeat(2, 1fr);
}
}
@media (max-width: 576px) {
.footer .container {
display: block;
}
}
.footer__column {
height: 100%;
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
@media (max-width: 576px) {
.footer__column:not(:first-child) {
margin-top: 50px;
}
}
.footer__column--first {
-ms-grid-row: 1;
-ms-grid-row-span: 1;
-ms-grid-column: 1;
-ms-grid-column-span: 1;
grid-area: 1 / 1 / 2 / 2;
}
.footer__column--second {
-ms-grid-row: 2;
-ms-grid-row-span: 1;
-ms-grid-column: 1;
-ms-grid-column-span: 1;
grid-area: 2 / 1 / 3 / 2;
}
.footer__column--third {
-ms-grid-row: 1;
-ms-grid-row-span: 2;
-ms-grid-column: 2;
-ms-grid-column-span: 1;
grid-area: 1 / 2 / 3 / 3;
}
.footer__header {
font-size: 20px;
font-weight: bold;
color: black;
margin-bottom: 35px;
}
.footer__header--center {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
}
.footer__link {
margin-left: 10px;
display: inline-block;
color: #810a51;
font-weight: bold;
}
.footer__link span {
color: black;
font-family: 'Righteous', cursive;
}
.footer__desc {
margin-bottom: 15px;
font-size: 16px;
color: #282828;
width: 80%;
}
.footer__desc--bold {
font-weight: 500;
}
.footer__link {
margin-right: 30px;
}
.footer__input {
margin-bottom: 25px;
border: 1px solid #282828;
background-color: transparent;
width: 100%;
padding: 5px;
resize: none;
}
.footer__btn {
font-weight: 500;
font-size: 16px;
background-color: #810a51;
color: white;
border: none;
width: 100%;
padding: 12px;
border-radius: 15px;
-webkit-transition: all 0.5s ease;
transition: all 0.5s ease;
cursor: pointer;
-webkit-box-shadow: 0 20px 20px rgba(0, 0, 0, 0.1);
box-shadow: 0 20px 20px rgba(0, 0, 0, 0.1);
}
.footer__btn:hover {
-webkit-transform: translateY(-5px);
transform: translateY(-5px);
}
.footer__btn:active {
-webkit-transform: translateY(5px);
transform: translateY(5px);
}
.footer__rights {
width: 100vw;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
height: 50px;
font-weight: 500;
font-size: 16px;
color: #DADADA;
background-color: #323131;
top: 100%;
left: 0;
}
/*# sourceMappingURL=main.css.map */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Righteous&display=swap" rel="stylesheet">
<link rel="stylesheet" href="sass/main.css">
<title>Minihouse</title>
<link rel="icon" type="img/png" sizes="16x16" href="img/favicon-16x16.png">
</head>
<body>
<header class='header'>
<div class="container">
<div class="header__logo">
<img src="img/logo.svg" alt="logo">
<a class="header__logo-link" href="#header">Mini<span>house</span></a>
</div>
<nav>
<ul class="header__menu">
<li><a href="#about" class="header__link">about</a></li>
<li><a href="#benefits" class="header__link">benefits</a></li>
<li><a href="#ideas" class="header__link">ideas</a></li>
</ul>
</nav>
<div class="header__socials">
<a href="https://www.instagram.com/" target="_blank" class="header__insta">
<img src="img/ig-header.png" alt="insta" >
</a>
<div class="hamburger">
<input type="checkbox" id="navi-toggle" class='hamburger__checkbox'>
<label class='hamburger__wrapper' for='navi-toggle'>
<span class='hamburger__bar'></span>
</label>
<div class="hamburger__nav" id="hamburger__nav">
<ul class="hamburger__menu">
<li><a href="#about" class="hamburger__link">about</a></li>
<li><a href="#benefits" class="hamburger__link">benefits</a></li>
<li><a href="#ideas" class="hamburger__link">ideas</a></li>
<li><a href="#contact" class="hamburger__link">contact</a></li>
</ul>
</div>
</div>
</div>
</div>
</header>
<div class="landing-page">
<div class="container">
<div class="info">
<h2 class="info__header">The beauty of <span>mini</span>malism</h2>
<hr class="info__hr">
<p class="info__desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
<a href="#about" class="info__button">Learn more</a>
</div>
<div class="plant">
<img src="img/plant.png" alt="plant" class='plant__thin'>
<img src="img/tree.png" alt="tree" class='plant__tree'>
</div>
</div>
</div>
<section class="about" id='about'>
<div class="container">
<h2 class="section-header">About.</h2>
<div class="about__wrapper">
<div class="about__text">
<p class="about__desc about__desc--bold">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
<p class="about__desc">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quaerat nesciunt eaque ab aliquid optio? Deserunt, cum reiciendis quasi, laborum blanditiis debitis inventore, maiores repudiandae saepe eveniet non nemo voluptate tempore?</p>
<p class="about__desc">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quaerat nesciunt eaque ab aliquid optio? Deserunt, cum reiciendis quasi, laborum blanditiis debitis inventore, maiores repudiandae saepe eveniet non nemo voluptate tempore?</p>
<hr class="about__hr">
</div>
<div class="about__img">
<img src="img/about-img.png" alt="clean room">
<img src="img/about-img-2.png" alt="alternative image of minimalism">
</div>
</div>
</div>
</section>
<section class="benefits" id="benefits">
<div class="container">
<h2 class="section-header">Benefits.</h2>
<div class="benefits-wrapper">
<div class="benefits-boxes">
<div class="benefits-boxes__box benefits-boxes__box--black">
<img src="img/earth-outline.svg" alt="earth">
<p class="benefits-boxes__title">Good for the Environment</p>
<p class="benefits-boxes__desc">Lorem Ipsum is simply dummy.</p>
</div>
<div class="benefits-boxes__box ">
<img src="img/brush-outline.svg" alt="clean">
<p class="benefits-boxes__title">Easier to Clean</p>
<p class="benefits-boxes__desc">Lorem Ipsum is simply dummy.</p>
</div>
<div class="benefits-boxes__box benefits-boxes__box--black benefits-boxes__box--switch-2">
<img src="img/heart-outline.svg" alt="heart" class="img-switch">
<img src="img/heart-outline-black.svg" alt="heart" class="img-switch-2">
<p class="benefits-boxes__title">Less Stress</p>
<p class="benefits-boxes__desc">Lorem Ipsum is simply dummy.</p>
</div>
<div class="benefits-boxes__box benefits-boxes__box--switch-1">
<img src="img/cash-outline.svg" alt="cash" class="img-switch">
<img src="img/cash-outline-white.svg" alt="cash" class="img-switch-2">
<p class="benefits-boxes__title">Spend Less</p>
<p class="benefits-boxes__desc">Lorem Ipsum is simply dummy.</p>
</div>
</div>
<div class="benefits-img">
<img src="img/benefits.png" alt="wardrobe">
</div>
</div>
</div>
</section>
<section class="ideas" id='ideas'>
<div class="container">
<h2 class="section-header">Ideas.</h2>
<div class="ideas-box">
<div class="ideas-box__column ideas-box__column--1">
<div class="ideas-box__left">
<h2 class="ideas-box__header">Inspire your self with those few ideas</h2>
<p class="ideas-box__desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>
</div>
<div class="ideas-box__right">
<div class="ideas-box__wrapper">
<div class="ideas-box__content">
<div class="ideas-box__circle"><img src="img/bulb.svg" alt="bulb"></div>
<h3 class="ideas-box__title">Start with throwing out stuff you don’t need</h3>
</div>
<div class="ideas-box__content">
<div class="ideas-box__circle"><img src="img/bulb.svg" alt="bulb"></div>
<h3 class="ideas-box__title">Save money by buying less </h3>
</div>
<div class="ideas-box__content">
<div class="ideas-box__circle"><img src="img/bulb.svg" alt="bulb"></div>
<h3 class="ideas-box__title">Sell clothes you don’t wear</h3>
</div>
<div class="ideas-box__content">
<div class="ideas-box__circle"><img src="img/bulb.svg" alt="bulb"></div>
<h3 class="ideas-box__title">Clean your house</h3>
</div>
<div class="ideas-box__content">
<div class="ideas-box__circle"><img src="img/bulb.svg" alt="bulb"></div>
<h3 class="ideas-box__title">Take a look at your PC and phone</h3>
</div>
</div>
</div>
</div>
<div class="ideas-box__column ideas-box__column--2">
<img src="img/idea.png" alt="bulb">
</div>
</div>
</div>
</section>
<footer class="footer" id='contact'>
<div class="container">
<div class="footer__column footer__column--first">
<div class="footer__header footer__header--center">
<img src="img/logo.svg" alt="logo">
<a class="footer__link" href="#header">Mini<span>house</span></a>
</div>
<p class="footer__desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
<p class="footer__desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
<div class="footer__column footer__column--second">
<h2 class="footer__header">Follow us on social media</h2>
<a href="https://www.instagram.com/" target="_blank" class="footer__link">
<img src="img/ig-footer.png" alt="ig logo">
</a>
<a href="" target="_blank" class="footer__link">
<img src="img/fb-footer.png" alt="fb logo">
</a>
<a href="" target="_blank" class="footer__link">
<img src="img/tw-footer.png" alt="tw logo">
</a>
</div>
<div class="footer__column footer__column--third">
<h2 class="footer__header">Contact us</h2>
<p class="footer__desc--bold">E-mail</p>
<input type="text" class="footer__input">
<p class="footer__desc--bold">Message</p>
<textarea cols="30" rows="10" class="footer__input"></textarea>
<button class="footer__btn">Send</button>
</div>
</div>
</footer>
<div class="footer__rights">&copy; 2020 All Rights reserved.</div>
<script src='script.js'></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Well, there are a lot of things that come up to my mind but the first is that <strong>your CSS is overloaded with media queries</strong>. Ideally a well-structured CSS should have not so many declarations in the media queries, because you should choose a fluid approach from the beginning. You should choose also if using a desktop-first or mobile-first approach.</p>\n<p>Your most important media-query breakpoint is for mobile devices; by now a mobile viewport does not exceed 500px while for a tablet this is set to 600px. For a desktop you can safely assume that you find nothing under 980px so your breakpoints could be for mobile-first:</p>\n<ul>\n<li>Normal sytle --> Everything for mobile.</li>\n<li>Breakpoint > 576px --> Rules for tablets</li>\n<li>Breakpoint >= 980px --> Rules for small desktops</li>\n<li>Breakpoint >= 1366px --> Rules for large desktops</li>\n</ul>\n<p>This approach is more modern, mobile-oriented but not ideal for beginners. If you want to prioritise desktops you should write the queries following a reversed logic:</p>\n<ul>\n<li>Normal sytle --> Everything for large desktops.</li>\n<li>Breakpoint <= 1366px --> Rules for small desktops</li>\n<li>Breakpoint <= 980px --> Rules for small tablets</li>\n<li>Breakpoint <= 576px --> Rules for mobile</li>\n</ul>\n<p>There are even better and more efficient approaches to media-queries but, in my opinion, are not well-suited for beginners.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:08:50.810",
"Id": "249435",
"ParentId": "249073",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249435",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T10:57:14.197",
"Id": "249073",
"Score": "4",
"Tags": [
"html",
"css",
"sass"
],
"Title": "Simple website made for learning purposes"
}
|
249073
|
<p>Below is my Code, I want to know ways to improve it.</p>
<pre><code>const findOdd = (A) => {
newObj={};
A.filter((cur,index) =>{
return A.indexOf(cur)===index;
}).forEach((cur) =>{
newObj[cur] = 0
for(let i = 0; i<A.length; i++) if(cur === A[i]) newObj[cur] +=1;
});
const keys = Object.keys(newObj)
key = keys.filter(cur => newObj[cur] % 2 !== 0)
return parseInt(key[0]);
}
</code></pre>
<p>Test Case :
A = [1,1,2,-2,5,2,4,4,-1,-2,5]</p>
<p>Output = -1</p>
<p>Edit : I am trying to create a list of distinct elements at first then add them to an object with key as elements and value as their frequency, then finally finding the keys with odd frequencies.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T11:50:45.453",
"Id": "488106",
"Score": "0",
"body": "What are odd occurrences? It is not clear from the example, and your propensity for skipping newlines makes it unclear from the code as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:15:03.653",
"Id": "488107",
"Score": "4",
"body": "What does your code do and what do you want from us? Remember: in a \"real world\" code review, the code review would be held with a specific purpose (improving throughput, reducing memory usage, find security holes, improve readability, etc.) *and* you would be in the room with us, walking us through your code line-by-line explaining every choice, every variable, every function. On this website, all we have is your question, so you need to make sure that all the information that we would normally get during the review is part of the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:24:02.447",
"Id": "488109",
"Score": "0",
"body": "@konijn I mean if frequency of a number is odd."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:30:22.167",
"Id": "488110",
"Score": "0",
"body": "@JörgWMittag I am trying to create a list of distinct elements at first then add them to an object with key as elements and value as their frequency. then finally finding the keys with odd frequencies."
}
] |
[
{
"body": "<p><strong>Undeclared variables</strong> You aren't declaring your <code>newObj</code> variable or your <code>key</code> variable. This will either implicitly create properties on the global object, or throw an error in strict mode. Both should be avoided. Always declare your variables (with <code>const</code>, or <code>let</code> when <code>const</code> isn't usable) before using them for the first time. Eg, change <code>newObj={};</code> to <code>const newObj = {};</code>.</p>\n<p><strong>Algorithm complexity</strong> Your current approach is pretty computationally expensive. <code>.indexOf</code> will iterate through all elements of the array until it finds a match, or until it reaches the end of the array. <code>.filter</code> will iterate through all elements of an array. With an <code>.indexOf</code> inside a <code>.filter</code>, the computational complexity is <code>O(n ^ 2)</code>. (For example, given an array of 30 items, you can expect to have to carry out 900 times more operations than an array with only 1 item, worst-case.) That's not very good.</p>\n<p>Inside the <code>forEach</code>, you again iterate over every element of the array, resulting in another operation of <code>O(n ^ 2)</code> complexity.</p>\n<p>To reduce the overall complexity of the whole <code>findOdd</code> function to <code>O(n)</code>, iterate over the input array only once, and inside the loop, either create a property on the object, or increment the existing property. (See snippet below for a demo.)</p>\n<p><strong>Variable names</strong> You have variable names <code>A</code> and <code>newObj</code>. At a glance, these are not very informative. Better to give them names that represent what they contain so you can understand them at a glance, such as <code>inputNumbers</code> and <code>occurrencesByNumber</code>. Also, the variable named <code>key</code> <em>isn't actually a key</em> - it's an array of keys. Better to make it plural: <code>keys</code>.</p>\n<p><strong>Semicolons</strong> Sometimes you're using semicolons, sometimes you aren't. Unless you're an expert, I'd recommend using semicolons, else you may occasionally run into hard-to-understand errors due to <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">Automatic Semicolon Insertion</a>. I'd highly <a href=\"https://eslint.org/docs/rules/semi\" rel=\"noreferrer\">a linter</a> (not just for semicolons, but for <em>many</em> ways to prompt you to correct potential bugs before they turn into errors, and to enforce a consistent code style)</p>\n<p><strong>Iterating over an object</strong> You collect the keys using <code>Object.keys</code>, then you iterate over the value at each key by accessing the property of the object: <code>newObj[cur]</code>. If you want to iterate over keys and values at once, you can consider using <code>Object.entries</code> instead.</p>\n<p><strong><code>.find</code> or <code>.filter</code>?</strong> If the objective is to</p>\n<blockquote>\n<p>then finally finding the keys with odd frequencies.</p>\n</blockquote>\n<p>then</p>\n<pre><code>return parseInt(key[0])\n</code></pre>\n<p>is not the right approach, since it'll return only the <em>first</em> element of the array. If you want only one match to be returned, use <code>.find</code> above instead of <code>.filter</code>, so that it ends as soon as a match is found. If you want more than one match to be found, return the array of keys/entries, mapped to numbers.</p>\n<p>Demo implementing these fixes:</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 findOdd = (inputNumbers) => {\n const occurrencesByNumber = {};\n for (const number of inputNumbers) {\n occurrencesByNumber[number] = (occurrencesByNumber[number] || 0) + 1;\n }\n return Object.entries(occurrencesByNumber)\n .filter(([, occurrences]) => occurrences % 2 === 1)\n .map(([numberKey]) => Number(numberKey));\n};\n\nconsole.log(findOdd([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]));\nconsole.log(findOdd([1, 1, 2]));\nconsole.log(findOdd([0, 1, 2]));</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-09-08T14:30:54.077",
"Id": "249081",
"ParentId": "249075",
"Score": "6"
}
},
{
"body": "<p>The feedback of <code>CertainPerformance</code> is already solid. Some minor extra points;</p>\n<ul>\n<li>Avoid fat arrow syntax unless you write an inline function (easier to read)</li>\n<li><code>findOdd</code> is an unfortunate name, how about <code>findOddCounts</code>, which is still a bit awkward but is definitely more evocative</li>\n<li>The nice thing about odd/even is that they follow each other up, you dont <em>have</em> to track the count, you could just track the <a href=\"https://en.wikipedia.org/wiki/Parity_(mathematics)\" rel=\"nofollow noreferrer\">parities</a>.</li>\n</ul>\n<p>All this was really just an excuse to write this;</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 findOddCounts(list){\n const parities = {};\n list.forEach(n => parities[n] = !parities[n]);\n return Object.keys(parities).filter(n => parities[n]).map(n => n*1);\n}\n\nconsole.log(findOddCounts([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]));\nconsole.log(findOddCounts([1, 1, 2]));\nconsole.log(findOddCounts([0, 1, 2]));\n\n//This inspired slepic to mention using a set which could look like this:\n\nfunction findOddCounts(list){\n const set = new Set();\n list.forEach(n => set.has(n) ? set.delete(n) : set.add(n));\n return [...set.keys()];\n}\n\nconsole.log(findOddCounts([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]));\nconsole.log(findOddCounts([1, 1, 2]));\nconsole.log(findOddCounts([0, 1, 2]));\n\n/* There is no need to coerce the output of `set.keys()`, \nthough jshint will not like the abuse of ternary \nand without the ternary it just looks worse to me */</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T18:25:23.260",
"Id": "488262",
"Score": "3",
"body": "It might be better to use `Set`, if `has` then `remove` else `set`. The set will contain exactly the elements that occured odd number of times. No type juggling, no filtering..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:36:27.810",
"Id": "488271",
"Score": "0",
"body": "Great idea, I always seem to forget about `Set`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T23:58:42.807",
"Id": "488285",
"Score": "2",
"body": "@slepic Or `set.delete(n) || set.add(n)` (without `has`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T03:22:23.473",
"Id": "488298",
"Score": "0",
"body": "@superbrain yeah i guess that's also possible :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:39:51.310",
"Id": "488335",
"Score": "0",
"body": "That `Set` solution is such a nice one it made me smile, as I was about to write “it can't work” **twice** already until the realization hit me. It is also really efficient (one could also `reduce` straight into it, but that's a matter of taste I suppose)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T18:07:25.147",
"Id": "249092",
"ParentId": "249075",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T11:21:12.107",
"Id": "249075",
"Score": "4",
"Tags": [
"javascript",
"array"
],
"Title": "Finding numbers with odd frequency in an array"
}
|
249075
|
<p>I have below code for implement toggle button.</p>
<p><a href="https://i.stack.imgur.com/7pXT4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7pXT4.gif" alt="1" /></a></p>
<p>After including below code, processing power consumed over 90% in my embedded application.
Is there any way to reduce this processing power.</p>
<hr />
<p><strong>ToggleButton.h</strong></p>
<pre><code>#ifndef TOGGLEBUTTON_H
#define TOGGLEBUTTON_H
#include <QtWidgets/QAbstractButton>
class QPropertyAnimation;
class ToggleButton :public QAbstractButton
{
Q_OBJECT
Q_PROPERTY(int mOffset READ offset WRITE setOffset);
public:
explicit ToggleButton(int trackRadius, int thumbRadius, QWidget* parent = nullptr);
~ToggleButton();
QSize sizeHint() const override;
protected:
void paintEvent(QPaintEvent *) override;
void resizeEvent(QResizeEvent*) override;
void mouseReleaseEvent(QMouseEvent *) override;
void enterEvent(QEvent *event) override;
void setChecked(bool checked);
int offset();
void setOffset(int value);
private:
qreal mOffset;
qreal mBaseOffset;
qreal mMargin;
qreal mTrackRadius;
qreal mThumbRadius;
qreal mOpacity;
QPropertyAnimation* mAnimation;
QHash<bool, qreal> mEndOffset;
QHash<bool, QBrush> mTrackColor;
QHash<bool, QBrush> mThumbColor;
QHash<bool, QColor> mTextColor;
QHash<bool, QString> mThumbText;
};
#endif // TOGGLEBUTTON_H
</code></pre>
<hr />
<p><strong>ToggleButton.cpp</strong></p>
<pre><code>#include "toggleButton.h"
#include <QtCore/QEvent>
#include <QtCore/QCoreApplication>
#include <QtCore/QPropertyAnimation>
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
///<summary>
/// Toggle button has 2 different design. In the first design, if the ball (thumb) radius is
/// larger than the slide (track) radius, a flat ball slides and colors from the slide according to
/// the on / off situation. In the second design, if the ball radius is smaller than the slide radius,
/// the ball moves according to the on / off status inside the slide and includes the check and uncheck marks.
///</summary>
ToggleButton::ToggleButton(int trackRadius, int thumbRadius, QWidget* parent)
: QAbstractButton(parent)
{
setCheckable(true);
setSizePolicy(QSizePolicy(QSizePolicy::Policy::Fixed, QSizePolicy::Policy::Fixed));
mTrackRadius = trackRadius;
mThumbRadius = thumbRadius;
mAnimation = new QPropertyAnimation(this);
mAnimation->setTargetObject(this);
mMargin = 0 > (mThumbRadius - mTrackRadius) ? 0 : (mThumbRadius - mTrackRadius);
mBaseOffset = mThumbRadius > mTrackRadius ? mThumbRadius : mTrackRadius;
mEndOffset.insert(true, 4 * mTrackRadius + 2 * mMargin - mBaseOffset); // width - offset
mEndOffset.insert(false, mBaseOffset);
mOffset = mBaseOffset;
QPalette palette = this->palette();
if (mThumbRadius > mTrackRadius)
{
mTrackColor.insert(true, palette.highlight());
mTrackColor.insert(false, palette.dark());
mThumbColor.insert(true, palette.highlight());
mThumbColor.insert(false, palette.light());
mTextColor.insert(true, palette.highlightedText().color());
mTextColor.insert(false, palette.dark().color());
mThumbText.insert(true, "");
mThumbText.insert(false, "");
mOpacity = 0.5;
}
else
{
mTrackColor.insert(true, palette.highlight());
mTrackColor.insert(false, palette.dark());
mThumbColor.insert(true, palette.highlightedText());
mThumbColor.insert(false, palette.light());
mTextColor.insert(true, palette.highlight().color());
mTextColor.insert(false, palette.dark().color());
mThumbText.insert(true, QChar(0x2714)); // check character
mThumbText.insert(false, QChar(0x2715)); // uncheck character
mOpacity = 1.0;
}
}
ToggleButton::~ToggleButton()
{
delete mAnimation;
}
QSize ToggleButton::sizeHint() const
{
int w = 4 * mTrackRadius + 2 * mMargin;
int h = 2 * mTrackRadius + 2 * mMargin;
return QSize(w, h);
}
void ToggleButton::paintEvent(QPaintEvent *)
{
QPainter p(this);
QPainter::RenderHints m_paintFlags = QPainter::RenderHints(QPainter::Antialiasing |
QPainter::TextAntialiasing);
p.setRenderHints(m_paintFlags, true);
p.setPen(Qt::NoPen);
bool check = isChecked();
qreal trackOpacity = mOpacity;
qreal textOpacity = 1.0;
qreal thumbOpacity = 1.0;
QBrush trackBrush;
QBrush thumbBrush;
QColor textColor;
if (this->isEnabled())
{
trackBrush = mTrackColor[check];
thumbBrush = mThumbColor[check];
textColor = mTextColor[check];
}
else
{
trackOpacity *= 0.8;
trackBrush = this->palette().shadow();
thumbBrush = this->palette().mid();
textColor = this->palette().shadow().color();
}
p.setBrush(trackBrush);
p.setOpacity(trackOpacity);
p.drawRoundedRect(mMargin, mMargin, width() - 2 * mMargin, height() - 2 * mMargin, mTrackRadius, mTrackRadius);
p.setBrush(thumbBrush);
p.setOpacity(thumbOpacity);
p.drawEllipse(mOffset - mThumbRadius, mBaseOffset - mThumbRadius, 2 * mThumbRadius, 2 * mThumbRadius);
p.setPen(textColor);
p.setOpacity(textOpacity);
QFont font = p.font();
font.setPixelSize(1.5*mThumbRadius);
p.setFont(font);
// Since the antialiasasing provided by the drawText function is incompetent,
// DrawPath function preferred. But since the drawPath function is not capable of aligment,
// Pixel offsets calculated to provide aligment.
QPainterPath textPath;
qreal pixelOffset = (qreal)mThumbRadius * (1 - 1 / 1.414);
textPath.addText(mOffset - mThumbRadius + pixelOffset, mBaseOffset + mThumbRadius - pixelOffset, font, mThumbText.value(check));
p.drawPath(textPath);
mAnimation->setDuration(100);
if(mAnimation->state() != mAnimation->Running)
{
mAnimation->setPropertyName("mOffset");
}
mAnimation->setStartValue(mOffset);
mAnimation->setEndValue(mEndOffset[isChecked()]);
mAnimation->start();
/*p.drawText(QRectF(mOffset - mThumbRadius,
mBaseOffset - mThumbRadius,
2 * mThumbRadius,
2 * mThumbRadius),
Qt::AlignCenter,
mThumbText.value(check));*/
}
void ToggleButton::resizeEvent(QResizeEvent* e)
{
QAbstractButton::resizeEvent(e);
mOffset = mEndOffset.value(isChecked());
}
void ToggleButton::mouseReleaseEvent(QMouseEvent *e)
{
QAbstractButton::mouseReleaseEvent(e);
if (e->button() == Qt::LeftButton)
{
mAnimation->setDuration(120);
mAnimation->setPropertyName("mOffset");
mAnimation->setStartValue(mOffset);
mAnimation->setEndValue(mEndOffset[isChecked()]);
mAnimation->start();
}
}
void ToggleButton::enterEvent(QEvent * event)
{
setCursor(Qt::PointingHandCursor);
QAbstractButton::enterEvent(event);
}
void ToggleButton::setChecked(bool checked)
{
QAbstractButton::setChecked(checked);
mOffset = mEndOffset.value(checked);
}
int ToggleButton::offset()
{
return mOffset;
}
void ToggleButton::setOffset(int value)
{
mOffset = value;
update();
}
</code></pre>
<hr />
<p><strong>main.cpp</strong></p>
<pre><code>#include "toggleButton.h"
#include <QtWidgets/QApplication>
#include <QtWidgets/QHBoxLayout>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget *widget = new QWidget;
widget->setWindowFlags(Qt::FramelessWindowHint);
QHBoxLayout layout;
widget->setLayout(&layout);
ToggleButton *toggleButton1 = new ToggleButton(10, 8);
ToggleButton *toggleButton2 = new ToggleButton(10, 12);
layout.addWidget(toggleButton1);
layout.addWidget(toggleButton2);
widget->show();
return a.exec();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:52:33.163",
"Id": "488113",
"Score": "2",
"body": "Have you profiled your code to find which functions are consuming the most CPU time? This is generally the first step in improving performance. If you are on Linux one of the most common profiling tools is [gprof](https://en.wikipedia.org/wiki/Gprof)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:34:35.393",
"Id": "488147",
"Score": "1",
"body": "I agree with @pacmaninbw that profiling this is the best way to work out what the bottleneck is. Have a look at gamma-ray https://doc.qt.io/GammaRay/gammaray-getting-started.html which is a tool for inspecting the internals of qt apps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T08:44:10.337",
"Id": "488204",
"Score": "1",
"body": "I got the solution by profiling. Thank you for commenting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:07:17.180",
"Id": "488316",
"Score": "0",
"body": "You are welcome. You can improve your question by posting your findings, or you could delete the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T16:07:38.707",
"Id": "488434",
"Score": "0",
"body": "Or post an answer to your own question."
}
] |
[
{
"body": "<p>It takes more processing due to mAnimation inside <strong>paintEvent()</strong> method..\nSo remove Create animation on from <strong>paintEvent()</strong>.</p>\n<p>generate animation inside <strong>mouseReleaseEvent()</strong> method only..</p>\n<pre><code> mAnimation->setDuration(100);\n if(mAnimation->state() != mAnimation->Running)\n {\n mAnimation->setPropertyName("mOffset");\n }\n mAnimation->setStartValue(mOffset);\n mAnimation->setEndValue(mEndOffset[isChecked()]);\n mAnimation->start();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T08:40:24.373",
"Id": "249341",
"ParentId": "249076",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249341",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T11:40:14.297",
"Id": "249076",
"Score": "2",
"Tags": [
"c++",
"performance",
"c++14",
"qt"
],
"Title": "Implementing toggle button using Qt"
}
|
249076
|
<p>So I made a game during the pandemic, and I really enjoyed seeing it grow and learn a ton of stuff and implement it.. The game is about small moving circles that cross a line and when they intersect with the line they start to drag the line with them, until a new circle is born again. You can play and see the source code here:
<a href="https://github.com/danieledep/REW__P5" rel="nofollow noreferrer">https://github.com/danieledep/REW__P5</a></p>
<p>The main cross-checking function works like this:</p>
<pre><code>p5.disableFriendlyErrors = true; // disables FES
let widthScreen = 800,
heightScreen = 540,
wheelRadius = 15,
tapeStart = {
x: widthScreen / 3,
y: heightScreen / 2 - 50,
},
tapeEnd = {
x: (2 * widthScreen) / 3,
y: heightScreen / 2 - 50,
},
theta = Math.PI / 2,
tapes = [],
sectionCross,
crossDirection = 0,
particles = [],
targetArea,
somma,
bgColors = [
"#33B1FF",
"#FD5361",
"#4CB5AE",
"#BEEE62",
"#36F1CD",
"#F786AA",
"#1B998B",
"#6369D1",
"#FFCF56",
"#A0E8AF",
"#F79824",
"#FCEB00",
];
class Tape {
constructor(x, y, crossDir, movement, wheelMov) {
this.x = x;
this.y = y;
this.cross = crossDir;
this.moving = movement;
this.wheelMov = wheelMov;
}
update(x, y, movement, wheelMov) {
this.x = x;
this.y = y;
this.moving = movement;
this.wheelMov = wheelMov;
}
}
function setup() {
createCanvas(widthScreen, heightScreen);
select("canvas").style("background-color", random(bgColors));
select("canvas").attribute("onclick", "pause()");
createUI();
timer = new Timer();
boundary = new Rectangle(0, 0, widthScreen, heightScreen);
qtree = new QuadTree(boundary, 4);
// setup stopped wheels at sides of starting tape
particles[0] = new Particle();
particles[0].setup(tapeStart.x, tapeStart.y + wheelRadius, 0, false);
particles[1] = new Particle();
particles[1].setup(tapeEnd.x, tapeEnd.y + wheelRadius, 0, false);
particles[2] = new Particle();
let point0 = new Point(particles[0].x, particles[0].y, particles[0]);
let point1 = new Point(particles[1].x, particles[1].y, particles[1]);
qtree.insert(point0);
qtree.insert(point1);
let tapeLeft = new Tape(tapeStart.x, tapeStart.y, 0, false, 0);
let tapeRight = new Tape(tapeEnd.x, tapeEnd.y, 0, false, 1);
tapes.push(tapeLeft, tapeRight);
}
function draw() {
clear();
//DEBUG QTREE
//qtree.show();
checkTimer();
checkButton();
checkCross();
moveLine();
drawTape();
drawWheels();
checkCrash();
updateUI();
//getCassetteData();
}
function createNewWheel() {
particles[particles.length] = new Particle();
theta = Math.PI / 2;
timer.resetTimer();
}
function checkTimer() {
if (timer.isFinished()) {
for (let p of particles) {
if (p.moving) {
let point = new Point(p.x, p.y, p);
qtree.insert(point);
}
p.speed = 0;
p.moving = false;
}
for (let w of tapes) w.moving = false;
//qtree = new QuadTree(boundary,4);
createNewWheel();
}
}
function drawWheels() {
let index = 0;
for (let p of particles) {
p.move();
p.render(index);
index++;
}
}
function checkCrash() {
for (let p of particles) {
if (p.moving) p.exits();
let range = new Circle(p.x, p.y, p.r);
let points = qtree.query(range);
for (let point of points) {
let other = point.userData;
if (p !== other) {
if (p.intersects(other)) {
p.collide(other);
}
// check when they are no more colliding
else if (other.moving) {
other.moving = false;
//let point = new Point(other.x, other.y, other);
//qtree.insert(point);
}
}
}
}
}
function drawTape() {
strokeWeight(2);
stroke(0);
somma = 0;
//draw static tape
for (let i = 0; i < tapes.length - 1; i++) {
somma += int(
dist(tapes[i].x, tapes[i].y, tapes[i + 1].x, tapes[i + 1].y) / 40
);
//don't draw the segments connecting behind wheels
if (tapes[i].wheelMov != tapes[i + 1].wheelMov)
line(tapes[i].x, tapes[i].y, tapes[i + 1].x, tapes[i + 1].y);
}
}
function checkCross() {
// for each wheel - particle
for (let j = 0; j < particles.length; j++) {
let p = new Particle();
Object.assign(p, particles[j]);
// check if it's passing between tapes points
for (let l = 0; l < tapes.length - 1; l++) {
// only between those that are not already moved by the particle
// & not the tape connector behind wheels
if (
tapes[l].wheelMov != j &&
tapes[l + 1].wheelMov != j &&
tapes[l].wheelMov != tapes[l + 1].wheelMov
) {
let crossDirection = 0;
// Translate everything so that line segment start point to (0, 0)
let a = tapes[l + 1].x - tapes[l].x; // Line segment end point horizontal coordinate
let b = tapes[l + 1].y - tapes[l].y; // Line segment end point vertical coordinate
let c = p.x - tapes[l].x; // Circle center horizontal coordinate
let d = p.y - tapes[l].y; // Circle center vertical coordinate
// Collision computation
if (
(d * a - c * b) * (d * a - c * b) <=
wheelRadius * wheelRadius * (a * a + b * b)
) {
if (
(c * a + d * b >= 0 && c * a + d * b <= a * a + b * b) ||
(a - c) * (a - c) + (b - d) * (b - d) <=
wheelRadius * wheelRadius ||
c * c + d * d <= wheelRadius * wheelRadius
) {
sectionCross = l;
//console.log(l)
// orientation computation
if (d * a - c * b < 0) {
// Circle center is on left side looking from (x0, y0) to (x1, y1)
crossDirection = 1;
}
insertMovingPoint(p, sectionCross, crossDirection, j);
}
}
}
}
}
}
function moveLine() {
for (let i = 0; i < tapes.length - 2; i++) {
//draw dinamic tape
if (
particles[tapes[i + 1].wheelMov].moving &&
particles[tapes[i + 1].wheelMov].moving &&
tapes[i + 1].wheelMov == tapes[i + 2].wheelMov
) {
//console.log("moveLine: ", i, " - ", i+1)
//let q = particles[tapes[ind].wheelMov]
let leftWheel = new Particle(),
rightWheel = new Particle(),
q = new Particle();
Object.assign(q, particles[tapes[i + 1].wheelMov]);
Object.assign(leftWheel, particles[tapes[i].wheelMov]);
Object.assign(rightWheel, particles[tapes[i + 3].wheelMov]);
//DEBUG
//strokeWeight(0);
//fill(20, 200,90);
//ellipse (leftWheel.x, leftWheel.y, wheelRadius+20, wheelRadius+20)
//ellipse (rightWheel.x, rightWheel.y, wheelRadius+20, wheelRadius+20)
let lt = calculateTangent(
leftWheel,
q,
tapes[i].cross,
tapes[i + 1].cross
);
tapes[i].update(lt.x1, lt.y1, false, tapes[i].wheelMov);
tapes[i + 1].update(lt.x2, lt.y2, true, tapes[i + 1].wheelMov);
let d1 = dist(lt.x1, lt.y1, lt.x2, lt.y2);
let rt = calculateTangent(
q,
rightWheel,
tapes[i + 2].cross,
tapes[i + 3].cross
);
tapes[i + 2].update(rt.x1, rt.y1, true, tapes[i + 2].wheelMov);
tapes[i + 3].update(rt.x2, rt.y2, false, tapes[i + 3].wheelMov);
let d2 = dist(rt.x1, rt.y1, rt.x2, rt.y2);
//distance tape in between tangents
let d12 = dist(lt.x2, lt.y2, rt.x1, rt.y1);
let distanza = dist(lt.x1, lt.y1, rt.x2, rt.y2);
//console.log("d1+d2+d12: ", d1+d2+d12, " dist: ", distanza)
//console.log("tapes[i+1].cross: ", tapes[i+1].cross)
if (d1 + d2 + d12 - distanza < 1) {
let crossingBack;
// Translate everything so that line segment start point to (0, 0)
let a = tapes[i + 3].x - tapes[i].x; // Line segment end point horizontal coordinate
let b = tapes[i + 3].y - tapes[i].y; // Line segment end point vertical coordinate
let c = q.x - tapes[i].x; // Circle center horizontal coordinate
let d = q.y - tapes[i].y; // Circle center vertical coordinate
// Collision computation
if (
(d * a - c * b) * (d * a - c * b) <=
wheelRadius * wheelRadius * (a * a + b * b)
) {
if (
(c * a + d * b >= 0 && c * a + d * b <= a * a + b * b) ||
(a - c) * (a - c) + (b - d) * (b - d) <=
wheelRadius * wheelRadius ||
c * c + d * d <= wheelRadius * wheelRadius
) {
crossingBack = 0;
// orientation computation
if (d * a - c * b < 0) {
// Circle center is on left side looking from (x0, y0) to (x1, y1)
crossingBack = 1;
}
}
}
if (crossingBack != tapes[i + 1].cross) {
//console.log("release")
tapes.splice(i + 1, 2);
}
//console.log("crossingBack: ", crossingBack)
}
}
}
}
function insertMovingPoint(point, sectionCross, crossDirection, wheelCross) {
let leftWheel = new Particle(),
rightWheel = new Particle();
Object.assign(leftWheel, particles[tapes[sectionCross].wheelMov]);
Object.assign(rightWheel, particles[tapes[sectionCross + 1].wheelMov]);
let lt = calculateTangent(
leftWheel,
point,
tapes[sectionCross].cross,
crossDirection
);
tapes[sectionCross].update(lt.x1, lt.y1, false, tapes[sectionCross].wheelMov);
let insertTapeLeft = new Tape(lt.x2, lt.y2, crossDirection, true, wheelCross);
let rt = calculateTangent(
point,
rightWheel,
crossDirection,
tapes[sectionCross + 1].cross
);
let insertTapeRight = new Tape(
rt.x1,
rt.y1,
crossDirection,
true,
wheelCross
);
tapes[sectionCross + 1].update(
rt.x2,
rt.y2,
false,
tapes[sectionCross + 1].wheelMov
);
tapes.splice(sectionCross + 1, 0, insertTapeLeft, insertTapeRight);
}
function calculateTangent(pointLeft, pointRight, crossLeft, crossRight) {
let dst = dist(pointLeft.x, pointLeft.y, pointRight.x, pointRight.y) / 2;
let angle = atan2(pointRight.y - pointLeft.y, pointRight.x - pointLeft.x);
let angle2 = acos((wheelRadius * 2) / dst);
let x1, y1, x2, y2;
if (crossLeft == 0 && crossRight == 0) {
// TANGENT ABOVE
x1 = pointLeft.x + Math.sin(angle) * wheelRadius;
y1 = pointLeft.y - Math.cos(angle) * wheelRadius;
x2 = pointRight.x + Math.sin(angle) * wheelRadius;
y2 = pointRight.y - Math.cos(angle) * wheelRadius;
} else if (crossLeft == 0 && crossRight == 1) {
// TANGENT UP / DOWN
x1 = pointLeft.x + Math.cos(angle - angle2) * wheelRadius;
y1 = pointLeft.y + Math.sin(angle - angle2) * wheelRadius;
x2 = pointRight.x - Math.cos(angle - angle2) * wheelRadius;
y2 = pointRight.y - Math.sin(angle - angle2) * wheelRadius;
} else if (crossLeft == 1 && crossRight == 0) {
// TANGENT DOWN / UP
x1 = pointLeft.x + Math.cos(angle + angle2) * wheelRadius;
y1 = pointLeft.y + Math.sin(angle + angle2) * wheelRadius;
x2 = pointRight.x - Math.cos(angle + angle2) * wheelRadius;
y2 = pointRight.y - Math.sin(angle + angle2) * wheelRadius;
} else if (crossLeft == 1 && crossRight == 1) {
// TANGENT BELOW
x1 = pointLeft.x - Math.sin(angle) * wheelRadius;
y1 = pointLeft.y + Math.cos(angle) * wheelRadius;
x2 = pointRight.x - Math.sin(angle) * wheelRadius;
y2 = pointRight.y + Math.cos(angle) * wheelRadius;
}
let tangent = { x1, y1, x2, y2 };
return tangent;
}
</code></pre>
<p>So the game kindof works fine, what really bothers me is that after few circles it gets slow because of the calculations to check if any circle is crossing any of the new lines, until it gets unplayable.</p>
<p>I'd like to ask for suggestion on how to deal with constantly checking multiple crossing, for example when you do collision detection with many particles you can use a quadtree, i'm wondering if there is an equivalent for lines. Any help is appreciated, thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:12:02.247",
"Id": "488117",
"Score": "0",
"body": "I'm using p5.js, you can read the whole code in the github repo link i posted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:14:25.480",
"Id": "488118",
"Score": "1",
"body": "Your indentation is messy and all over the place; please fix it in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:14:25.667",
"Id": "488119",
"Score": "1",
"body": "While links to repositories are helpful, any code you actually want reviewed must be in the question itself, that is why there is a 64K limit to question size, to allow a great deal of code to be included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:29:13.007",
"Id": "488120",
"Score": "0",
"body": "Fixed the indentation and pasted the main sketch.js file. So you can see my reasoning: I check for line crossing, of all the circles, against all the pair of points of the line. How could that be possibly improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:40:57.017",
"Id": "488123",
"Score": "1",
"body": "Thank you. After some quick & dirty profiling using Chrome's built-in performance profiler, it seems that the most limiting step in your code is this line, `Object.assign(p, particles[j]);`, at line 171 of your `checkCross()` function. I'm no JavaScript expert, but I'm not sure why you need to use `Object.assign()` when you could simply do `const p = particles[j];` instead and be done with it, since you don't change any of the particle's properties afterwards. I'd recommend you also try using your browser's profiler yourself so you can see exactly what parts of your code are slowing you down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:54:42.577",
"Id": "488125",
"Score": "0",
"body": "Thanks, I removed the object.assign but i can't notice big improvements yet, I'm looking into the performance profiler, even tho I'm not expert in this tool"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T14:09:54.717",
"Id": "488129",
"Score": "2",
"body": "@cliesens thank you that was def part of the problem! there were 5 more object.assign and after removing all of these is now way faster, it gets slow after 10 circles, instead of 4/5. i will keep looking into it"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:01:26.110",
"Id": "249077",
"Score": "2",
"Tags": [
"javascript",
"performance",
"processing"
],
"Title": "Multiple circle - line crossing performance"
}
|
249077
|
<p>I've just implemented a search box, so I can search on employee object by (name, part of the name, phone, email ...).
Ex. if the name: Moamen Abdulraouf Mansour, I can search with ( moamen | moa | moamen mansour ...).
The Idea I've followed is:</p>
<ul>
<li>split some values from the object to be not included in the search.</li>
<li>convert each object of the array to one string,</li>
<li>then replace extra spaces and some special Arabic letters with another letter (آ أ إ => ا) and so on.</li>
<li>then convert the search text string to an array of words.</li>
<li>After that, going through each object and find if it includes all words on the search text</li>
<li>finally, return this object to be the result.</li>
</ul>
<p>the JSON looks:</p>
<pre><code>{
"id": "0",
"ORGANIZATION_NAME": "ORGANIZATION NAME",
"ORGANIZATION_NAME_LINK": "<a href='...' target='_blank' title='..'>....</a>",
"ORGANIZATION_TYPE_CODE": "MIN",
"ORGANIZATION_TYPE": "type",
"pid": "99999",
"ORIGINAL_ORGANIZATION_LEVEL": 0,
"DeptUrl": "MI0",
"IsCreated": true,
"ManImageUrl": "https://....jpg",
"EMPLOYEECODE": "90000419",
"EMP_NO_ERP": "90000419",
"TITLE": "السيد",
"USER_FULL_NAME": "employee name",
"USER_POSITION_TITLE": "title",
"USER_EMAIL": "..@domain.com",
"SEX_CODE": "M",
"USER_EXTENSION": "4999",
"USER_MOBILE": "1234",
"USER_HOME_PHONE": "1234"
},...
</code></pre>
<p>and this is the JS:</p>
<pre><code>let searchBtn = document.getElementById('searchBtn');
let myList = document.getElementById('myList');
let arr = [];
let searchKeyword;
var resultsSize = 5;
async function getUserAsync(keywords) {
let response = await fetch('http://localhost:3000/users');
let data = await response.json();
return data;
}
searchBtn.addEventListener('keyup', (e) => {
// get serach text, remove spaces from start and end and remove more than one space between, then convert to array of words
searchKeyword = e.target.value
.replace(/\s+/g, ' ')
.replace(/[\u0623|\u0622|\u0625]/g, 'ا')
.replace(/[\u0649]/g, 'ي')
.replace(/[\u0629]/g, 'ه')
.trim()
.split(' ');
getUserAsync(searchKeyword).then((data) => {
arr = data;
if (searchKeyword[0].length > 2) {
let filtered = arr.filter(function (el) {
let {
id,
DeptUrl,
pid,
IsCreated,
TITLE,
SEX_CODE,
ManImageUrl,
ORGANIZATION_TYPE,
ORGANIZATION_TYPE_CODE,
ORIGINAL_ORGANIZATION_LEVEL,
fortags,
...rest
} = el;
let elCompind = Object.values(rest)
.join()
.replace(/\s+/g, ' ')
.replace(/[\u0623|\u0622|\u0625]/g, 'ا')
.replace(/[\u0649]/g, 'ي')
.replace(/[\u0629]/g, 'ه');
let checkAllWords = searchKeyword.map((item) => {
return elCompind.includes(item);
});
return checkAllWords.includes(false) ? false : true;
});
appendFiltered(filtered.slice(0, resultsSize));
} else {
appendFiltered([]);
}
});
});
function appendFiltered(filteredArray) {
// reset container HTML
myList.innerHTML = '';
filteredArray.forEach((element) => {
// console.log(element);
let node = document.createElement('div'); // Create a node
node.innerHTML = `
<ul>
<li>${element.USER_FULL_NAME}</li>
<li>${element.ORGANIZATION_NAME}</li>
<li>${element.USER_EMAIL}</li>
<li>${element.USER_POSITION_TITLE}</li>
</ul>
`;
myList.appendChild(node); // Append to body
});
}
</code></pre>
<p>the code works well, but I believe this code can be improved.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:12:25.483",
"Id": "488620",
"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)*. Feel free to post a follow-up question instead."
}
] |
[
{
"body": "<p>You didn't post your HTML, but the element with the id <code>searchBtn</code> doesn't seem to be a button, so it shouldn't be called "btn" in it's id or variable name.</p>\n<p>There are many variables that don't change their value, so you should be using <code>const</code> instead of <code>let</code> (or <code>var</code>).</p>\n<p>The variables <code>arr</code> and <code>searchKeyword</code> are only used inside the event handler, so they should be declared in there and not outside.</p>\n<p>The function <code>getUserAsync</code> doesn't use its parameter.</p>\n<p>You should use the event <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event\" rel=\"nofollow noreferrer\"><code>input</code></a> instead of <code>keyup</code>, because the value of the input can change without a keypress.</p>\n<p>The same <code>.replace</code> calls are used on the keywords and the content being searched, so that should be extracted into their out function.</p>\n<p>The requirement that only the first keyword must be longer than two characters seems a bit arbitrarily. The user won't get any results, even if there are more valid (longer) keywords, but they will get results from invalid (shorter) keywords if they are not in the first position. It probably would make more sense to filter out words shorter than three out of the list of keywords.</p>\n<p>Using a deconstructing assignment to create variables that you don't use and in order to exclude certain object properties seems strange. It would probably make more sense to do something like:</p>\n<pre><code>const IGNORED_PROPERTIES = ["id", "DeptUrl", "pid" /* etc. */ ]; \nconst elCompind = Object.entries(el)\n .filter(([k, v]) => !IGNORED_PROPERTIES.includes(k))\n .map(([k, v]) => v)\n .join()\n /* etc. */;\n</code></pre>\n<p>The expression <code>checkAllWords.includes(false) ? false : true</code> can be simplified to <code>!checkAllWords.includes(false)</code>, however it is not necessary at all, because instead of mapping all keywords to a boolean and then checking of there is a <code>false</code> item, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\"><code>.every</code></a> array method. This also has the advantage, that it will stop once a single <code>false</code> has been found and won't necessarily check more keywords:</p>\n<pre><code>return searchKeyword.every(item => elCompind.includes(item)});\n</code></pre>\n<p>(Also notice the simplified lambda.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T10:13:01.980",
"Id": "249207",
"ParentId": "249078",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249207",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T12:56:20.090",
"Id": "249078",
"Score": "1",
"Tags": [
"javascript",
"search"
],
"Title": "Search by parts of Arabic word on JSON"
}
|
249078
|
<p>This is web exercise 3.1.63. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a program that reads in a command line input N and plots the
N-by-N <a href="https://mathworld.wolfram.com/Thue-MorseSequence.html" rel="nofollow noreferrer">Thue-Morse pattern</a>. Below are the Thue-Morse patterns for
N = 4, 8, and 16.</p>
<p><a href="https://i.stack.imgur.com/FpXKY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FpXKY.png" alt="enter image description here" /></a></p>
</blockquote>
<p>Here is my program:</p>
<pre><code>public class ThueMorse
{
public static void drawThueMorse1(int n, double x, double y, double size)
{
if (n == 0) return;
double x1 = x - size/2, x2 = x + size/2;
double y1 = y - size/2, y2 = y + size/2;
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
StdDraw.filledRectangle(x+(3*size/4),y,size/4,size/2);
//StdDraw.pause(300);
StdDraw.filledRectangle(x-(3*size/4),y,size/4,size/2);
//StdDraw.pause(300);
StdDraw.filledRectangle(x,y+(3*size/4),size/2,size/4);
//StdDraw.pause(300);
StdDraw.filledRectangle(x,y-(3*size/4),size/2,size/4);
//StdDraw.pause(300);
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.filledSquare(x,y,size/2);
//StdDraw.pause(300);
StdDraw.filledSquare(x+(3*size/4),y+(3*size/4),size/4);
//StdDraw.pause(300);
StdDraw.filledSquare(x+(3*size/4),y-(3*size/4),size/4);
//StdDraw.pause(300);
StdDraw.filledSquare(x-(3*size/4),y-(3*size/4),size/4);
//StdDraw.pause(300);
StdDraw.filledSquare(x-(3*size/4),y+(3*size/4),size/4);
//StdDraw.pause(300);
drawThueMorse1(n-1, x1, y1, size/2);
drawThueMorse2(n-1, x1, y2, size/2);
drawThueMorse2(n-1, x2, y1, size/2);
drawThueMorse1(n-1, x2, y2, size/2);
}
public static void drawThueMorse2(int n, double x, double y, double size)
{
if (n == 0) return;
double x1 = x - size/2, x2 = x + size/2;
double y1 = y - size/2, y2 = y + size/2;
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.filledRectangle(x+(3*size/4),y,size/4,size/2);
//StdDraw.pause(300);
StdDraw.filledRectangle(x-(3*size/4),y,size/4,size/2);
//StdDraw.pause(300);
StdDraw.filledRectangle(x,y+(3*size/4),size/2,size/4);
//StdDraw.pause(300);
StdDraw.filledRectangle(x,y-(3*size/4),size/2,size/4);
//StdDraw.pause(300);
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
StdDraw.filledSquare(x,y,size/2);
//StdDraw.pause(300);
StdDraw.filledSquare(x+(3*size/4),y+(3*size/4),size/4);
//StdDraw.pause(300);
StdDraw.filledSquare(x+(3*size/4),y-(3*size/4),size/4);
//StdDraw.pause(300);
StdDraw.filledSquare(x-(3*size/4),y-(3*size/4),size/4);
//StdDraw.pause(300);
StdDraw.filledSquare(x-(3*size/4),y+(3*size/4),size/4);
//StdDraw.pause(300);
drawThueMorse1(n-1, x1, y1, size/2);
drawThueMorse2(n-1, x1, y2, size/2);
drawThueMorse2(n-1, x2, y1, size/2);
drawThueMorse1(n-1, x2, y2, size/2);
}
public static int log2(int x)
{
return (int) (Math.log(x)/Math.log(2));
}
public static void main(String[] args)
{
int n = Integer.parseInt(args[0]);
n = log2(n)-1;
drawThueMorse1(n, 0.5, 0.5, 0.5);
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input: N = 256</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/dPko7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dPko7.png" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<blockquote>\n<p>Is there any way that I can improve my program?</p>\n</blockquote>\n<p>Yes :)</p>\n<p>A good cue to see if your program can be improved is when there is lot of repetition in the code. There are <em>usually</em> ways to avoid repetition, although they can sometimes get pretty complex. However, avoiding repetition is useful for two very important reasons :</p>\n<ul>\n<li>Copy/paste usually leads to "dumb" bugs</li>\n<li>If you want to change a thing you need to change it in a billion places, making it more likely you'll forget one.</li>\n</ul>\n<p>I'll be very honest, I'm reading your code as much as I can, but I don't understand what's happening in there, so it's going to be hard to provide a review of what you're doing, but it's also an indication that the code isn't clear enough to be understood by someone trying to understand it (me, in this case).</p>\n<p>What can be done about this?</p>\n<ul>\n<li>Use comprehensive names (That goes for methods, variables, everything really)</li>\n<li>Spacing the code properly (Have you ever read a complicated paper/book where all the text was cramped up? Have you ever read another one where the was good spacing? It makes a world of difference!)</li>\n<li>Avoiding commented code (Why is it there? Is it a mistake? Should it be uncommented? How long has it been commented? Why?)</li>\n<li>Finally, when none of those tips are enough, you should comment your code, but be cautious not to "overcomment". Comments should be just long enough so that someone can understand <em>why</em> you coded the way you did. There's no need to explain things such as "I'm changing the pen color" over <code>StdDraw.setPenColor(StdDraw.BOOK_BLUE);</code></li>\n</ul>\n<p>Now, there's one thing that I think would help tremedously with the readability of the code. Right now, your code both computes the "pattern" and prints it. What if you first generated a binary 2D array that fit the problem at hand, and you had another function that printed this array?</p>\n<p>Taking an example of the N=4 case you gave, the array could look like this :</p>\n<pre><code>0110\n1001\n1001\n0110\n</code></pre>\n<p>Separating the algorithm from the printing will also let you see how you can improve your code.</p>\n<p>For example, we can notice that there's symmetry between the <span class=\"math-container\">\\$row_i\\$</span> and <span class=\"math-container\">\\$col_i\\$</span>, meaning that we only need to find the value of half the grid in order to find all the values (that would be a valuable optimisation for a problem with a big <code>N</code> value).</p>\n<p>Now, if I take a look at the link you gave us, I see that :</p>\n<blockquote>\n<p>Amazingly, the Thue-Morse sequence can be generated from the substitution system :\n0 -> 01 and 1 -> 10, recursively.</p>\n</blockquote>\n<p>Let's look at this with the first row of the N=8 example you gave us. We'll need <span class=\"math-container\">\\$log_2(8)=3\\$</span> iterations of this substitution sequence : <code>0->01->0110->01101001</code>. Let's fill our 2D array with this :</p>\n<pre><code>0 1 1 0 1 0 0 1\n1 X X X X X X X\n1 X X X X X X X\n0 X X X X X X X\n1 X X X X X X X\n0 X X X X X X X\n0 X X X X X X X\n1 X X X X X X X\n</code></pre>\n<p>Now, let's fill the second row, knowing that the first value is 1 : <code>1 -> 10 -> 1001 -> 10010110</code></p>\n<pre><code>0 1 1 0 1 0 0 1\n1 0 0 1 0 1 1 0\n1 0 X X X X X X\n0 1 X X X X X X\n1 0 X X X X X X\n0 1 X X X X X X\n0 1 X X X X X X\n1 0 X X X X X X\n</code></pre>\n<p>For completion, let's do the third row, and I'll leave the rest to you <code>10 -> 1001 -> 10010110</code></p>\n<pre><code>0 1 1 0 1 0 0 1\n1 0 0 1 0 1 1 0\n1 0 0 1 0 1 1 0\n0 1 1 X X X X X\n1 0 0 X X X X X\n0 1 1 X X X X X\n0 1 1 X X X X X\n1 0 0 X X X X X\n</code></pre>\n<p>I guess you see where this ends. This leads to a pretty performant approach with code that should be pretty simple to understand. Afterwards, you could have a function <code>paintThueMorse</code>, give it this 2D array and paint blue for 1, white for 0 or the inverse.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:14:02.050",
"Id": "488330",
"Score": "1",
"body": "Your answer is amazing. Thank you very much. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:03:57.453",
"Id": "249166",
"ParentId": "249080",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:54:29.890",
"Id": "249080",
"Score": "5",
"Tags": [
"java",
"performance",
"beginner",
"recursion"
],
"Title": "Drawing a Thue-Morse pattern recursively"
}
|
249080
|
<p>I have written a little program that converts a CSV-File to an HTML-Table. It works for my purposes. But are there parts in my code that can be written more clean? Can you improve maybe the performance? Are there maybe any bugs? I searched for bugs and fortunately I did not find some.</p>
<p><strong>Postscript</strong></p>
<p>Maybe I should have provided some background information: I am working on a database documentation that I am writing as an HTML document, because I dont like Word-documents. However, creating a tabular description of the columns with dozens of tags is painful. That is why I wrote this script: Now I only have to export the table information as CSV and can convert it directly without having to enter many tags myself. This is why there are no HTML and body tags: The tables created should not be separate HTML documents, but parts of a single, large HTML document.</p>
<p><strong>CsvToHtmlTable.java</strong></p>
<pre><code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
import java.util.List;
import java.util.ArrayList;
public class CsvToHtmlTable {
public static void main(String[] args) {
// print info and show user how to call the program if needed
System.out.println("This program is tested only for UTF-8 files.");
if (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("-help") || args.length != 2) {
System.out.println("java CsvToHtmlTable <input file> <output file>");
System.out.println("Example: java CsvToHtmlTable nice.csv nice.html");
System.exit(0);
}
String csvFile = args[0];
String outputFile = args[1];
// read lines of csv to a string array list
List<String> lines = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) {
String currentLine;
while ((currentLine = reader.readLine()) != null) {
lines.add(currentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
//embrace <td> and <tr> for lines and columns
for (int i = 0; i < lines.size(); i++) {
lines.set(i, "<tr><td>" + lines.get(i) + "</td></tr>");
lines.set(i, lines.get(i).replaceAll(",", "</td><td>"));
}
// embrace <table> and </table>
lines.set(0, "<table border>" + lines.get(0));
lines.set(lines.size() - 1, lines.get(lines.size() - 1) + "</table>");
// output result
try (FileWriter writer = new FileWriter(outputFile)) {
for (String line : lines) {
writer.write(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p><strong>How to call the program:</strong></p>
<pre><code>java CsvToHtmlTable ExampleInput.csv ExampleOutput.html
</code></pre>
<p><strong>ExampleInput.csv</strong></p>
<pre><code>Name,Vorname,Alter
Ulbrecht,Klaus Dieter,12
Meier,Bertha,102
</code></pre>
<p><strong>ExampleOutput.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border><tr><td>Name</td><td>Vorname</td><td>Alter</td></tr>
<tr><td>Ulbrecht</td><td>Klaus Dieter</td><td>12</td></tr>
<tr><td>Meier</td><td>Bertha</td><td>102</td></tr></table></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T15:46:14.460",
"Id": "488137",
"Score": "2",
"body": "You can have an exception when there are no arguments (ArrayIndexOutOfBoundsException), since you validate the position on an empty array; you can add another validation in case the array is empty."
}
] |
[
{
"body": "<h1>CSVReader</h1>\n<p>Reading a CSV file can be a complex task. While many CSV files are just comma-separated-values, if a value contains a comma, it would be surrounded by double quotes, and if the value contains double quotes, the double quotes themselves are doubled.</p>\n<p>To handle these more that just a basic CSV files, you really should use a CSV library, such as <a href=\"http://opencsv.sourceforge.net/\" rel=\"noreferrer\">OpenCSV</a> (com.opencsv:opencsv:5.0) or <a href=\"https://commons.apache.org/proper/commons-csv/\" rel=\"noreferrer\">Apache Commons CSV</a> (org.apache.commons:commons-csv:1.7).</p>\n<h1>HTML</h1>\n<h2>Valid HTML</h2>\n<p>Your code essentially just writes <code><table>...table data...</table></code>. This isn't proper HTML. You're missing <code><html>...</html></code> tags around the entire document, and <code><body>...</body></code> around the content. You should probably also have a <code><head>...</head></code>, perhaps with a nice <code><title>...</title></code>.</p>\n<h2>Escaping</h2>\n<p>If your CSV data contains any special characters, like <code><</code>, <code>></code>, and <code>&</code>, you really must escape them in the generated HTML table.</p>\n<h2>Table Headings</h2>\n<p>It looks like the first line of your table contains headings, not data. The first table row should probably be formatted with <code><th>...</th></code> tags instead of <code><td>...</td></code> tags.</p>\n<h1>Line by Line processing</h1>\n<p>You are reading the entire CSV file into memory, and only when it has been loaded in its entirety are you writing it back out as HTML. This is very memory intensive, especially if the CSV file is huge!</p>\n<p>Instead, you could:</p>\n<ul>\n<li>open the CSV</li>\n<li>open the HTML file</li>\n<li>write the HTML prolog</li>\n<li>for each line read from CSV file:\n<ul>\n<li>format and write line to HTML file</li>\n</ul>\n</li>\n<li>write HTML epilog</li>\n</ul>\n<p>Untested, coding from the hip, without handling quoting in CSV or escaping any HTML entities in output:</p>\n<pre class=\"lang-java prettyprint-override\"><code> try (BufferedReader reader = new BufferedReader(new FileReader(csvFile));\n FileWriter writer = new FileWriter(outputFile)) {\n\n writer.write("<html><body><table border>\\n");\n\n String currentLine;\n while ((currentLine = reader.readLine()) != null) {\n writer.write("<tr>");\n\n for(String field: currentLine.split(","))\n writer.write("<td>" + field + "</td>");\n\n writer.write("</tr>\\n");\n }\n\n writer.write("</table></body></html>\\n");\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n</code></pre>\n<h1>XML & XSLT</h1>\n<p>You may want to consider creating a CSV to XML translator.</p>\n<p>Your XML output might look like:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><data input-file='ExampleInput.csv'>\n <person>\n <Name>Ulbrecht</Name>\n <Vorname>Klaus Dieter</Vorname>\n <Alter>12</Alter>\n </person>\n <person>\n <Name>Meier</Name>\n <Vorname>Bertha</Vorname>\n <Alter>102</Alter>\n </person>\n</data>\n</code></pre>\n<p>And then you could use an <a href=\"https://www.w3schools.com/xml/xsl_intro.asp\" rel=\"noreferrer\">XSLT Stylesheet</a> to translate the XML to HTML, possibly in a browser without ever writing the HTML to a file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:13:47.593",
"Id": "488232",
"Score": "1",
"body": "@DexterThorn As suggested by AJNeufeld better rely on a csv library especially because of problem of quotes inside quotes that is quite common with excel files converted to csv format."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T03:02:09.047",
"Id": "249108",
"ParentId": "249083",
"Score": "5"
}
},
{
"body": "<p>Nice implementation, find my suggestions inline.</p>\n<hr />\n<blockquote>\n<p>can be written more clean?</p>\n</blockquote>\n<ul>\n<li>The class <code>java.nio.file.Files</code> has a couple of handy methods that you can use:</li>\n</ul>\n<pre><code>lines = Files.readAllLines(Paths.get(csvFile), StandardCharsets.UTF_8);\n//..\nFiles.write(Paths.get(outputFile), lines);\n</code></pre>\n<ul>\n<li>Consider to create a constant for the delimiter character. Some CSV files are delimited by <code>;</code> to handle values containing commas, etc.:</li>\n</ul>\n<pre><code>public static final String DELIMITER_CHAR=",";\n</code></pre>\n<ul>\n<li>Provide a user message and exit in case of I/O Exception, for example:</li>\n</ul>\n<pre><code>} catch (IOException e) {\n System.out.println("Error reading input file: "+e.getMessage());\n System.exit(1);\n}\n</code></pre>\n<ul>\n<li>Encapsulate the logic to convert the lines into a method, so that it's easier to test and reuse. For example:</li>\n</ul>\n<pre><code>public class CsvToHtmlTable{\n public static List<String> convert(List<String> lines){/**/}\n public static void main(String[] args){/**/}\n}\n</code></pre>\n<hr />\n<blockquote>\n<p>Can you improve maybe the performance?</p>\n</blockquote>\n<p>The limit of this implementation is the memory constraint. If the input file is large, the whole file might not fit in the available memory.</p>\n<p>Might not be your case, but if you need to handle large files, consider reading and writing the file line by line.</p>\n<hr />\n<blockquote>\n<p>Are there maybe any bugs?</p>\n</blockquote>\n<ul>\n<li>Check if the input file is empty, otherwise <code>lines.set(0,..)</code> fails</li>\n<li>As @Doi9t mentioned, the input validation logic needs to consider when there are no arguments, one, two or more.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T03:25:42.177",
"Id": "249109",
"ParentId": "249083",
"Score": "4"
}
},
{
"body": "<p><strong>Possible <code>NullPointerException</code> at line <code>if (args[0].equals...</code></strong></p>\n<p>Please check the input <code>args</code> size and <code>nullifying</code> before proceed to access any index/item.<br />\nYes, that <code>args</code> could be <code>null</code>, as called by another loaded class. Or empty, if the user forgets to set the <code>args</code>.</p>\n<p><strong>Buffering File</strong></p>\n<p>I think caching the whole file in memory, and then processing it is a good idea for your case, as each line you read, you could simply process, and write it, and proceed for next line. (as <em>Line By Line Processing</em> mentioned by AJNeufeld)</p>\n<p><strong>Broken Column(delimiter) Splitting</strong></p>\n<p>Basically, splitting the columns data using <code>lines.get(i).replaceAll(",",...)</code> is broken, since the data itself would have <code>,</code> as content.</p>\n<p>Considering a line as <code>Porsche,"991,991.2,992",70</code> where your code (and even the one provided by AJNeufeld) will fail, since <code>991,991.2,992</code> is one value, and those <code>""</code> are there to tell the parser, escaped data are ahead.</p>\n<p>So personally, I suggest go for a char-by-char parsing process, that allow you skip any <code>,</code> as delimiter when you reach an opening <code>"</code> til its ending <code>"</code> pair.</p>\n<p><strong>Unexpected Chars</strong></p>\n<p>Also considering to either assert, skip, or convert any unexpected characters. For example converting a <code>NULL</code> (<code>\\0</code>) char into <code>0x00</code> or show the warning and skip it.</p>\n<p><strong>Forget Files</strong></p>\n<p>I suggest, to not lock your app to just read from files, and save to them. Many times <code>STDIN</code>, and <code>STDOUT</code> are more welcome ways.</p>\n<p>I suggest to support from both a file and <code>STDIN</code>. For example, use have to set <code>-fin</code> for a file-input in argument, or <code>-stdin</code> to inform tool read from <code>STDIN</code>.</p>\n<p><strong>Checking Files</strong></p>\n<p>Checking files(both in/out) before processing the file will be great too. To make sure they are accessible.</p>\n<p><strong>Assertion</strong></p>\n<p>Cleaning up(or prompt/setable) the result, while there is an unexpected IO exception during process could be good too.</p>\n<p>Hope it helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:23:24.810",
"Id": "249187",
"ParentId": "249083",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249108",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T15:04:47.673",
"Id": "249083",
"Score": "6",
"Tags": [
"java",
"html",
"csv"
],
"Title": "CSV to HTML Converter"
}
|
249083
|
<p>I'm quite new to web development. I want to implement basic session ID authentication. Here's the implementation</p>
<pre class="lang-golang prettyprint-override"><code>package httphandler
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
"github.com/yura-under-review/auth-01-session-id/user"
)
const UserIdTag = "userId"
type (
Handler struct {
host string
port int
server *http.Server
userStorage UserStorage
sessionStorage SessionStorage
contentPage []byte
loginPage []byte
}
Config struct {
Host string
Port int
}
UserStorage interface {
Close() error
Create(*user.User, string) error
Upsert(*user.User, string) error
Get(string) (*user.User, error)
Exists(string) (bool, error)
CheckPassword(string, string) (bool, error)
}
SessionStorage interface {
Set(userID string)
Get(userID string) bool
}
Credentials struct {
Login string `json:"login"`
Password string `json:"password"`
}
)
func New(config Config, userStorage UserStorage, sessionStorage SessionStorage) (*Handler, error) {
handler := Handler{
host: config.Host,
port: config.Port,
userStorage: userStorage,
sessionStorage: sessionStorage,
}
mux := http.NewServeMux()
mux.Handle("/", handler.Auth(http.HandlerFunc(handler.handleContent)))
mux.HandleFunc("/login", handler.handleLogin)
mux.HandleFunc("/auth", handler.handleAuth)
handler.server = &http.Server{
Addr: fmt.Sprintf("%s:%d", config.Host, config.Port),
Handler: mux,
}
if err := handler.initPages(); err != nil {
return nil, err
}
return &handler, nil
}
func (h *Handler) initPages() error {
contentPage, err := ioutil.ReadFile("html-pages/content.html")
if err != nil {
return fmt.Errorf("failed to read content page: %v", err)
}
h.contentPage = contentPage
loginPage, err := ioutil.ReadFile("html-pages/login.html")
if err != nil {
return fmt.Errorf("failed to read content page: %v", err)
}
h.loginPage = loginPage
return nil
}
func (h *Handler) Run(ctx context.Context, wg *sync.WaitGroup) {
go func() {
<-ctx.Done()
ctxClose, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = h.server.Shutdown(ctxClose)
}()
wg.Add(1)
go func() {
defer wg.Done()
if err := h.server.ListenAndServe(); err != nil {
log.Errorf("server exited with error: %v\n", err)
}
}()
}
func (h *Handler) handleContent(w http.ResponseWriter, r *http.Request) {
_, err := w.Write(h.contentPage)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
func (h *Handler) handleLogin(w http.ResponseWriter, r *http.Request) {
_, err := w.Write(h.loginPage)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
func (h *Handler) handleAuth(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
return
}
login := r.Form.Get("login")
password := r.Form.Get("password")
ok, err := h.userStorage.CheckPassword(login, password)
if err != nil {
log.Errorf("failed to check password: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !ok {
http.Redirect(w, r, "/login", 301)
return
}
newID := uuid.NewV4().String()
h.sessionStorage.Set(newID)
c := http.Cookie{
Name: UserIdTag,
Value: newID,
Path: "/",
}
http.SetCookie(w, &c)
http.RedirectHandler("/", 307).ServeHTTP(w, r)
return
}
func (h *Handler) Auth(destHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var userID string
for _, cookie := range r.Cookies() {
if cookie.Name == UserIdTag {
userID = cookie.Value
break
}
}
if len(userID) != 0 {
ok := h.sessionStorage.Get(userID)
if ok {
h.sessionStorage.Set(userID)
destHandler.ServeHTTP(w, r)
return
}
}
http.RedirectHandler("/login", 307).ServeHTTP(w, r)
return
})
}
</code></pre>
<p>Here's the project on github
<a href="https://github.com/yura-under-review/auth-01-session-id" rel="nofollow noreferrer">https://github.com/yura-under-review/auth-01-session-id</a></p>
<p>I will appreciate for the comments. Could this approach be implemented in production? What must be improved (i.e. passwords shouldn't be stored opened, service must be configurable etc.).</p>
<p>Any kind of ideas and critics is welcome.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T15:34:50.937",
"Id": "249084",
"Score": "3",
"Tags": [
"go",
"authentication"
],
"Title": "Basic authentication with session ID"
}
|
249084
|
<p>I am trying to write a function which execute the given command with given number of retry and delay. If the return code is 0 and output string have expected_output(partial) have to break the loop and return the return code and output. Is there any better to write this code?</p>
<pre><code>cmd check_output_and_retry(cmd, expected_output, delay=1, retry=3):
for i in range(retry):
# Run the given command.
# Return value will be return code with cmd output.
ret, output = execute_cmd(cmd)
if ret == 0 and expected_out in output:
break
else:
time.sleep(delay)
return ret, output
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T17:17:19.580",
"Id": "488154",
"Score": "0",
"body": "This isn't valid Python `cmd` is not a keyword and `cmd check_...` is a syntax error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T18:17:13.217",
"Id": "488156",
"Score": "0",
"body": "By \"command\" I assume you mean some external, non-Python process. The standard way to do that is with [subprocess](https://docs.python.org/3/library/subprocess.html). In particular, you should start by taking a look at `run()`, `check_call()` and `check_output()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T03:34:24.080",
"Id": "488299",
"Score": "0",
"body": "Yes. Its a external non-python binary. Internally execute_cmd wrapped with check_output."
}
] |
[
{
"body": "<p>Without getting into a code golf'esque "shortest possible way to write this function", I'll just note a few alternatives to your particular implementation, and you can consider if you think they're simpler or not.</p>\n<ol>\n<li><p><code>if ret == 0</code> is equivalent to <code>if not ret</code>. While that's probably not more legible in the <code>if</code> statement, it might be if you named this variable, e.g. <code>program_failed = not ret</code>.</p>\n</li>\n<li><p><code>expected_out in output</code> is just one thing someone might want to do to evaluate if the output was what they wanted (e.g., maybe instead they want to do a regex check). You may want to replace this with a totally freeform function, then just call that function and use its result; e.g., <code>if ret == 0 and output_ok(output):</code></p>\n</li>\n<li><p>Building on both of these, it might be prettier to name the conditions:</p>\n<pre><code>status_ok = ret == 0\noutput_ok = check_output(output)\nif status_ok and output_ok: # ...\n</code></pre>\n</li>\n<li><p>Due to the nature of the <code>if</code> statement, the <code>else</code> condition is superfluous. It'd be equivalent to write:</p>\n<pre><code>if condition:\n break\n\ntime.sleep(delay)\n</code></pre>\n</li>\n<li><p>You <code>return ret, output</code> whether or not the program succeeds, which may be confusing. Since your function's purpose is to check the output of the program and retry if it fails, it seems odd to return "successfully" if the program fails those checks just because it's run out of retries. Consider raising an exception instead.</p>\n<pre><code>for _ in range(retry):\n # ...\n if condition:\n break\n # ...\nelse:\n raise ValueError("Failed to run program successfully, <some useful information about ret, output, etc.>")\nreturn output # Only output, since ``ret`` is guaranteed to be 0\n</code></pre>\n</li>\n<li><p>Pycharm and potentially other Python stylers might get upset at you for having a named variable you don't use: <code>i</code>. Consider replacing with <code>_</code>:</p>\n<pre><code>for _ in range(retry): # ...\n</code></pre>\n</li>\n<li><p>I'm just going to assume the <code>cmd check_output...</code> is just a typo, since Python uses <code>def</code>.</p>\n</li>\n<li><p>Write a docstring!</p>\n</li>\n</ol>\n<p>Again, you might not think all of the above are improvements, just alternatives. If you did follow them all, you might end up with the following:</p>\n<pre><code>def check_output_and_retry(cmd, check_output: lambda out: True, delay=1, retry=3):\n """Runs command until it succeeds. Raises a ValueError if it can't get the program to succeed.\n\n Args:\n cmd (str): The command to run\n check_output (callable): A function that takes the output string and returns whether or not it's ok\n delay (int|float): The number of seconds to wait between attempts\n retry (int): The number of times to try running the command before failing\n\n Returns:\n str: The program output. The program return code is guaranteed to be 0.\n """\n for _ in range(retry):\n # Run the given command.\n ret, output = execute_cmd(cmd)\n status_ok = ret == 0\n output_ok = check_output(output)\n if status_ok and output_ok:\n break\n\n time.sleep(delay)\n else:\n raise ValueError(f"Program failed to execute within {retry} attempts (status: {ret}: {output}")\n\n # Return value will be cmd output, since the return code is guaranteed to always be 0\n return output\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T17:20:53.413",
"Id": "249089",
"ParentId": "249087",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:34:05.600",
"Id": "249087",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python retry logic based on return code and output"
}
|
249087
|
<p>I am passing <code>a</code> in as a parameter and want to return <code>b</code>.</p>
<p><strong>This works</strong>, however I feel like it is wrong because I shouldn't have to pass <code>a</code> in at the return. Also, if I don't include the type for <code>a</code>, I get an error that says <code>Parameter 'path' implicitly has an 'any' type.</code></p>
<pre><code>async function exampleFunc(a: string) {
const b = async (a: any) => {
try {
// blah blah
} catch (error) {
console.log(error);
}
};
return b(a);
}
</code></pre>
<p>How can I improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T23:52:52.620",
"Id": "488170",
"Score": "1",
"body": "Welcome to the Code Review site where we review actual working code from your project and provide suggestions on how to improve the code. The code in the question is very hypothetical and doesn't appear to be real code from your project. Please [see our guidelines](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T06:04:01.577",
"Id": "488308",
"Score": "0",
"body": "There is nothing wrong in *tail calls*."
}
] |
[
{
"body": "<p>You declared a function <code>b</code> with an argument declared named <code>a</code>. That argument definition "hides" or "overrides" the parent <code>a</code> so you cannot access the parent <code>a</code> when you have this other <code>a</code> declared.</p>\n<p>So, you have to pass that argument or it will have an <code>undefined</code> value. If you leave out the argument definition for <code>b</code> entirely or give it a different non-conflicting name, then and only then, can you directly reference the parent argument <code>a</code>.</p>\n<p>So, you could do this if you want to directly reference the parent-scoped <code>a</code> from within <code>b</code> without passing it as an argument:</p>\n<pre><code>async function exampleFunc(a: string) {\n const b = async () => {\n try {\n console.log(a);\n // blah blah \n } catch (error) {\n console.log(error);\n }\n };\n return b();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T05:31:01.673",
"Id": "488176",
"Score": "0",
"body": "Please refrain from answering off topic questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T22:45:54.010",
"Id": "249102",
"ParentId": "249101",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249102",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T22:37:13.327",
"Id": "249101",
"Score": "-1",
"Tags": [
"asynchronous",
"typescript",
"async-await",
"promise",
"type-safety"
],
"Title": "Am I using the same Typescript variable?"
}
|
249101
|
<p>I need an encryption system with a super simple API. I'd prefer something as simple as the following. The output should also be browser-friendly and ideally url-friendly.</p>
<pre><code>$encrypted=encrypt(data);
$decrypted=decrypt(encrypted);
</code></pre>
<p>I'm not a cryptographer, however I have come up with the following to achieve this.</p>
<pre class="lang-php prettyprint-override"><code><?php
declare(strict_types = 1);
class EasyCrypt
{
// format: easycryptstart_version_(bytes_of_b64bin)_b64bin_easycryptend
// b64bin: base64urlencode(bin)
// bin: versionspecific
// V1 versionspecific: IV+aes128ctr(encryption_key=hkey,csum+inner_length+data+padding)
// V1 hkey: substr(sha256(key),16); // sha256 is used as a key compressor/expander
// V1 inner_length: little_endian_uint64(strlen(data))
// V1 csum: substr(sha256(inner_length+data+padding),14)
// V1 padding: null-bytes until strlen(csum+inner_length+data+padding) is divisible by 16 bytes (128 bits), (16-(size%16))%16
// generate secure key: cat /dev/urandom | head --bytes=15 | base64
private const EASY_ENCRYPTION_KEY = "CHANGEME";
private const V1_IV_LENGTH = 16;
private const V1_ENCRYPT_ALGO = 'aes-128-ctr';
private const V1_HASH_ALGO = 'sha256';
private const V1_HASH_TRUNCATE_LENGTH = 14;
public static function encryptEasy(string $data): string
{
return self::encrypt($data, self::EASY_ENCRYPTION_KEY);
}
public static function decryptEasy(string $data, string &$decryptionError = null): ?string
{
return self::decrypt($data, self::EASY_ENCRYPTION_KEY, $decryptionError);
}
public static function encrypt(string $data, string $encryption_key): string
{
$version = 1;
$prefix = "easycryptstart_{$version}_";
$postfix = "_easycryptend";
$ret = self::encryptV1($data, $encryption_key);
$ret = self::base64url_encode($ret);
$ret = $prefix . strlen($ret) . "_" . $ret . $postfix;
return $ret;
}
public static function decrypt(string $data, string $encryption_key, string &$decryptionError = null): ?string
{
// only 1 "version" exist thus far
$version = 1;
$data = str_replace(array(
" ",
"\r",
"\n",
"\t"
), "", $data);
$prefix = "easycryptstart_{$version}_";
$postfix = "_easycryptend";
$prefixpos = strpos($data, $prefix);
if (false === $prefixpos) {
$decryptionError = "prefix not found";
return null;
}
$postfixpos = strpos($data, $postfix, $prefixpos);
if (false === $postfixpos) {
$decryptionError = "postfix not found (even tho prefix was found!)";
return null;
}
$data = substr($data, $prefixpos + strlen($prefix), $postfixpos - ($prefixpos + strlen($prefix)));
$outer_length_end = strpos($data, "_");
if (false === $outer_length_end) {
$decryptionError = "corrupted input, outer length end missing!";
return null;
}
$outer_length = substr($data, 0, $outer_length_end);
$outer_length = filter_var($outer_length, FILTER_VALIDATE_INT);
if (false === $outer_length) {
$decryptionError = "corrupt input, outer_length non-int!";
return null;
}
$data = substr($data, $outer_length_end + strlen("_"));
$dlen = strlen($data);
if ($dlen < $outer_length) {
$decryptionError = "corrupt input, outer length header said {$outer_length} bytes, but only {$dlen} bytes available!";
return null;
}
$data = substr($data, 0, $outer_length);
$data = self::base64url_decode($data);
return self::decryptV1($data, $encryption_key, $decryptionError);
}
private static function decryptV1(string $data, string $encryption_key, string &$decryptionError = null): ?string
{
if (strlen($data) < self::V1_IV_LENGTH) {
$decryptionError = "corrupt input, IV is missing!";
return null;
}
$IV = substr($data, 0, self::V1_IV_LENGTH);
$data = substr($data, self::V1_IV_LENGTH);
// now we have the aes128 data..
if (strlen($data) < 16 || (strlen($data) % 16) !== 0) {
$decryptionError = "corrupted input, after removing IV, data is not a multiple of 16 bytes!";
return null;
}
$hkey = hash(self::V1_HASH_ALGO, $encryption_key, true);
$hkey = substr($hkey, 0, 16);
$data = openssl_decrypt($data, self::V1_ENCRYPT_ALGO, $hkey, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $IV);
if (! is_string($data)) {
// should never happen
throw new \RuntimeException("openssl_decrypt failed! wtf!?");
}
if (strlen($data) < self::V1_HASH_TRUNCATE_LENGTH) {
$decryptionError = "corrupt input, after decryption, checksum hash is missing!";
return null;
}
$checksum_supplied_hash = substr($data, 0, self::V1_HASH_TRUNCATE_LENGTH);
$data = substr($data, self::V1_HASH_TRUNCATE_LENGTH);
$checksum_calculated_hash = hash(self::V1_HASH_ALGO, $data, true);
$checksum_calculated_hash = substr($checksum_calculated_hash, 0, self::V1_HASH_TRUNCATE_LENGTH);
if (! hash_equals($checksum_calculated_hash, $checksum_supplied_hash)) {
$decryptionError = "checksum mismatch, possibly wrong decryption key?";
return null;
}
$little_endian_uint64_length = 8;
if (strlen($data) < $little_endian_uint64_length) {
$decryptionError = "after decryption, inner_length header is missing!";
return null;
}
$little_endian_uint64 = substr($data, 0, $little_endian_uint64_length);
$little_endian_uint64 = self::from_little_uint64_t($little_endian_uint64);
$data = substr($data, $little_endian_uint64_length);
$dlen = strlen($data);
if ($dlen < $little_endian_uint64) {
$decryptionError = "inner_length header said {$little_endian_uint64} bytes, but only {$dlen} bytes remaining, and that includes any padding bytes!";
return null;
}
$data = substr($data, 0, $little_endian_uint64);
return $data;
}
private static function encryptV1(string $data, string $encryption_key): string
{
// compress/expand the key so we can accept any encryption key length (instead of the 16 bytes key required by aes-128)
$hkey = hash(self::V1_HASH_ALGO, $encryption_key, true);
$hkey = substr($hkey, 0, 16);
$iv = random_bytes(self::V1_IV_LENGTH);
$inner_length_bytes = self::to_little_uint64_t(strlen($data));
$ret = $inner_length_bytes;
$ret .= $data;
$padding_length = self::V1_HASH_TRUNCATE_LENGTH + strlen($ret);
$padding_length = (16 - ($padding_length % 16)) % 16;
$ret .= str_repeat("\x00", $padding_length);
$csum = hash(self::V1_HASH_ALGO, $ret, true);
$csum = substr($csum, 0, self::V1_HASH_TRUNCATE_LENGTH);
$ret = $csum . $ret;
$str = openssl_encrypt($ret, self::V1_ENCRYPT_ALGO, $hkey, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
if (! is_string($str)) {
// should never happen
throw new \RuntimeException("openssl_encrypt failed! wtf!?");
}
$str = $iv . $str;
return $str;
}
private static function to_uint8_t(int $i): string
{
return pack('C', $i);
}
private static function from_uint8_t(string $i): int
{
// ord($i) , i know.
$arr = unpack("Cuint8_t", $i);
return $arr['uint8_t'];
}
private static function to_little_uint64_t(int $i): string
{
return pack('P', $i);
}
private static function from_little_uint64_t(string $i): int
{
$arr = unpack('Puint64_t', $i);
return $arr['uint64_t'];
}
private static function base64url_encode($data)
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
private static function base64url_decode($data)
{
return base64_decode(strtr($data, '-_', '+/'));
}
}
</code></pre>
<p>Example usage:</p>
<pre><code>$data = "Hello World!"; // . random_bytes(10*1024*1024);
$decryptionError = "";
$encrypted = EasyCrypt::encryptEasy($data);
$decrypted = EasyCrypt::decryptEasy($encrypted, $decryptionError);
$pretty = [
"data to encrypt" => $data,
"encrypted" => $encrypted,
"decrypted successfully" => $decrypted === $data,
"decryption error" => $decryptionError
];
var_export($pretty);
</code></pre>
<pre><code>$ php EasyCrypt.php | more
array (
'data to encrypt' => 'Hello World!',
'encrypted' => 'easycryptstart_1_86_LvBV6n3yLY-sH3vdhjzIZmbAm56s7VEZ9ah0wh5z4p9-rhJBaIDmOQYaWOTuRSei7yfmXJ6HTbqgvBaQJsQdMg_easycryptend',
'decrypted successfully' => true,
'decryption error' => '',
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T08:03:24.853",
"Id": "488200",
"Score": "2",
"body": "For a widely used, well studied secure implementation, [libsodium](https://libsodium.gitbook.io/doc/secret-key_cryptography/secretbox) is a good option. It is available built-in to PHP since version 7.2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T10:56:34.827",
"Id": "488214",
"Score": "1",
"body": "\"I need a cryptography system! I'm not a cryptographer, but I'm going to make my own.\" This is basically the definition of a bad idea. Just use an existing crypto system, which *has* been designed by cryptographers and is actually secure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T12:18:12.057",
"Id": "488218",
"Score": "0",
"body": "@nick012000 you certainly have a point; but i'm also curious as to what mistakes i did, so having the implementation reviewed may be very educational for me"
}
] |
[
{
"body": "<p>Remove <code>encryptEasy</code> and <code>decryptEasy</code>; both functions are insecure and only serve to confuse possible users.</p>\n<p>Your current scheme doesn't use a MAC, not a checksum which means the ciphertext is unauthenticated. <a href=\"https://security.stackexchange.com/questions/44150/dont-use-encryption-without-message-authentication\">This is a bad idea</a>. It is recommended to use a HMAC function for authentication, in order to also avoid the risk of hash extension attacks while keeping the output range large.</p>\n<p><a href=\"https://crypto.stackexchange.com/questions/202/should-we-mac-then-encrypt-or-encrypt-then-mac\">Encrypt-then-MAC is recommended</a>, while your current approach is hash-then-encrypt which is theoretically vulnerable to CTR bitflipping attacks.</p>\n<p>Your padding implementation is incorrect if the data already contains null bytes (Use PKCS#7).</p>\n<p>Instead of using a reference param for exceptions, just throw exceptions directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T06:54:04.580",
"Id": "488187",
"Score": "0",
"body": "thanks for checking it! `order to also avoid the risk of hash extension attacks` - i don't think length extension attack is feasible on `sha256|112` even if the attacker had the encryption key? (for the same reason length extension isn't feasible on SHA2-384) `theoretically vulnerable to CTR bitflipping attacks` - i would imagine any bitflips would break the sha256|112 hash ending up with `checksum mismatch, possibly wrong decryption key?` regardless of CTR vulnerabilities?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T00:09:02.207",
"Id": "493442",
"Score": "0",
"body": "Nowadays you should use authenticated encryption instead of HMAC, if just because starting users are going to forget to e.g. MAC the IV as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T01:21:01.403",
"Id": "249106",
"ParentId": "249104",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T23:29:24.900",
"Id": "249104",
"Score": "3",
"Tags": [
"php",
"security",
"cryptography",
"encryption"
],
"Title": "Very simple encryption API"
}
|
249104
|
<p>Is there a way to do this many-to-many update with less code? It feels awfully bulky to me.</p>
<p>I started out using AutoMapper to avoid the explicit value assignments, but then the mapped <code>Movie</code> doesn't come with its <code>Genre</code> entities. I had to scrap that so I could use the <code>Include()</code> extension method to accomplish the goal. But even AutoMapper, if it worked in this case, wouldn't trim all of this down by much.</p>
<p>The idea is to update the database with the movie genres specified by the user, both addition and removal.</p>
<p>If this is the most compact it can get, so be it. But I thought I'd at least check first.</p>
<p><strong>Controller</strong></p>
<pre><code><HttpPost>
<ValidateAntiForgeryToken>
Public Function Edit(ViewModel As MovieViewModel) As ActionResult
Dim oUnchecked As Func(Of GenreCheckBox, Boolean)
Dim oChecked As Func(Of GenreCheckBox, Boolean)
Dim oMovie As Db.Movie
Dim oGenre As Db.Genre
If Me.ModelState.IsValid Then
Using oDb As Db.Context = Db.Context.Create
oMovie = oDb.Movies.Include(Function(Movie) Movie.Genres).SingleOrDefault(Function(Movie) Movie.Id = ViewModel.Id)
If oMovie Is Nothing Then
Edit = Me.HttpNotFound
Else
oUnchecked = Function(CheckBox) CheckBox.IsChecked = False
oChecked = Function(CheckBox) CheckBox.IsChecked = True
oMovie.ReleaseYear = ViewModel.ReleaseYear
oMovie.Rating = ViewModel.Rating
oMovie.Price = ViewModel.Price
oMovie.Title = ViewModel.Title
ViewModel.GenreCheckBox.Where(oUnchecked).ForEach(Sub(CheckBox)
oGenre = oDb.Genres.Single(Function(Genre) Genre.Id = CheckBox.Id)
oMovie.Genres.Remove(oGenre)
End Sub)
ViewModel.GenreCheckBox.Where(oChecked).ForEach(Sub(CheckBox)
oGenre = oDb.Genres.Single(Function(Genre) Genre.Id = CheckBox.Id)
oMovie.Genres.Add(oGenre)
End Sub)
oDb.SaveChanges()
End If
End Using
Edit = Me.RedirectToAction(NameOf(MoviesController.Index))
Else
Edit = Me.View(ViewModel)
End If
End Function
</code></pre>
<p><strong>Movie</strong></p>
<pre><code>Public Class Movie
Public Property Id As Integer
Public Property ReleaseYear As Integer
Public Property Rating As String
Public Property Price As Decimal
Public Property Title As String
Public Property Genres As ICollection(Of Genre) = New List(Of Genre)
End Class
</code></pre>
<p><strong>Genre</strong></p>
<pre><code>Public Class Genre
Public Property Id As Integer
Public Property Name As String
Public Property Movies As ICollection(Of Movie) = New List(Of Movie)
End Class
</code></pre>
<p><strong>--EDIT--</strong></p>
<p>I managed to clean it up a bit. This should bring some small measure of performance improvement as well, now that it's not hitting the database with each loop.</p>
<p>I think this is going to be about as good as it gets.</p>
<pre><code><HttpPost>
<ValidateAntiForgeryToken>
Public Function Edit(ViewModel As MovieViewModel) As ActionResult
Dim oActionRemove As Action(Of Db.Genre)
Dim oQueryRemove As Func(Of Db.Genre, Boolean)
Dim oUnchecked As Func(Of GenreCheckBox, Boolean)
Dim oIdsRemove As IEnumerable(Of Integer)
Dim oActionAdd As Action(Of Db.Genre)
Dim oSelector As Func(Of GenreCheckBox, Integer)
Dim oQueryAdd As Func(Of Db.Genre, Boolean)
Dim oChecked As Func(Of GenreCheckBox, Boolean)
Dim oIdsAdd As IEnumerable(Of Integer)
Dim oMovie As Db.Movie
If Me.ModelState.IsValid Then
Using oDb As Db.Context = Db.Context.Create
oMovie = oDb.Movies.Include(Function(Movie) Movie.Genres).SingleOrDefault(Function(Movie) Movie.Id = ViewModel.Id)
If oMovie Is Nothing Then
Edit = Me.HttpNotFound
Else
oUnchecked = Function(CheckBox) CheckBox.IsChecked = False
oSelector = Function(CheckBox) CheckBox.Id
oChecked = Function(CheckBox) CheckBox.IsChecked = True
oIdsRemove = ViewModel.GenreCheckBox.Where(oUnchecked).Select(oSelector)
oQueryRemove = Function(Genre) oIdsRemove.Contains(Genre.Id)
oActionRemove = Sub(Genre) oMovie.Genres.Remove(Genre)
oDb.Genres.Where(oQueryRemove).ForEach(oActionRemove)
oIdsAdd = ViewModel.GenreCheckBox.Where(oChecked).Select(oSelector)
oQueryAdd = Function(Genre) oIdsAdd.Contains(Genre.Id)
oActionAdd = Sub(Genre) oMovie.Genres.Add(Genre)
oDb.Genres.Where(oQueryAdd).ForEach(oActionAdd)
oMovie.ReleaseYear = ViewModel.ReleaseYear
oMovie.Rating = ViewModel.Rating
oMovie.Price = ViewModel.Price
oMovie.Title = ViewModel.Title
oDb.SaveChanges()
Edit = Me.RedirectToAction(NameOf(MoviesController.Index))
End If
End Using
Else
Edit = Me.View(ViewModel)
End If
End Function
</code></pre>
<p><strong>--EDIT--</strong></p>
<p>Here's the final version, after migration to the Repository Pattern and some more cleanup:</p>
<pre><code><HttpPost>
<ValidateAntiForgeryToken>
Public Function Edit(ViewModel As MovieViewModel) As ActionResult
Dim oAllRatings As List(Of Db.Rating)
Dim oAllGenres As List(Of Db.Genre)
Dim oAction As Action(Of Db.Genre)
Dim oMovie As Db.Movie
oAction = Nothing
oMovie = Me.Worker.Movies.RetrieveById(ViewModel.Id, Me.Relations)
If oMovie Is Nothing Then
Edit = Me.HttpNotFound
Else
oAllRatings = Me.Worker.Ratings.Retrieve.ToList
oAllGenres = Me.Worker.Genres.Retrieve.ToList
If Me.ModelState.IsValid Then
ViewModel.GenreCheckBox.ForEach(Sub(CheckBox)
Select Case CheckBox.IsChecked
Case False : oAction = Sub(Genre) oMovie.Genres.Remove(Genre)
Case True : oAction = Sub(Genre) oMovie.Genres.Add(Genre)
End Select
oAction.Invoke(oAllGenres.Single(Function(Genre) Genre.Id = CheckBox.Id))
End Sub)
oMovie.ReleaseYear = ViewModel.ReleaseYear
oMovie.RatingId = ViewModel.RatingId
oMovie.Price = ViewModel.Price
oMovie.Title = ViewModel.Title
Me.Worker.Movies.Update(oMovie)
Me.Worker.SaveChanges()
Edit = Me.RedirectToAction(Views.Index)
Else
Edit = Me.View(Me.GetMovieViewModel(oAllGenres, oAllRatings, oMovie))
End If
End If
End Function
</code></pre>
<p>Readability is vastly improved. I think we can call this good.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T20:33:56.220",
"Id": "489843",
"Score": "0",
"body": "I've included the C# tag to indicate that I have no preference. I don't want to restrict an answer over a language tag."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T23:57:42.917",
"Id": "249105",
"Score": "1",
"Tags": [
"c#",
"entity-framework",
"vb.net",
"asp.net-mvc"
],
"Title": "Addition/removal of entities in EF6 many-to-many architecture"
}
|
249105
|
<p>I have a function that adds a class name to a DOM element is met. The script provided works.</p>
<pre><code>function rm_row(){
var chk_inherent = arcapi.dataResult().columnNameToIndex('Inherent Risk');
var chk_residual = arcapi.dataResult().columnNameToIndex('Residual Risk')
var chk_perf = arcapi.dataResult().columnNameToIndex(arcapi.getSetting('Column name'));
d3.selectAll("#" + arcapi.chartId() + " .dataTables_scrollBody tbody tr").classed('removerow', function() {
const perf = this.children[chk_perf].innerHTML
const inherent = this.children[chk_inherent].innerHTML
const residue = this.children[chk_residual].innerHTML
const cf_regex = perf.replace(/[`~%]/gi, '');
// **** Check *****
const inh_isEmpty = inherent === '' || inherent === 'Null'
const rsk_isEmpty = residue === '' || residue === 'Null'
const perf_isInvalid = cf_regex < 0 || cf_regex > 100
/** Logic [if inherent is empty AND Residual risk is empty AND is perf value is incorrect = True] **/
return inh_isEmpty && rsk_isEmpty && perf_isInvalid === true
});
}
</code></pre>
<p>However, I feel it's long-winded. I feel this can be further optimized. What is the best approach/best practices to further improve myself and optimize my script so that it will be easy to maintain?</p>
<p>I have thought of creating an array and store all my variables in an array, but I feel this approach will be expensive.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:22:03.133",
"Id": "488233",
"Score": "2",
"body": "What do you mean by *\"...DOM element is met\"* (seems incomprehensible). E.g., is a word missing?"
}
] |
[
{
"body": "<blockquote>\n<p>However, I feel it's long-winded.</p>\n</blockquote>\n<p>To reduce the amount of repeated code, and to make it easier to adapt for different columns without writing the same sort of thing again 2 or 3 times, look for similarities across the different columns. For every column, you're calling <code>arcapi.dataResult().columnNameToIndex</code>, so you can make a function which, given a column name, calls that. You're also accessing the <code>this.children[index].innerHTML</code> for every index retrieved.</p>\n<p>One option is to use objects instead of multiple standalone variables. You can have an object indexed by variable names, whose values are the column indicies. Then, in the <code>selectAll</code> callback, you can construct an object with the same properties but with the text values you're interested in by using mapping the object's entries and passing into <code>Object.fromEntries</code>:</p>\n<pre><code>function rm_row() {\n const getIndex = columnName => arcapi.dataResult().columnNameToIndex(columnName);\n const columnIndiciesByName = {\n inherent: getIndex('Inherent Risk'),\n residual: getIndex('Residual Risk'),\n perf: getIndex(arcapi.getSetting('Column name')),\n };\n\n d3.selectAll("#" + arcapi.chartId() + " .dataTables_scrollBody tbody tr").classed('removerow', function() {\n const columnTextsByName = Object.fromEntries(\n Object.entries(columnIndicies).map(\n ([key, columnIndex]) => ([key, this.children[columnIndex].innerHTML])\n )\n );\n columnTextsByName.perf = columnTextsByName.perf.replace(/[`~%]/gi, '');\n // Then refer to columnTextsByName.inherent, etc\n</code></pre>\n<p>The above is just an option to consider. While this makes the code less repetitive and more flexible for future added or removed columns you might want to check, I'm not entirely convinced that it's a solid improvement over your current code <em>if</em> you're not expecting your current code to change. YMMV; you may consider your current code to be more readable, or not.</p>\n<p>Other possible improvements:</p>\n<p><strong>Don't use <code>var</code> in ES6:</strong> If you're going to write in ES6 syntax - which you should, it's great - there's no reason to use <code>var</code>, it has too many gotchas (such as function-scope hoisting and automatically being assigned to the global object on the top level) to be worth using. Always use <code>const</code> (or, when you must reassign the variable, <code>let</code>).</p>\n<p><strong>JS naming conventions</strong> The vast majority of professional JavaScript uses <code>camelCase</code> for functions and ordinary variables. <code>snake_case</code> is quite rare (and mixing snake case with camelCase in the <em>same variable name</em> is even weirder). Consider using <code>camelCase</code> everywhere that it's appropriate.</p>\n<p><strong><code>cf_regex</code></strong> On a similar note, name your variables appropriately: in your original code, <code>cf_regex</code> is not a regular expression, it's just a string which has had certain characters replaced. Better to call it something more accurate and longer (I don't have any idea what it's meant to be, and neither will other readers of the code given only this context)</p>\n<p>Something odd about the regex - you're using the case-insensitive flag <code>i</code>, but you're not matching any letters, so the flag isn't doing anything. Might as well remove it. Or, to make it clearer what's going on, if you're expecting the result to contain only numbers, match digits instead:</p>\n<pre><code>columnTextsByName.perf = Number(columnTextsByName.perf.match(/\\d+/)[0]);\n</code></pre>\n<p>(since you're going to be comparing with numbers later, it feels better to cast the variable being compared to a number too; it makes more sense and will make debugging a bit easier if problems arise later)</p>\n<p><strong><code>innerHTML</code> or <code>textContent</code>?</strong> Unless you're deliberately retrieving HTML markup, which doesn't look present here, if you just care about the text of a cell, it would be more appropriate to use <code>.textContent</code> rather than <code>.innerHTML</code>. It's faster too.</p>\n<p><strong>Semicolons</strong> You're using a few semicolons, but also missing a bunch. Unless you're an expert or use semicolons everywhere, you may eventually get tripped up by <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">Automatic Semicolon Insertion</a>. Consider using <a href=\"https://eslint.org/docs/rules/semi\" rel=\"noreferrer\">a linter</a>.</p>\n<p><strong>Performance</strong> You say</p>\n<blockquote>\n<p>I have thought of creating an array and store all my variables in an array, but I feel this approach will be expensive.</p>\n</blockquote>\n<p>On modern computers, the overhead of creating an array or object instead of multiple standalone variables is completely nonexistent. If using a particular data structure makes the code more maintainable (given whatever style you prefer), go ahead and do it. If you later find that there's a performance issue, feel free to go back and debug to find what exactly the bottleneck is, so you can figure out a more efficient method - but using an object or array will almost certainly not be the bottleneck. Try to avoid <a href=\"https://wiki.c2.com/?PrematureOptimization\" rel=\"noreferrer\">premature optimization</a>, or at least don't sacrifice code clarity for it unless you have to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:23:59.307",
"Id": "488234",
"Score": "0",
"body": "The question has been updated. Can you update the quoted parts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:46:18.297",
"Id": "488237",
"Score": "0",
"body": "How can you tell that it's ES6? I am aware of ES6 but I've only used ES5 so far (IE support reqs, only recently removed) and I cannot see anything non-ES5 except that there are some missing semicolons?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:47:11.727",
"Id": "488239",
"Score": "3",
"body": "@RBarryYoung He is using `const`, and `const` is ES6 syntax. In ES5 and before, there was only `var` to declare variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:49:54.277",
"Id": "488241",
"Score": "0",
"body": "Ah thanks. I guess I didn't realize that `const` was not ES5 (though it would explain why I couldn't get it to work on IE and thus stopped using it)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T03:27:43.453",
"Id": "249110",
"ParentId": "249107",
"Score": "11"
}
},
{
"body": "<h3>Refactor repetitive code into reusable functions.</h3>\n\n<p>The first thing that popped out to me was this pair of repetitive lines:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const inh_isEmpty = inherent === '' || inherent === 'Null'\nconst rsk_isEmpty = residue === '' || residue === 'Null'\n</code></pre>\n<p>Let's turn that into a function instead:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function isEmpty(string) {\n return string === '' || string === 'Null'\n}\n</code></pre>\n<p>Now we can get rid of the <code>inh_isEmpty</code> and <code>rsk_isEmpty</code> variables entirely, and just write <code>isEmpty(inherent)</code> and <code>isEmpty(residue)</code> instead. That may not be a huge saving in terms of raw line count, but it certainly looks cleaner. And you might be able to reuse the <code>isEmpty</code> function elsewhere in your code, too.</p>\n<p>But we're not done yet. These lines also look very repetitive:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var chk_inherent = arcapi.dataResult().columnNameToIndex('Inherent Risk');\nvar chk_residual = arcapi.dataResult().columnNameToIndex('Residual Risk')\nvar chk_perf = arcapi.dataResult().columnNameToIndex(arcapi.getSetting('Column name'));\n</code></pre>\n<p><sup>(BTW, why are you using <code>var</code> here but <code>const</code>/<code>let</code> elsewhere? There's very little point in mixing these two styles of variable declarations. Be consistent!\nFor that matter, your semicolon usage is also kind of random.)</sup></p>\n<p>…as do these lines below:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const perf = this.children[chk_perf].innerHTML\nconst inherent = this.children[chk_inherent].innerHTML\nconst residue = this.children[chk_residual].innerHTML\n</code></pre>\n<p>One option would be to refactor the repetitive parts of these lines into a function like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function getColumnHTML(row, columnName) {\n const index = arcapi.dataResult().columnNameToIndex(columnName)\n return row.children[index].innerHTML\n}\n</code></pre>\n<p>…and use it like e.g. this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const perf = getColumnHTML(this, arcapi.getSetting('Column name'))\nconst inherent = getColumnHTML(this, 'Inherent Risk')\nconst residual = getColumnHTML(this, 'Residual Risk')\n</code></pre>\n<p><sup>(BTW, I renamed your <code>residue</code> variable to <code>residual</code> to match the column name.)</sup></p>\n<p>While we're at it, let's define a function for your validity check too:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function isValidPercentage(string) {\n const percent = Number(string.replace(/[`~%]/g, ''))\n return percent >= 0 && percent <= 100\n}\n</code></pre>\n<p><sup>(<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than\" rel=\"nofollow noreferrer\">JavaScript string-to-number comparison</a> can be tricky, so I'd prefer explicitly running the filtered string through <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\"><code>Number()</code></a>. In particular, doing so ensures that any unparseable inputs get turned into NaN, which then fails the comparison. Also, the <code>/i</code> switch is useless for this regexp, so I removed it.)</sup></p>\n<p>With all these changes, your refactored code would look something like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function getColumnHTML(row, columnName) {\n const index = arcapi.dataResult().columnNameToIndex(columnName)\n return row.children[index].innerHTML\n}\n\nfunction isEmpty(string) {\n return string === '' || string === 'Null'\n}\n\nfunction isValidPercentage(string) {\n const percent = Number(string.replace(/[`~%]/gi, ''))\n return percent >= 0 && percent <= 100\n}\n\nfunction removeBadRows() { \n d3.selectAll("#" + arcapi.chartId() + " .dataTables_scrollBody tbody tr").classed('removerow', function() {\n const perf = getColumnHTML(this, arcapi.getSetting('Column name'))\n const inherent = getColumnHTML(this, 'Inherent Risk')\n const residual = getColumnHTML(this, 'Residual Risk')\n\n return isEmpty(inherent) && isEmpty(residual) && !isValidPercentage(perf)\n })\n}\n</code></pre>\n<p>Of course, you can also choose to move the helper functions somewhere else — e.g. inside the <code>removeBadRows</code> function, if you don't want to have them visible outside it, or alternatively into some reusable collection of utility functions.</p>\n<p>Ps. A few other changes I'd also suggest:</p>\n<ul>\n<li><p>If you don't specifically <em>need</em> the raw HTML code (and it looks like you don't), use <code>textContent</code> (or its effective synonym <code>innerText</code>) instead of <code>innerHTML</code> to access the text inside a DOM element. It's both easier (no need to worry about HTML parsing or entity decoding) and safer (less opportunities for accidental HTML injection bugs).</p>\n</li>\n<li><p>Use a stricter regexp match to validate the percentages. I can't suggest a specific regexp since I don't know exactly what your data looks like, but just as an example, if you only ever had an unsigned (integer or decimal) number followed by a <code>%</code> sign, you could do something like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function isValidPercentage(string) {\n const match = /^([0-9]+)(\\.[0-9]+)?%$/.exec(string)\n if (!match) return false\n const percent = Number(match[1] + match[2])\n return percent >= 0 && percent <= 100\n}\n</code></pre>\n</li>\n<li><p>Building DOM selectors via string concatenation is ugly and bug-prone. Avoid it if you can, minimize it if you can't. Consider e.g. doing something like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const chart = d3.select('#' + arcapi.chartId())\nchart.selectAll('.dataTables_scrollBody tbody tr').classed('removerow', // ...\n</code></pre>\n<p>or even:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const chart = d3.select(document.getElementById(arcapi.chartId()))\n// ...\n</code></pre>\n<p>(and consider saving the <code>chart</code> variable as a global constant, or wrap the code for computing it into yet another helper function to avoid repeating it).</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T14:39:11.760",
"Id": "249124",
"ParentId": "249107",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249110",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T02:39:39.273",
"Id": "249107",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Add class name to DOM element"
}
|
249107
|
<p>I have implemented the following code which works as intended. However, I would like to improve my code in terms of performance and efficiency</p>
<p><strong>Code in Question</strong></p>
<pre><code>import pandas as pd
from scipy.stats import norm
# data frame of length 40,000 rows, containing 25 columns
for indx in df.index:
matrix_ordered_first = df.loc[indx].rank(method='first',na_option='bottom')
matrix_ordered_avg = df.loc[indx].rank(method='average', na_option='bottom')
matrix_ordered_first.loc[df.loc[indx] == 0] = matrix_ordered_avg
matrix_computed = norm.ppf(matrix_ordered_first / (len(df.columns) + 1))
df.loc[indx] = matrix_computed.T
</code></pre>
<p><strong>A peak of the dataframe</strong></p>
<p>Here is a part view of my dataframe df:</p>
<pre><code>s s1 s2 s3 s4 ... s21 s23 s24 s25
0 NaN 5.406999 5.444658 4.640154 ... 4.633389 5.517850 NaN 6.121492
1 NaN 2.147866 1.758245 1.274754 ... 1.465129 1.200157 NaN 1.789203
2 2.872652 5.492498 2.547415 3.754654 ... 3.686420 1.540947 4.405961 1.715685
3 NaN 46.316837 27.197062 72.910797 ... NaN 46.812153 NaN NaN
4 1.365775 1.329316 1.852473 1.208155 ... 1.489296 1.313321 1.462968 1.249645
[5 rows x 25 columns]
</code></pre>
<p><strong>Explanation</strong></p>
<p>The code above is the part of a long python script in which this part runs slower than the other parts of the program. So what I am trying to do in the above code is to iterate over the data frame in a row-wise fashion. Then, for each row I have to perform a chain of pandas ranking operations followed by a statistical test equivalent to the "One-tail test”.Finally, transpose the matrix which will then be fed as a row for the data frame.</p>
<p>How can I improve this block of code in terms of efficiency, speed, and performance?</p>
<p>On a separate note, I not experienced in pandas so my code may seem amateur and for that I kindly seek your guidance.</p>
<p>Thank you so much in advance,</p>
|
[] |
[
{
"body": "<p>A basic principle of performance optimization in <code>pandas</code> is to avoid for-loops and vectorize as much computation as possible.</p>\n<p>Here is one version of improved code:</p>\n<pre><code>order_df = df.rank(axis=1, method="first", na_option="bottom")\norder_df_avg = df.rank(axis=1, method="average", na_option="bottom")\norder_df.where(df.astype(bool), order_df_avg, inplace=True)\nmatrix_computed = norm.ppf(order_df / (len(df.columns) + 1))\ndf[:] = matrix_computed\n</code></pre>\n<p>One potential further improvement is to compute only the orders that need to be updated rather than <code>order_df_avg</code>.</p>\n<pre><code>order_df = df.rank(axis=1, method="first", na_option="bottom")\nmask = (df == 0)\norders_to_update = np.broadcast_to(np.expand_dims(order_df[mask].mean(axis = 1), 1), df.shape)\norder_df.mask(mask, orders_to_update, inplace=True)\nmatrix_computed = norm.ppf(order_df / (len(df.columns) + 1))\ndf[:] = matrix_computed\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T20:06:16.797",
"Id": "488346",
"Score": "0",
"body": "Thank you so much for your answer @GZ0. Would you kindly explain what orders_to_update and order_df.mask(mask, orders_to_update, inplace=True) do? I would love you to elaborate more on why those operations make them more efficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:08:47.693",
"Id": "488349",
"Score": "0",
"body": "`order_df.mask(mask, orders_to_update, inplace=True)` is equivalent to `order_df.where(~mask, orders_to_update, inplace=True)` so their performances are more or less the same. The second solution *could* be faster because theoretically, the computation of `order_df_avg` has time complexity `O(nlogn)` -- here `n` is the number of columns -- while the computation of `orders_to_update` has time complexity `O(n)`. However, since `n` is relatively small in this case, you need to measure the performance on your data to see whether the second solution is actually faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:48:07.287",
"Id": "488351",
"Score": "0",
"body": "According to your code, the numbers that need to be updated in `order_df` are the orders of `0`s in `df`. So `orders_to_update` computes only the correct orders of `0`s (rather than doing a complete reranking) and broadcast it to the shape of `order_df`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:44:24.270",
"Id": "249159",
"ParentId": "249111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T04:37:30.717",
"Id": "249111",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"pandas"
],
"Title": "Multiple Pandas Ranking Operations within a Loop - Better Optimization and Performance"
}
|
249111
|
<p>I am making a simulator game "BEE HUNT SIMULATOR" and in that game we have bees and we have to collect pollen from different fields,this is fully command line game that means a typing game so i have made all things that should be there but the main thing is of collecting pollen out of specific storage for that i had tried this-:</p>
<pre><code>import time
global aa
aa = 15 # POWER OF ALL BEES WHICH ADDED IN POLLEN PER FUNCTION
global b
b = 100 # MAX POLLEN STORAGE
global honey
honey = 0 # IGNORE THIS VARIABLE
global pollen
pollen = 0 # POLLEN WHICH ADDS ON EACH FUNCTION AND DID NOT EXCEND THE STORAGE
def add():
global pollen
if pollen < b:
ss = aa + pollen
if ss > b:
pollen = b
elif ss <= b:
print("Collecting pollen....")
time.sleep(0.5)
pollen += aa
else:
print("Backpack Full convert it to honey or buy a new backapck.")
while True:
a = input("Press enter or any key: ")
if a == "s":
print(a,b,honey,"",pollen)
print(type(aa))
else:
add()
print("Pollen Collected-: ",pollen,"/",b)
time.sleep(1)
</code></pre>
<p>That code is fully working and its output is like this-:</p>
<pre><code>Press enter or any key:
Collecting pollen....
Pollen Collected-: 15 / 100
Press enter or any key:
Collecting pollen....
Pollen Collected-: 30 / 100
Press enter or any key:
</code></pre>
<p>But i think that this can bored peoples and they can easliy collect pollen so i need more system like this which should not bored peoples and they take enough time to collect pollen.</p>
<p>I am using pyCharm</p>
<p>This code is fully working i only need ideas for collecting pollen , so that players like to do and they dont get bored and they take time to collect pollen.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T09:35:40.027",
"Id": "488205",
"Score": "4",
"body": "I think that's a feature-request, not a request for a review of the code provided. Are you sure you're on the correct site? Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T12:36:54.677",
"Id": "488221",
"Score": "4",
"body": "I’m voting to close this question because it is not a request for review. Please take a look at the [help/on-topic]. \"Do I want feedback about any or all facets of the code?\""
}
] |
[
{
"body": "<p>As mentioned in comments above, your question is about gamedesign. But since you brought your code here already, here's a suggestion: use better variable names - <code>aa</code> and <code>b</code> are very non-descriptive and as the amount of code will grow, you'll have a hard time to understand what's going on there with variables like these.</p>\n<p>So instead of <code>b</code>, use something like <code>MAX_POLLEN</code>. When you'll see it in the code you'll immediately know what it is. And since it's UPPERCASE, which is a Python's convention for constants, you'll also know it won't change its value over time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T09:54:28.530",
"Id": "249119",
"ParentId": "249117",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T08:40:02.430",
"Id": "249117",
"Score": "0",
"Tags": [
"python"
],
"Title": "Simulator game in python"
}
|
249117
|
<p>This is web exercise 3.1.14. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Set pixel (i, j) to the color of the most frequent value among pixels
with Manhattan distance W of (i, j) in the original image.</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>import java.awt.Color;
public class OilPaintingFilter
{
public static int findNumberOfPixels(int distance)
{
int numberOfPixels = 4;
if (distance == 1) return numberOfPixels;
int increment = 8;
for (int i = 2; i <= distance; i++)
{
numberOfPixels += increment;
increment += 4;
}
return numberOfPixels;
}
public static Color[] findNeighboringColors(Picture picture, int col, int row, int distance)
{
int width = picture.width();
int height = picture.height();
Color[] pixels = new Color[findNumberOfPixels(distance)+1];
int counter = 0;
for (int j = col-distance; j <= col+distance; j++)
{
for (int i = row-distance; i <= row+distance; i++)
{
if ((Math.abs(col-j) + Math.abs(row-i)) <= distance)
{
pixels[counter] = picture.get(Math.abs(j)%width,Math.abs(i)%height);
counter++;
}
}
}
return pixels;
}
public static Color findMostFrequentNeighbor(Color[] pixels)
{
int[] colors = new int[pixels.length];
for (int i = 0; i < pixels.length; i++)
{
for (int j = 0; j < pixels.length; j++)
{
if (pixels[i].equals(pixels[j]))
{
colors[i]++;
}
}
}
int max = 0;
int index = 0;
for (int i = 0; i < pixels.length; i++)
{
if (colors[i] > max)
{
max = colors[i];
index = i;
}
}
return pixels[index];
}
public static Picture applyPaintingFilter(Picture picture, int distance)
{
int width = picture.width();
int height = picture.height();
Picture newPicture = new Picture(width,height);
for (int col = 0; col < width; col++)
{
for (int row = 0; row < height; row++)
{
Color newColor = findMostFrequentNeighbor(findNeighboringColors(picture, col, row, distance));
newPicture.set(col,row,newColor);
}
}
return newPicture;
}
public static void main(String[] args)
{
Picture picture = new Picture(args[0]);
int distance = Integer.parseInt(args[1]);
Picture newPicture = applyPaintingFilter(picture, distance);
newPicture.show();
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/Picture.html" rel="nofollow noreferrer">Picture</a> is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input (picture of a puffin taken from <a href="https://www.pinterest.com/pin/424886546098280605/?d=t&mt=login" rel="nofollow noreferrer">Pinterest</a>):</p>
<p><a href="https://i.stack.imgur.com/r5bFP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r5bFP.jpg" alt="enter image description here" /></a></p>
<p>with Manhattan distance = 10</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/zs9XU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zs9XU.png" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>Just my few cents...</p>\n<p>There is no reason to treat <code>distance == 1</code> differently:</p>\n<pre><code> public static int findNumberOfPixels(int distance)\n {\n int numberOfPixels = 0;\n int increment = 4;\n for (int i = 1; i <= distance; i++)\n {\n numberOfPixels += increment;\n increment += 4;\n }\n return numberOfPixels;\n }\n</code></pre>\n<p>Furthermore, this method returns the same output for the same input every time. But you are calling it once for every pixel. It might be better to compute this value only once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T16:20:46.387",
"Id": "488245",
"Score": "1",
"body": "Also he can remove cycle inside this function, because it makes fine arithmetic progression `numberOfPixels += lim * (increment + 2 * lim - 2);` where `lim` is `distance-1`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:47:41.710",
"Id": "249127",
"ParentId": "249121",
"Score": "2"
}
},
{
"body": "<p>That's a pretty cool application and it's nice to see the output!</p>\n<p>There are a few things I'd like to cover :</p>\n<ul>\n<li>Let's say you were to print the output of <code>findNumberOfPixels</code> everytime you ran it, you'd see that it <em>always</em> outputs the same number. Why? Because <code>distance</code> never changes and your function doesn't rely on anything else. What this means is that instead of computing the "number of pixels" everytime you want to find the color for pixel intensity I(X,Y), you could call <code>findNumberOfPixels</code> only once and reuse the same result. With that, I also think that your function could be evaluated in "one shot", meaning that there's clearly an equation that could get you the number of pixels without iterating on anything.</li>\n<li>The combination of <code>findNeighboringColors</code> and <code>findMostFrequentNeighbor</code> seem a little overkill. Although the code does what it's supposed to do, you iterate <em>a lot</em> of times to do something that is pretty simple. What if, instead of having a function that returns all the individual pixel intensities in the neighborhood and another function that finds the most frequent value, you had <strong>only one function</strong> that found the most repeated color in a neighborhood? You'd only need to change the code in <code>findNeighboringColors</code> to return say... a dictionary where <code>key=color, value=count</code>. Then you could pick the color that has the highest count (I'll leave you the exercise of implementing that function, but you pretty much have all the necessary tools in the <code>findNeighboringColors</code> function already!)</li>\n<li>Finally, I was wondering why the bottom of your image is also blue. There's nothing wrong with it considering it looks pretty, but it's also not how the code is supposed to behave. I figured it was related to the usage of modulos : <code>picture.get(Math.abs(j)%width,Math.abs(i)%height);</code>. While this works, you could be interesed in a technique called <strong>padding</strong> that often comes back in computer vision when you have to deal with neighborhood. The idea is that before starting to compute your image, you "grow" it by a certain number of pixels (in your case, <code>distance</code>). You should then set these pixels to the closest value from the real image. This way, you wouldn't need to use modulo and the blue line at the bottom would be black-ish, like expected.</li>\n</ul>\n<p>That's pretty much all, but I gotta say good job it looks really nice (both the output and the code)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:57:37.070",
"Id": "488322",
"Score": "0",
"body": "Thank you very much. I appreciate your feedback. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:22:51.093",
"Id": "249156",
"ParentId": "249121",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249156",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T10:19:12.763",
"Id": "249121",
"Score": "6",
"Tags": [
"java",
"beginner",
"image"
],
"Title": "Implementation of oil-painting filter for images"
}
|
249121
|
<p>I'm practicing back-end programming and NodeJS. As an exercise, I'm attempting to build a REST API for a MongoDB collection. I'm also learning to use the Express and Mongoose middle-wares, so that's what we'll use for the server and database respectively. Also practicing async / await to handle promises.</p>
<p>The requirements for this basic REST API and exercise are:</p>
<ul>
<li>Support get and delete on individual resources.</li>
<li>Support get and post on the resource collection.</li>
<li>Apply generalization and separation of concerns.</li>
<li>Protect against Mongo injection.</li>
<li>Use async / await to handle promises.</li>
</ul>
<p>This is the current working implementation:</p>
<hr />
<p>app.js</p>
<pre><code>const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const songRouter = require('./routes/song-router.js')
const mongurl = 'mongodb://localhost:27017/library'
const port = 3000
const app = express()
app.use(morgan('combined'))
app.use('/songs', songRouter)
mongoose.connect(mongurl, () => {
console.log(`\n >> Mongoose connected to ${mongurl}`)
})
app.listen(port, () => {
console.log(`\n >> Node listening to port ${port}`)
})
</code></pre>
<hr />
<p>models/song-model.js</p>
<pre><code>const mongoose = require('mongoose')
const song = {
name: {
type: String,
required: true
},
author: {
type: String,
required: true
},
key: String
}
const options = {
timestamps: true
}
const schema = new mongoose.Schema(song, options)
module.exports = mongoose.model('song', schema)
</code></pre>
<hr />
<p>routes/song-router.js</p>
<pre><code>const express = require('express')
const control = require('../controllers/song-control.js')
const router = express.Router()
router.use(express.json())
router
.route('/')
.get(control.getAll)
.post(control.postOne)
router
.route('/:songId')
.get(control.getOne)
.delete(control.deleteOne)
module.exports = router
</code></pre>
<hr />
<p>controllers/song-control.js (version 1, without generalization)</p>
<pre><code>const songModel = require('../models/song-model.js')
exports.getAll = async (req, res, nxt) => {
try {
const allSongs = await songModel.find({})
res.status(200).json(allSongs)
} catch (err) {
nxt(err)
}
}
exports.getOne = async (req, res, nxt) => {
try {
const oneSong = await songModel.findById(req.params.songId)
res.status(200).json(oneSong)
} catch (err) {
nxt(err)
}
}
exports.postOne = async (req, res, nxt) => {
try {
const postedSong = await songModel.create(req.body)
res.status(200).json(postedSong)
} catch (err) {
nxt(err)
}
}
exports.deleteOne = async (req, res, nxt) => {
try {
const deletedSong = await songModel.findByIdAndDelete(req.params.songId)
res.status(200).json(deletedSong)
} catch (err) {
nxt(err)
}
}
</code></pre>
<hr />
<p>controllers/song-control.js (version 2, first attempt at generalization)</p>
<pre><code>const songModel = require('../models/song-model.js')
exports.getAll = buildMongoFunction('find')
exports.getOne = buildMongoFunction('findById', true)
exports.postOne = buildMongoFunction('create', false)
exports.deleteOne = buildMongoFunction('findByIdAndDelete', true)
function buildMongoFunction (funName, argIsParam) {
return async (req, res, nxt) => {
const arg = argIsParam ? req.params.songId : req.body
try {
const reply = await songModel[funName](arg)
res.status(200).json(reply)
} catch (err) {
nxt(err)
}
}
}
</code></pre>
<hr />
<hr />
<p>I'm looking forward to all kinds and types of feedback: style, bugs, anti-patterns, ways to do this more concise / maintainable / redeable, conventions, best practices; whatever you think can be improved, please share.</p>
<p>I have some specific questions, but please feel free to ignore these and comment on something else!</p>
<ul>
<li><p>The generalization of controllers/song-control.js feels hacky. Is there a better way to implement the generalization of that pattern? How'd you do it?</p>
</li>
<li><p>How well are these concepts being applied: generalization, separation of concerns? Would you separate responsibilities even further? Or are they too separated? Can something be further generalized?</p>
</li>
<li><p>How well is async / await being used?</p>
</li>
<li><p>Should I sanitize inputs? Or is enforcing Mongoose models and schemas protection enough against Mongo injections?</p>
</li>
<li><p>Seems that <a href="https://mongoosejs.com/docs/queries.html#queries-are-not-promises" rel="nofollow noreferrer">Mongoose queries do not return promises</a>. Is the async / await code here doing any actual asynchronous job?</p>
</li>
<li><p>What would you recommend doing in a different way?</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>This is not a full response to your question but what I could quickly jot down while looking at your post. Sorry, no insights to share. I would discourage you from choosing this answer in case someone with a more fleshed out response decides to come along and provide more value.</p>\n<p>I looked over the song controller. I considered style and organization choices and decided on the following. This is more about javascript styling in general, not necessarily about node, or mongoose, or server-side technology.</p>\n<p>Please take a look and see if it helps you think differently about anything you are looking forward to understanding.</p>\n<pre><code>const buildMongoFunction = name => async (req, res, nxt) => {\n const { params: { songId }, body } = req;\n \n try {\n const needsSongID = ['findById', 'findByIdAndDelete'].includes(name);\n res.status(200).json(await songModel[name](needsSongID ? songID : body));\n } catch (error) { nxt(error); }\n};\n\nconst toExports = ['find', 'findById', 'create', 'findByIdAndDelete']\n .reduce((toExport, name) => ({ ...toExport, [name]: buildMongoFunction(name) }), {});\n\nObject.assign(exports, toExports);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T01:12:28.683",
"Id": "249297",
"ParentId": "249122",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249297",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T10:20:25.193",
"Id": "249122",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"mongodb",
"express.js",
"mongoose"
],
"Title": "Basic REST API for manipularing a MongoDB collection, using Node, Express, and Mongoose"
}
|
249122
|
<p>I have a pandas dataframe, <code>my_calculation</code>, that is a Cartesian product of 4 different categories (Name, Freqset, Formula, and Location) and two additional <code>Address</code> categories. There are 3 different names, 12 different frequency sets, 14 different formulas, and 13 different locations making 6552 rows. There can be any number of possible addresses (their possible states are stored in a different frame), but in this frame, for any location there is only one possible <code>Address1</code> and one possible <code>Address2</code>.</p>
<pre><code>0 Name Freqset Formula Location Address1 Address2
1 Jeff freqset1 form1 New York Box 12 Box 15
2 Jeff freqset1 form1 Buffalo Box 60 Box 11
3 Jeff freqset1 form1 Miami Box 10 Box 80
4...............................................................
................................................................
6551 Leroy freqset12 form14 Charleston Box 100 Box 28
</code></pre>
<p>I only made the dataframe in this manner because that's how I would logically set it up in a db table for maintainability. If there is a more efficient structure for this dataframe, or an easier structure to work with, please let me know.</p>
<p>I need to add a column for frequencies for each address (<code>Freq1</code> for <code>Address1</code> and <code>Freq2</code> for <code>Address2</code>) and then a column for a probability calculation I will call <code>Calculation Result</code> that is based on the <code>Formula</code> column (I haven't addressed this yet). I want to use this frame as an index to do what will amount to millions of additional calculations. My thinking is that a dataframe of values to choose millions of results from SHOULD be more efficient than doing millions of calculations on the fly. If this is flawed thinking, please let me know.</p>
<p>The frequencies are stored in a dictionary of dataframes. An example of one dataframe:</p>
<pre><code> Address New York Buffalo Miami
0 Box 1 0.24560 0.95000 0.25000
1 Box 2 0.00100 0.45190 0.65091
.............................................
n Box n 0.45450 0.20341 0.11110
</code></pre>
<p>They are accessed like this:</p>
<pre><code>freq_dict.freq['Freqset1']
freq_dict.freq['Freqset2']
</code></pre>
<p>etc...</p>
<p>The frequencies come out of excel automatically in this structure and I am unsure if any manipulation of this structure from its current state will make things any easier or more efficient.</p>
<p>Here is the only way I can get the <code>Freq1</code> and <code>Freq2</code> columns in <code>my_calculation</code> to populate. I'm almost positive this isn't the way to go about things.</p>
<pre><code>import numpy as np
import pandas as pd
#arrays of Cartesian categories
names = np.array(['Jeff', 'Jenn', 'Leroy'])
locations = np.array(['New York', 'Buffalo', 'Miami', 'Tampa', 'Boston',
'Pittsburgh', 'Portland', 'Seattle', 'Toronto',
'Witchita', 'Austin', 'Bangor', 'Charleston'])
freqsets = np.array(['freqset1','freqset2','freqset3','freqset4',
'freqset5','freqset6','freqset7','freqset8',
'freqset9','freqset10','freqset11','freqset12'])
formulas = np.array(['form1', 'form2', 'form3', 'form4', 'form5',
'form6', 'form7', 'form8', 'form9', 'form10',
'form11', 'form12', 'form13', 'form14'])
temp_arr1 = np.zeros((6552, ))
temp_arr2 = np.zeros((6552, ))
i = 0
for name in names:
for location in locations:
for freqset in freqsets:
for formula in formulas:
temp_arr1[i] = freq_dict.freq[freqset].query('Address ==' + my_calculation['Address1'][i])[my_calculation['Location'][i]].item()
temp_arr1[i] = freq_dict.freq[freqset].query('Address ==' + my_calculation['Address2'][i])[my_calculation['Location'][i]].item()
i+=1
my_calculation['Freq1'] = pd.Series(temp_arr1)
my_calculation['Freq2'] = pd.Series(temp_arr2)
</code></pre>
<p>Now <code>my_calculation</code> dataframe looks like this (last column not part of code yet):</p>
<pre><code>0 Name Freqset Formula Location Address1 Address2 Freq1 Freq2 Calculation Result
1 Jeff freqset1 form1 New York Box 12 Box 15 0.00020 0.23140 TBD
2 Jeff freqset1 form1 Buffalo Box 60 Box 11 0.05121 0.15432 TBD
3 Jeff freqset1 form1 Miami Box 10 Box 80 0.12120 0.54230 TBD
4......................................................................................
.......................................................................................
6551 Leroy freqset12 form14 Charleston Box 100 Box 28 0.32001 0.00023 TBD
</code></pre>
<p>In the long run I want to be able to create this table quickly because I want to do it thousands of times. Right now it takes about 28 seconds on my machine to do just one, and I have yet to populate a <code>Calculation Result</code> column.</p>
<p>Let me know if something doesn't quite run correctly. I am transcribing code across machines and can correct easily.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T18:40:18.300",
"Id": "488263",
"Score": "0",
"body": "Before this gets away from me, I already see one place I can improve. I'm doing 6552 queries of the dictionary. I should be able to reduce this to 312. (ie 12 freqsets x 26 addresses)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:45:20.153",
"Id": "249126",
"Score": "2",
"Tags": [
"python",
"numpy",
"pandas"
],
"Title": "Populating 2 columns in a dataframe with frequencies from a dictionary of dataframes"
}
|
249126
|
<p>I am trying to write a program to get the count of the maximum number in an array of integers. The below code is what I have written. Is there any better way to write this code in Ruby?</p>
<pre><code>def max_number_count(my_array)
max_num, max_num_count = my_array.inject([0, 0]) {
|arr, age| age > arr[0] ?
[arr[0] = age, arr[1] = 1] : age == arr[0] ?
arr[1] += 1 : arr[1] = arr[1];
arr
}
max_num_count
end
max_number_count([1,2,3,3,3])
#3
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Your method shouldn't call the given array <code>my_array</code>. It's not the method's array, it's the <em>caller's</em> array. Just call it <code>array</code>, which is also shorter, so less clutter.</p>\n<p>And you're making it very complicated. The array already offers all you need:</p>\n<pre><code>def max_number_count(array)\n array.count(array.max)\nend\n</code></pre>\n<p>That's also <em>much</em> faster:</p>\n<pre><code> user system total real\nyours 1.696091 0.034977 1.731068 ( 3.476805)\nmine 0.074057 0.000000 0.074057 ( 0.131310)\n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>require 'benchmark'\n\ndef max_number_count1(my_array)\n max_num, max_num_count = my_array.inject([0, 0]) { \n |arr, age| age > arr[0] ? \n [arr[0] = age, arr[1] = 1] : age == arr[0] ?\n arr[1] += 1 : arr[1] = arr[1]; \n arr \n }\n max_num_count\nend\n\ndef max_number_count2(array)\n array.count(array.max)\nend\n\nn = 5\narray = (1..1000).to_a * 1000\nBenchmark.bmbm do |x|\n x.report("yours") { n.times { max_number_count1(array) } }\n x.report("mine") { n.times { max_number_count2(array) } }\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T01:22:55.077",
"Id": "488291",
"Score": "0",
"body": "Is Ruby smart enough to optimize this into a single pass over the array? (If not, I suppose interpreter overhead would kill any attempt to manually loop over the array and check `a[i] >= current_max`, then choose whether it's a new max + reset count to 1 or increment count of same max. In a compiled or JITed language that one-pass way would probably be fastest. Although with SIMD a 2-pass way could be faster for small arrays, like maybe a dozen SIMD vectors, to avoid needing to branch on each SIMD chunk containing a new max.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T01:59:13.517",
"Id": "488292",
"Score": "0",
"body": "@PeterCordes I don't know Ruby much, but I highly doubt it'll make it single-pass. But that's exactly why I felt compelled to add the benchmark, for the people who think that's automatically slower than single-pass (I don't think you do, I just mean I've seen people say that many times). Manual [used to be faster](https://stackoverflow.com/q/34695364/1672429) for `min` because the builtin used to be slow, but apparently that got fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T13:04:39.427",
"Id": "488419",
"Score": "0",
"body": "@superbrain I actually thought that it would be slower if I find max and then count the max. So I wrote the above code. Thanks for your answer. I learnt a very simple way to implement. But I was also looking to implement the algorithm. That is also the reason why I wrote it like that. But yes I did not specify it in the question. So that is my mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T13:13:45.750",
"Id": "488420",
"Score": "0",
"body": "@Lax_Sam Yeah, I was kinda hoping someone else would re-implement it similar to how you did, just better (i.e., also without using the builtin `max` and `count`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T20:49:45.900",
"Id": "491172",
"Score": "1",
"body": "@PeterCordes: Most language implementations are not able able to rewrite algorithms. GHC has some hand-written rewrite rules in its optimizer for things like map-fusion that *might* even trigger in this case, but I feel that hand-written pattern-rewrite rules are somewhat cheating. Supercompilation can do amazing things, but the only supercompilers I know of are REFAL (the language for which supercompilation was invented), a Java compiler by the designer of REFAL, and Supero, a long-since abandoned grad-student research compiler for Haskell. I don't know of any Ruby supercompilers. However, …"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T20:53:17.567",
"Id": "491173",
"Score": "1",
"body": "… both the RPython framework and the Truffle framework come pretty darn close, and there is an (abandoned) Ruby implementation in RPython called Topaz, and a very much alive TruffleRuby. The TruffleRuby guys have shown some quite amazing things. In one example, TruffleRuby compiled a complex Ruby program using dynamic techniques and `Hash` lookup into a single constant. In another example, they were able to beat a YARV C extension with pure Ruby. I myself have seen 1000 x speedups over Ruby 2.7 with JIT."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T22:01:24.557",
"Id": "491181",
"Score": "0",
"body": "@JörgWMittag: I didn't really think it was likely anything could rewrite the algorithm to be one pass. I just find it disappointing when languages only provide a few efficient building blocks, but there's no way to combine them into an optimal algorithm; your options are multiple passes over the data, or manually iterate and get killed by interpreter overhead. Even in C, `memcmp` doesn't return the *position* of the mismatch, so if you want that you need to either search manually (doesn't auto-vectorize), or use the optimized SIMD library function in small chunks. TL:DR: most languages suck."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T17:50:47.187",
"Id": "249132",
"ParentId": "249128",
"Score": "7"
}
},
{
"body": "<p>Ruby's <code>Enumerable</code> has a large number of useful methods, which often have additional behaviours when you pass in parameters or a block. It's well worth the time invested in reading about them, as pretty much anything you want to do with an iterator has already been implemented. I learned something new about <code>count</code> today from @superb rain, because I'd originally gone with</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def count_max(ary)\n ary.select { |e| e == ary.max }.count\nend\n</code></pre>\n<p>then decided that executing <code>ary.max</code> on every iteration was a waste of machine time and changed it to</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def count_max(ary)\n max = ary.max\n ary.select { |e| e == max }.count\nend\n</code></pre>\n<p>only to discover that <code>count(n)</code> is a shorthand for <code>ary.select { |e| e == n }.count</code>, which is how we arrive at the achingly-elegant <code>array.count(array.max)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T22:27:35.890",
"Id": "488277",
"Score": "0",
"body": "Another way: `ary.count { |e| e == max }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T06:23:08.313",
"Id": "488678",
"Score": "0",
"body": "Or in point-free style `ary.count(&max.method(:==))`, taking advantage of the symmetry of equality."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T22:20:15.160",
"Id": "249136",
"ParentId": "249128",
"Score": "0"
}
},
{
"body": "<p>Following <a href=\"https://codereview.stackexchange.com/questions/249128/better-way-to-count-the-number-of-occurrences-of-a-maximum-number-in-the-array-i/249132#comment491173_249132\">the discussion in the comments</a> to <a href=\"https://codereview.stackexchange.com/a/249132/1581\">superb rain's answer</a>, I got interested to</p>\n<ul>\n<li>Write an extremely low-level looping answer and</li>\n<li>Benchmark all the versions on several different Ruby implementations</li>\n</ul>\n<p>Another thing I did was to run a linter (<a href=\"https://rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a>) on the OP's code from the question and see what happens.</p>\n<p>So, let's start with Rubocop. When I ran Rubocop on the OP's code, it detected <em>28 offenses</em>, of which it could automatically correct <em>25</em>. Most of them were related to indentation or other layout issues, I will ignore those. Here is the non-layout related ones that were auto-corrected:</p>\n<pre class=\"lang-none prettyprint-override\"><code>test2.rb:2:39: C: [Corrected] Style/EachWithObject: Use each_with_object instead of inject.\n max_num, max_num_count = my_array.inject([0, 0]) {\n ^^^^^^\ntest2.rb:3:43: C: [Corrected] Style/MultilineTernaryOperator: Avoid multi-line ternary operators, use if or unless instead.\n |arr, age| age > arr[0] ? ...\n ^^^^^^^^^^^^^^\n\ntest2.rb:4:3: W: Lint/UselessAssignment: Useless assignment to variable - max_num. Use _ or _max_num as a variable name to indicate that it won't be used.\n max_num, max_num_count = my_array.each_with_object([0, 0]) do |age, arr|\n ^^^^^^^\n\ntest2.rb:4:61: C: [Corrected] Style/NestedTernaryOperator: Ternary operators must not be nested. Prefer if or else constructs instead.\n [arr[0] = age, arr[1] = 1] : age == arr[0] ? ...\n ^^^^^^^^^^^^^^^\n\ntest2.rb:7:3: C: [Corrected] Style/MultilineTernaryOperator: Avoid multi-line ternary operators, use if or unless instead.\n age == arr[0] ? ...\n ^^^^^^^^^^^^^^^\n</code></pre>\n<p>And this is what the result looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def max_number_count(my_array)\n max_num, max_num_count = my_array.each_with_object([0, 0]) do |age, arr|\n if age > arr[0]\n [arr[0] = age, arr[1] = 1]\n else\n if age == arr[0]\n arr[1] += 1\n else\n arr[1] = arr[1]\n end\n end\n end\n max_num_count\nend\n</code></pre>\n<p>There are essentially two things that Rubocop did. For one, it replaced the <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_with_object\" rel=\"nofollow noreferrer\"><code>Enumerable#inject</code></a> with <code>Enumerable#each_object</code>. <code>inject</code> is a functional method, and it makes sense to use it when you program in a functional style and want to return a <em>new</em> accumulator after each invocation of the block. But here, you <em>mutate</em> the accumulator, and there is a method which expresses this better, namely <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_with_object\" rel=\"nofollow noreferrer\"><code>Enumerable#each_with_object</code></a>.</p>\n<p>The other thing it did was to replace the <em>conditional operator</em> (<code>?</code> / <code>:</code>) with the conditional expression (<code>if</code> / <code>then</code> / [<code>else</code>]). Here's my short rant on the conditional operator in Ruby: the conditional operator is needed in C, because the conditional statement (<code>if</code>) is a <em>statement</em>, and thus you need the conditional operator because operators are <em>expressions</em>. So, without the conditional operator, it would be impossible to write a conditional expression.</p>\n<p>But in Ruby, the conditional expression already <em>is</em> … well … an <em>expression</em>! Duh! So, the conditional operator is <em>never</em> needed. You can <em>always</em> replace</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo ? bar : baz\n</code></pre>\n<p>with</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>if foo then bar else baz end\n</code></pre>\n<p>There is <em>never</em> a need to use the conditional operator. Never.</p>\n<p>And there is the additional advantage that the precedence of the conditional expression is somewhat more sensible than the precedence of the conditional operator. If you pop on over to the Ruby tag on Stack Overflow, you will find quite a number of questions where the problem was that the OP got confused about the precedence of the conditional operator. And mostly, the answers either suggest inserting parentheses or rewriting the expression altogether, but actually, in every single case, the problem would <em>also</em> be solved by doing a completely stupid search&replace and replace the conditional operator with the conditional expression, because the conditional expression has <em>exactly</em> the precedence you would expect it to have.</p>\n<p>That's why I, in general, <em>always</em> prefer the conditional expression over the conditional operator. Don't you think that the version that Rubocop produced is much easier to read than the original?</p>\n<p>So, let's look at what Rubocop <em>didn't</em> fix automatically:</p>\n<pre class=\"lang-none prettyprint-override\"><code>test2.rb:3:1: C: Metrics/MethodLength: Method has too many lines. [12/10]\ndef max_number_count(my_array) ...\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\ntest2.rb:4:3: W: Lint/UselessAssignment: Useless assignment to variable - max_num. Use _ or _max_num as a variable name to indicate that it won't be used.\n max_num, max_num_count = my_array.each_with_object([0, 0]) do |age, arr|\n ^^^^^^^\n\ntest2.rb:8:7: C: Style/IfInsideElse: Convert if nested inside else to elsif.\n if age == arr[0]\n ^^\n</code></pre>\n<p>So, the method is too long, there is an unused variable, and the conditional expression can be simplified.</p>\n<p>I prefer to start with the stupid mechanical things first, which is why I am going to ignore the first for now. (It often turns out that when you follow the stupid mechanical advice given by Rubocop, the more complex ones also go away.)</p>\n<p>The unused variable is easy: Ruby warns about unused variables, which is a <em>good thing</em>™️ because it almost always indicates a bug. If, for some reason, you really, absolutely <em>must</em> have an unused variable, there is a convention in the Ruby community that is also followed by Ruby itself, that the name of an unused variable should start with <code>_</code> or <em>be</em> just <code>_</code>.</p>\n<p>Ruby will not issue unused variable warnings for variables starting with <code>_</code>, and also, it will allow you to use <code>_</code> multiple times as a parameter, which would otherwise be an error:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def foo(bar, bar) end\n# SyntaxError\n</code></pre>\n<p>but</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def foo(_, _) end\n</code></pre>\n<p>is valid.</p>\n<p>The last suggestion is to replace the <code>if</code> nested inside the <code>else</code> with an <code>elsif</code>.</p>\n<p>So, if we do that, we end up with this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def max_number_count(my_array)\n _, max_num_count = my_array.each_with_object([0, 0]) do |age, arr|\n if age > arr[0]\n [arr[0] = age, arr[1] = 1]\n elsif age == arr[0]\n arr[1] += 1\n else\n arr[1] = arr[1]\n end\n end\n max_num_count\nend\n</code></pre>\n<p>And this has actually also fixed the <em>too many lines</em> offense, without us having to do anything.</p>\n<p>Now, isn't this much more readable than the original? And the powerful things is: we didn't have to do <em>anything</em>! There was no thinking involved. Almost everything was auto-corrected by Rubocop, and even for the issues that weren't auto-corrected we just stupidly followed the instructions.</p>\n<p>And now that we have some nice, readable code without the doubly-nested conditional operator, it's easy to spot that the <code>else</code> branch isn't actually doing anything! It is completely useless, so let's just delete it.</p>\n<p>We also see that we are needlessly constructing an array in the <code>if</code> branch that we are not using anywhere, so can get rid of that, too.</p>\n<p>And lastly, we see that <code>arr[0]</code> is computed twice, so we pull that out into a variable, and this is the result:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def max_number_count(my_array)\n _, max_num_count = my_array.each_with_object([0, 0]) do |age, arr|\n max = arr[0]\n\n if age > max\n arr[0] = age\n arr[1] = 1\n elsif age == max\n arr[1] += 1\n end\n end\n\n max_num_count\nend\n</code></pre>\n<p>I mentioned in the beginning that I wrote a very low-level, completely <em>un</em>-Ruby version as well, that guarantees only one pass and uses low-level loops instead of high-level iterators, and this is what it looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def max_count(array)\n size = array.size\n num = idx = 1\n max = array.first\n\n while idx < size\n el = array[idx]\n if el > max\n max = el\n num = 1\n elsif el == max\n num += 1\n end\n\n idx += 1\n end\n\n num\nend\n</code></pre>\n<p>I took</p>\n<ul>\n<li>the OP's original version from <a href=\"https://codereview.stackexchange.com/q/249128/1581\">the question</a>,</li>\n<li>the Rubocop-ified version from this answer,</li>\n<li>superb rain's elegant one-liner from their answer,</li>\n<li>the first version from <a href=\"https://codereview.stackexchange.com/a/249136/1581\">nullTerminator's answer</a></li>\n<li>the improved version from nullTerminator's answer</li>\n<li><a href=\"https://codereview.stackexchange.com/questions/249128/better-way-to-count-the-number-of-occurrences-of-a-maximum-number-in-the-array-i/249132#comment488277_249136\">superb rain's comment</a> to nullTerminator's answer, and</li>\n<li><a href=\"https://codereview.stackexchange.com/questions/249128/better-way-to-count-the-number-of-occurrences-of-a-maximum-number-in-the-array-i/249132#comment488678_249136\">my response</a></li>\n</ul>\n<p>and benchmarked them on</p>\n<ul>\n<li><a href=\"http://atdot.net/yarv\" rel=\"nofollow noreferrer\">YARV</a> 2.7.2 (default)</li>\n<li>YARV 2.7.2 (with <code>--jit</code>)</li>\n<li>YARV 3.0.0-preview1 (default)</li>\n<li>YARV 3.0.0-preview1 (with <code>--jit</code>)</li>\n<li><a href=\"https://www.jruby.org/\" rel=\"nofollow noreferrer\">JRuby</a> 9.2.13.0 running on <a href=\"https://openjdk.java.net/\" rel=\"nofollow noreferrer\">OpenJDK</a> 14.0.2 (default, i.e. on the Client VM)</li>\n<li>JRuby 9.2.13.0 running on OpenJDK 14.0.2 (with <code>--server</code>, i.e. on the Server VM)</li>\n<li><a href=\"https://github.com/oracle/truffleruby/\" rel=\"nofollow noreferrer\">TruffleRuby</a> from <a href=\"https://www.graalvm.org/\" rel=\"nofollow noreferrer\">GraalVM</a> 20.2 (default, i.e. native)</li>\n<li>TruffleRuby from GraalVM 20.2 (with <code>--jvm</code>, i.e. running on OpenJDK 14.0.2)</li>\n</ul>\n<p>I used the test data and test parameters from superb rains answer for my benchmarks, but I used <a href=\"https://github.com/evanphx/benchmark-ips\" rel=\"nofollow noreferrer\">benchmark-ips</a> as the benchmark harness. Unfortunately, there are no really good benchmark harnesses for Ruby (comparable to e.g. <a href=\"https://openjdk.java.net/projects/code-tools/jmh/\" rel=\"nofollow noreferrer\">jmh</a>), but benchmark-ips is at least not completely horrible:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>require 'benchmark/ips'\n\narray = (1..1000).to_a * 1000\n\nBenchmark.ips do |x|\n x.config(time: 30, warmup: 10)\n\n x.report('Lax_Sam') do\n max_num, max_num_count = array.inject([0, 0]) {\n |arr, age| age > arr[0] ?\n [arr[0] = age, arr[1] = 1] : age == arr[0] ?\n arr[1] += 1 : arr[1] = arr[1];\n arr\n }\n max_num_count\n end\n\n x.report('Rubocop') do\n _, max_num_count = array.each_with_object([0, 0]) do |age, arr|\n max = arr[0]\n\n if age > max\n arr[0] = age\n arr[1] = 1\n elsif age == max\n arr[1] += 1\n end\n end\n\n max_num_count\n end\n\n x.report('superb rain') do\n array.count(array.max)\n end\n\n x.report('nullTerminator 1') do\n array.select { |e| e == array.max }.count\n end\n\n x.report('nullTerminator 2') do\n max = array.max\n array.select { |e| e == max }.count\n end\n\n x.report('superb rain comment') do\n max = array.max\n array.count { |e| e == max }\n end\n\n x.report('Jörg comment') do\n max = array.max\n array.count(&max.method(:==))\n end\n\n x.report('alt Jörg comment') do\n array.count(&array.max.method(:==))\n end\n\n x.report('Jörg') do\n size = array.size\n num = idx = 1\n max = array.first\n\n while idx < size\n el = array[idx]\n if el > max\n max = el\n num = 1\n elsif el == max\n num += 1\n end\n\n idx += 1\n end\n\n num\n end\n\n x.compare!\nend\n</code></pre>\n<p>Unfortunately, I had to disable nullTerminator's first solution because it would have taken hours with the test data from superb rain's benchmark. (Quadratic complexity at its finest.)</p>\n<p>Here are the results:</p>\n<pre class=\"lang-none prettyprint-override\"><code>YARV 2.7.2\nWarming up --------------------------------------\n Lax_Sam 1.000 i/100ms\n Rubocop 1.000 i/100ms\n superb rain 9.000 i/100ms\n nullTerminator 2 2.000 i/100ms\n superb rain comment 2.000 i/100ms\n Jörg comment 2.000 i/100ms\n alt Jörg comment 2.000 i/100ms\n Jörg 2.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 11.857 (± 0.0%) i/s - 356.000 in 30.058305s\n Rubocop 14.472 (± 6.9%) i/s - 429.000 in 30.143883s\n superb rain 103.444 (± 5.8%) i/s - 3.096k in 30.021317s\n nullTerminator 2 26.671 (± 0.0%) i/s - 800.000 in 30.004352s\n superb rain comment 26.331 (± 3.8%) i/s - 790.000 in 30.033501s\n Jörg comment 20.527 (± 4.9%) i/s - 616.000 in 30.057100s\n alt Jörg comment 20.492 (± 4.9%) i/s - 616.000 in 30.083978s\n Jörg 30.119 (± 3.3%) i/s - 904.000 in 30.027649s\n\nComparison:\n superb rain: 103.4 i/s\n Jörg: 30.1 i/s - 3.43x (± 0.00) slower\n nullTerminator 2: 26.7 i/s - 3.88x (± 0.00) slower\n superb rain comment: 26.3 i/s - 3.93x (± 0.00) slower\n Jörg comment: 20.5 i/s - 5.04x (± 0.00) slower\n alt Jörg comment: 20.5 i/s - 5.05x (± 0.00) slower\n Rubocop: 14.5 i/s - 7.15x (± 0.00) slower\n Lax_Sam: 11.9 i/s - 8.72x (± 0.00) slower\n</code></pre>\n<p>This is expected. YARV does not have any sophisticated optimizations, so an implementation that simply calls into internal C functions should be much faster. Of the implementations that use significant amounts of Ruby code, I also would have expected mine to be the fastest, because it is the most-straightforward one.</p>\n<pre class=\"lang-none prettyprint-override\"><code>Warming up --------------------------------------\n Lax_Sam 1.000 i/100ms\n Rubocop 2.000 i/100ms\n superb rain 11.000 i/100ms\n nullTerminator 2 3.000 i/100ms\n superb rain comment 3.000 i/100ms\n Jörg comment 2.000 i/100ms\n alt Jörg comment 2.000 i/100ms\n Jörg 3.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 16.548 (± 0.0%) i/s - 497.000 in 30.059499s\n Rubocop 20.852 (± 4.8%) i/s - 626.000 in 30.050299s\n superb rain 106.282 (± 3.8%) i/s - 3.190k in 30.058346s\n nullTerminator 2 31.768 (± 3.1%) i/s - 954.000 in 30.072028s\n superb rain comment 30.981 (± 3.2%) i/s - 930.000 in 30.064810s\n Jörg comment 20.582 (± 4.9%) i/s - 618.000 in 30.065961s\n alt Jörg comment 20.679 (± 4.8%) i/s - 620.000 in 30.016374s\n Jörg 30.319 (± 3.3%) i/s - 909.000 in 30.024552s\n\nComparison:\n superb rain: 106.3 i/s\n nullTerminator 2: 31.8 i/s - 3.35x (± 0.00) slower\n superb rain comment: 31.0 i/s - 3.43x (± 0.00) slower\n Jörg: 30.3 i/s - 3.51x (± 0.00) slower\n Rubocop: 20.9 i/s - 5.10x (± 0.00) slower\n alt Jörg comment: 20.7 i/s - 5.14x (± 0.00) slower\n Jörg comment: 20.6 i/s - 5.16x (± 0.00) slower\n Lax_Sam: 16.5 i/s - 6.42x (± 0.00) slower\n</code></pre>\n<p>The interesting thing here is that superb rain's answer did not profit much from the JIT. That is the problem when large parts of your core and standard library are written in C: Making your Ruby interpreter better does not actually speed up the code, because most of the code isn't Ruby!</p>\n<pre class=\"lang-none prettyprint-override\"><code>YARV 3.0.0-preview1\nWarming up --------------------------------------\n Lax_Sam 1.000 i/100ms\n Rubocop 1.000 i/100ms\n superb rain 15.000 i/100ms\n nullTerminator 2 2.000 i/100ms\n superb rain comment 2.000 i/100ms\n Jörg comment 2.000 i/100ms\n alt Jörg comment 2.000 i/100ms\n Jörg 2.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 10.816 (± 0.0%) i/s - 325.000 in 30.082046s\n Rubocop 12.942 (± 7.7%) i/s - 388.000 in 30.075579s\n superb rain 167.287 (± 6.6%) i/s - 5.010k in 30.071105s\n nullTerminator 2 26.439 (± 3.8%) i/s - 794.000 in 30.044673s\n superb rain comment 25.678 (± 3.9%) i/s - 770.000 in 30.037176s\n Jörg comment 27.056 (± 3.7%) i/s - 812.000 in 30.070840s\n alt Jörg comment 27.879 (± 3.6%) i/s - 836.000 in 30.002903s\n Jörg 25.197 (±27.8%) i/s - 666.000 in 30.085013s\n\nComparison:\n superb rain: 167.3 i/s\n alt Jörg comment: 27.9 i/s - 6.00x (± 0.00) slower\n Jörg comment: 27.1 i/s - 6.18x (± 0.00) slower\n nullTerminator 2: 26.4 i/s - 6.33x (± 0.00) slower\n superb rain comment: 25.7 i/s - 6.51x (± 0.00) slower\n Jörg: 25.2 i/s - 6.64x (± 0.00) slower\n Rubocop: 12.9 i/s - 12.93x (± 0.00) slower\n Lax_Sam: 10.8 i/s - 15.47x (± 0.00) slower\n</code></pre>\n<p>In YARV 3.0.0-preview1, performance has improved somewhat, but only superb rain's code really benefits. I suspect again that this may be due to improvements in the C libraries, not in the interpreter.</p>\n<p>In fact, we see again that it does not benefit from JIT:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Warming up --------------------------------------\n Lax_Sam 1.000 i/100ms\n Rubocop 1.000 i/100ms\n superb rain 9.000 i/100ms\n nullTerminator 2 2.000 i/100ms\n superb rain comment 2.000 i/100ms\n Jörg comment 2.000 i/100ms\n alt Jörg comment 2.000 i/100ms\n Jörg 1.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 14.049 (± 7.1%) i/s - 421.000 in 30.032181s\n Rubocop 17.339 (± 5.8%) i/s - 518.000 in 30.050563s\n superb rain 167.254 (± 4.2%) i/s - 5.013k in 30.027938s\n nullTerminator 2 28.321 (± 3.5%) i/s - 850.000 in 30.044948s\n superb rain comment 29.456 (± 3.4%) i/s - 884.000 in 30.039652s\n Jörg comment 26.970 (± 3.7%) i/s - 808.000 in 30.012719s\n alt Jörg comment 27.412 (± 3.6%) i/s - 822.000 in 30.022766s\n Jörg 30.465 (± 3.3%) i/s - 913.000 in 30.018464s\n\nComparison:\n superb rain: 167.3 i/s\n Jörg: 30.5 i/s - 5.49x (± 0.00) slower\n superb rain comment: 29.5 i/s - 5.68x (± 0.00) slower\n nullTerminator 2: 28.3 i/s - 5.91x (± 0.00) slower\n alt Jörg comment: 27.4 i/s - 6.10x (± 0.00) slower\n Jörg comment: 27.0 i/s - 6.20x (± 0.00) slower\n Rubocop: 17.3 i/s - 9.65x (± 0.00) slower\n Lax_Sam: 14.0 i/s - 11.91x (± 0.00) slower\n</code></pre>\n<p>Everything only gets slightly faster with JIT.</p>\n<pre class=\"lang-none prettyprint-override\"><code>JRuby 9.2.13.0\nWarming up --------------------------------------\n Lax_Sam 1.000 i/100ms\n Rubocop 1.000 i/100ms\n superb rain 24.000 i/100ms\n nullTerminator 2 1.000 i/100ms\n superb rain comment 1.000 i/100ms\n Jörg comment 9.000 i/100ms\n alt Jörg comment 9.000 i/100ms\n Jörg 2.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 10.050 (± 0.0%) i/s - 302.000 in 30.084528s\n Rubocop 15.374 (± 6.5%) i/s - 461.000 in 30.031534s\n superb rain 318.038 (±17.3%) i/s - 9.216k in 30.045246s\n nullTerminator 2 16.119 (± 6.2%) i/s - 480.000 in 30.012794s\n superb rain comment 16.837 (± 5.9%) i/s - 504.000 in 29.994138s\n Jörg comment 94.309 (± 5.3%) i/s - 2.826k in 30.054033s\n alt Jörg comment 88.040 (± 9.1%) i/s - 2.619k in 30.013846s\n Jörg 28.873 (± 6.9%) i/s - 864.000 in 30.025918s\n\nComparison:\n superb rain: 318.0 i/s\n Jörg comment: 94.3 i/s - 3.37x (± 0.00) slower\n alt Jörg comment: 88.0 i/s - 3.61x (± 0.00) slower\n Jörg: 28.9 i/s - 11.02x (± 0.00) slower\n superb rain comment: 16.8 i/s - 18.89x (± 0.00) slower\n nullTerminator 2: 16.1 i/s - 19.73x (± 0.00) slower\n Rubocop: 15.4 i/s - 20.69x (± 0.00) slower\n Lax_Sam: 10.1 i/s - 31.64x (± 0.00) slower\n</code></pre>\n<p>It starts to get interesting! We see some significant improvements in performance, but more interestingly, we also see a significant change in the order!</p>\n<p>My two comments get a significant performance boost. I believe this is due to the fact that JRuby does some significant optimizations of blocks and <code>&block</code> arguments. There is a question on Stack Overflow somewhere, where I speculated that it might be possible to optimize <code>&block</code> arguments, and it looks like JRuby is able to do that, considering that my two comments are 5 x faster than superb rain's despite essentially being equivalent.</p>\n<pre class=\"lang-none prettyprint-override\"><code>Warming up --------------------------------------\n Lax_Sam 1.000 i/100ms\n Rubocop 1.000 i/100ms\n superb rain 25.000 i/100ms\n nullTerminator 2 2.000 i/100ms\n superb rain comment 2.000 i/100ms\n Jörg comment 10.000 i/100ms\n alt Jörg comment 9.000 i/100ms\n Jörg 2.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 11.510 (± 0.0%) i/s - 345.000 in 30.018452s\n Rubocop 19.436 (± 5.1%) i/s - 583.000 in 30.039970s\n superb rain 382.561 (±18.8%) i/s - 10.975k in 30.016459s\n nullTerminator 2 21.196 (± 9.4%) i/s - 632.000 in 30.069497s\n superb rain comment 21.665 (± 9.2%) i/s - 646.000 in 30.066157s\n Jörg comment 94.816 (± 3.2%) i/s - 2.850k in 30.093806s\n alt Jörg comment 93.373 (± 6.4%) i/s - 2.790k in 30.016488s\n Jörg 25.982 (± 7.7%) i/s - 774.000 in 30.009033s\n\nComparison:\n superb rain: 382.6 i/s\n Jörg comment: 94.8 i/s - 4.03x (± 0.00) slower\n alt Jörg comment: 93.4 i/s - 4.10x (± 0.00) slower\n Jörg: 26.0 i/s - 14.72x (± 0.00) slower\n superb rain comment: 21.7 i/s - 17.66x (± 0.00) slower\n nullTerminator 2: 21.2 i/s - 18.05x (± 0.00) slower\n Rubocop: 19.4 i/s - 19.68x (± 0.00) slower\n Lax_Sam: 11.5 i/s - 33.24x (± 0.00) slower\n</code></pre>\n<p>superb rain's answer is the only one that gets a significant performance boost from switching from the client JVM with the C0 compiler to the server VM with the C1 compiler.</p>\n<p>I believe that this might be due to that answer being the only one that is actually executed often enough to even <em>be</em> compiled. (I think the default threshold for compilation on the HotSpot server JVM is several thousand invocations.)</p>\n<p>I must admit that I did not spend too much time trying to tweak the benchmark and the various compiler and VM settings. Ideally, even the slowest implementation should be executed at least 20000 times during warmup, to ensure that all caches are warmed up and all code is compiled, before the actual benchmark run even starts. However, that would have meant a warmup time of over half an hour for just Lax Sam's original version on just YARV 2.7.2 without JIT alone. That doesn't even account for the actual benchmark run, and now add in the fact that we have 7 other versions per VM, and 8 VMs in total, and you can understand why I didn't do that.</p>\n<p>But I should've.</p>\n<pre class=\"lang-none prettyprint-override\"><code>TruffleRuby 20.2\nWarming up --------------------------------------\n Lax_Sam 39.000 i/100ms\n Rubocop 19.000 i/100ms\n superb rain 16.000 i/100ms\n nullTerminator 2 26.000 i/100ms\n superb rain comment 10.000 i/100ms\n Jörg comment 3.000 i/100ms\n alt Jörg comment 2.000 i/100ms\n Jörg 33.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 1.128k (± 7.8%) i/s - 33.579k in 30.019660s\n Rubocop 811.797 (± 5.3%) i/s - 24.282k in 30.013340s\n superb rain 681.764 (± 7.8%) i/s - 20.112k in 29.997715s\n nullTerminator 2 268.225 (±19.0%) i/s - 7.670k in 30.060797s\n superb rain comment 528.931 (± 3.0%) i/s - 15.850k in 30.000811s\n Jörg comment 31.826 (±22.0%) i/s - 897.000 in 30.002193s\n alt Jörg comment 31.255 (±25.6%) i/s - 852.000 in 30.051522s\n Jörg 346.747 (± 7.5%) i/s - 10.362k in 30.070039s\n\nComparison:\n Lax_Sam: 1127.5 i/s\n Rubocop: 811.8 i/s - 1.39x (± 0.00) slower\n superb rain: 681.8 i/s - 1.65x (± 0.00) slower\n superb rain comment: 528.9 i/s - 2.13x (± 0.00) slower\n Jörg: 346.7 i/s - 3.25x (± 0.00) slower\n nullTerminator 2: 268.2 i/s - 4.20x (± 0.00) slower\n Jörg comment: 31.8 i/s - 35.43x (± 0.00) slower\n alt Jörg comment: 31.3 i/s - 36.08x (± 0.00) slower\n</code></pre>\n<p>Hello! All of a sudden, Lax Sam's version, which was consistently the <em>slowest</em> on YARV and JRuby is the <em>fastest</em>. Not only is it literally <em>a hundred times</em> faster than on YARV and JRuby, it is also the fastest of the pack.</p>\n<pre class=\"lang-none prettyprint-override\"><code>Warming up --------------------------------------\n Lax_Sam 122.000 i/100ms\n Rubocop 25.000 i/100ms\n superb rain 24.000 i/100ms\n nullTerminator 2 60.000 i/100ms\n superb rain comment 15.000 i/100ms\n Jörg comment 4.000 i/100ms\n alt Jörg comment 15.000 i/100ms\n Jörg 105.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 1.223k (± 1.8%) i/s - 36.722k in 30.029216s\n Rubocop 1.218k (± 3.4%) i/s - 36.500k in 29.999182s\n superb rain 855.216 (± 4.0%) i/s - 25.464k in 30.022110s\n nullTerminator 2 635.845 (± 3.5%) i/s - 19.080k in 30.046283s\n superb rain comment 778.807 (± 2.6%) i/s - 23.355k in 30.010292s\n Jörg comment 82.560 (±21.8%) i/s - 2.304k in 30.022217s\n alt Jörg comment 721.277 (± 5.5%) i/s - 21.570k in 30.013936s\n Jörg 1.068k (± 5.1%) i/s - 32.025k in 30.067412s\n\nComparison:\n Lax_Sam: 1223.3 i/s\n Rubocop: 1218.4 i/s - same-ish: difference falls within error\n Jörg: 1068.3 i/s - 1.15x (± 0.00) slower\n superb rain: 855.2 i/s - 1.43x (± 0.00) slower\n superb rain comment: 778.8 i/s - 1.57x (± 0.00) slower\n alt Jörg comment: 721.3 i/s - 1.70x (± 0.00) slower\n nullTerminator 2: 635.8 i/s - 1.92x (± 0.00) slower\n Jörg comment: 82.6 i/s - 14.82x (± 0.00) slower\n</code></pre>\n<p>Stuff gets significantly faster when running on the JVM as opposed to native. That is to be expected. In native mode, GraalVM starts up much faster, but it lacks the sophisticated optimizations that the JVM has. It's trade-off of startup time vs. steady-state throughput.</p>\n<p>Not sure what happened with my comment there, I think there must have been some disturbance on my laptop. I wasn't able to have a really separate idle test system, unfortunately, I was running these in the background while working.</p>\n<p>I would like to draw your attention to the performance of superb rain's solution. Above, it was consistently the fastest, since it is simply calling into C code (or Java code on JRuby). But I would like to compare it not to the others running on the same VM, but rather to itself running on a different VM: it is 2.23 times faster than when running on JRuby <code>--server</code> and 8.27 times faster than running on YARV.</p>\n<p>Now, you might say, okay, I have heard of code written in Java running faster than code written in C in some circumstances, but here's the kicker: it's not written in Java. TruffleRuby's <code>Array#max</code> and <code>Array#count</code> are written in pure Ruby. Only <code>Array#each</code> is written in Java. (More precisely, it is written as Truffle AST Nodes, the Java code is really only there to construct the Nodes).</p>\n<p>So, in some very narrow sense, we have just proven that Ruby is 8 x faster than C ;-)</p>\n<p>For completeness' sake, I also ran the benchmarks with a 100000 item array instead of 1000000, so that I could include the original O(n²)version from NullTerminator's answer.</p>\n<p>It doesn't offer any significant insights other than the obvious "O(n²) is slow". There is some strangeness going on here as well with the performance of that version. E.g. on TruffleRuby, it is faster on native than on JVM, and it doesn't seem to benefit from JITting nearly as much as I would expect.</p>\n<p>Although thinking about it, it makes sense. While <code>Array#max</code> and <code>Integer#==</code> are called 100000 times, and thus should be sped up significantly by JITting, <code>Integer#==</code> is probably a highly-optimized builtin which gets special-cased already, and <code>Array#max</code> is too simple to reap any significant benefit. And the benchmark loop itself is only run once.</p>\n<pre class=\"lang-none prettyprint-override\"><code>YARV 2.7.2\nWarming up --------------------------------------\n Lax_Sam 12.000 i/100ms\n Rubocop 15.000 i/100ms\n superb rain 112.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 26.000 i/100ms\n superb rain comment 26.000 i/100ms\n Jörg comment 21.000 i/100ms\n alt Jörg comment 20.000 i/100ms\n Jörg 31.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 122.064 (± 2.5%) i/s - 3.660k in 30.009487s\n Rubocop 152.157 (± 2.0%) i/s - 4.575k in 30.082788s\n superb rain 1.127k (± 2.0%) i/s - 33.824k in 30.029655s\n nullTerminator 1 0.036 (± 0.0%) i/s - 2.000 in 54.944267s\n nullTerminator 2 269.498 (± 1.5%) i/s - 8.086k in 30.012557s\n superb rain comment 263.736 (± 2.3%) i/s - 7.930k in 30.085927s\n Jörg comment 213.588 (± 1.9%) i/s - 6.426k in 30.095600s\n alt Jörg comment 212.821 (± 2.8%) i/s - 6.380k in 30.008460s\n Jörg 312.213 (± 2.6%) i/s - 9.362k in 30.005331s\n\nComparison:\n superb rain: 1126.8 i/s\n Jörg: 312.2 i/s - 3.61x (± 0.00) slower\n nullTerminator 2: 269.5 i/s - 4.18x (± 0.00) slower\n superb rain comment: 263.7 i/s - 4.27x (± 0.00) slower\n Jörg comment: 213.6 i/s - 5.28x (± 0.00) slower\n alt Jörg comment: 212.8 i/s - 5.29x (± 0.00) slower\n Rubocop: 152.2 i/s - 7.41x (± 0.00) slower\n Lax_Sam: 122.1 i/s - 9.23x (± 0.00) slower\n nullTerminator 1: 0.0 i/s - 30956.35x (± 0.00) slower\n\nWarming up --------------------------------------\n Lax_Sam 17.000 i/100ms\n Rubocop 20.000 i/100ms\n superb rain 113.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 32.000 i/100ms\n superb rain comment 30.000 i/100ms\n Jörg comment 21.000 i/100ms\n alt Jörg comment 20.000 i/100ms\n Jörg 31.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 171.256 (± 2.9%) i/s - 5.134k in 30.004456s\n Rubocop 213.270 (± 2.3%) i/s - 6.400k in 30.025421s\n superb rain 1.122k (± 3.0%) i/s - 33.674k in 30.031110s\n nullTerminator 1 0.036 (± 0.0%) i/s - 2.000 in 55.154473s\n nullTerminator 2 297.029 (± 7.1%) i/s - 8.896k in 30.111224s\n superb rain comment 289.555 (± 7.6%) i/s - 8.640k in 30.014487s\n Jörg comment 198.056 (± 5.0%) i/s - 5.943k in 30.095264s\n alt Jörg comment 200.426 (± 5.5%) i/s - 6.000k in 30.031566s\n Jörg 707.428 (±59.1%) i/s - 13.981k in 30.015974s\n\nComparison:\n superb rain: 1122.4 i/s\n Jörg: 707.4 i/s - same-ish: difference falls within error\n nullTerminator 2: 297.0 i/s - 3.78x (± 0.00) slower\n superb rain comment: 289.6 i/s - 3.88x (± 0.00) slower\n Rubocop: 213.3 i/s - 5.26x (± 0.00) slower\n alt Jörg comment: 200.4 i/s - 5.60x (± 0.00) slower\n Jörg comment: 198.1 i/s - 5.67x (± 0.00) slower\n Lax_Sam: 171.3 i/s - 6.55x (± 0.00) slower\n nullTerminator 1: 0.0 i/s - 30952.98x (± 0.00) slower\n\nYARV 3.0.0-preview1\nWarming up --------------------------------------\n Lax_Sam 10.000 i/100ms\n Rubocop 14.000 i/100ms\n superb rain 173.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 24.000 i/100ms\n superb rain comment 26.000 i/100ms\n Jörg comment 26.000 i/100ms\n alt Jörg comment 28.000 i/100ms\n Jörg 30.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 112.428 (± 3.6%) i/s - 3.370k in 30.011516s\n Rubocop 145.914 (± 2.7%) i/s - 4.382k in 30.056886s\n superb rain 1.772k (± 2.5%) i/s - 53.284k in 30.083199s\n nullTerminator 1 0.108 (± 0.0%) i/s - 4.000 in 37.125165s\n nullTerminator 2 264.817 (± 3.4%) i/s - 7.944k in 30.032986s\n superb rain comment 265.206 (± 3.0%) i/s - 7.956k in 30.029620s\n Jörg comment 281.578 (± 2.5%) i/s - 8.450k in 30.029642s\n alt Jörg comment 267.871 (± 8.6%) i/s - 7.952k in 30.019412s\n Jörg 309.680 (± 2.3%) i/s - 9.300k in 30.049396s\n\nComparison:\n superb rain: 1772.4 i/s\n Jörg: 309.7 i/s - 5.72x (± 0.00) slower\n Jörg comment: 281.6 i/s - 6.29x (± 0.00) slower\n alt Jörg comment: 267.9 i/s - 6.62x (± 0.00) slower\n superb rain comment: 265.2 i/s - 6.68x (± 0.00) slower\n nullTerminator 2: 264.8 i/s - 6.69x (± 0.00) slower\n Rubocop: 145.9 i/s - 12.15x (± 0.00) slower\n Lax_Sam: 112.4 i/s - 15.76x (± 0.00) slower\n nullTerminator 1: 0.1 i/s - 16446.42x (± 0.00) slower\n\nWarming up --------------------------------------\n Lax_Sam 15.000 i/100ms\n Rubocop 17.000 i/100ms\n superb rain 179.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 29.000 i/100ms\n superb rain comment 29.000 i/100ms\n Jörg comment 27.000 i/100ms\n alt Jörg comment 28.000 i/100ms\n Jörg 30.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 145.516 (± 2.1%) i/s - 4.365k in 30.007498s\n Rubocop 184.778 (± 2.7%) i/s - 5.542k in 30.015867s\n superb rain 1.795k (± 2.3%) i/s - 53.879k in 30.035743s\n nullTerminator 1 0.108 (± 0.0%) i/s - 4.000 in 36.988133s\n nullTerminator 2 297.031 (± 3.4%) i/s - 8.903k in 30.011491s\n superb rain comment 294.181 (± 4.8%) i/s - 8.816k in 30.046669s\n Jörg comment 282.395 (± 2.1%) i/s - 8.478k in 30.033645s\n alt Jörg comment 281.245 (± 2.5%) i/s - 8.456k in 30.083727s\n Jörg 755.737 (±55.7%) i/s - 15.240k in 30.023659s\n\nComparison:\n superb rain: 1794.9 i/s\n Jörg: 755.7 i/s - 2.37x (± 0.00) slower\n nullTerminator 2: 297.0 i/s - 6.04x (± 0.00) slower\n superb rain comment: 294.2 i/s - 6.10x (± 0.00) slower\n Jörg comment: 282.4 i/s - 6.36x (± 0.00) slower\n alt Jörg comment: 281.2 i/s - 6.38x (± 0.00) slower\n Rubocop: 184.8 i/s - 9.71x (± 0.00) slower\n Lax_Sam: 145.5 i/s - 12.33x (± 0.00) slower\n nullTerminator 1: 0.1 i/s - 16596.95x (± 0.00) slower\n\nJRuby 9.2.13.0\nWarming up --------------------------------------\n Lax_Sam 11.000 i/100ms\n Rubocop 16.000 i/100ms\n superb rain 291.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 18.000 i/100ms\n superb rain comment 18.000 i/100ms\n Jörg comment 85.000 i/100ms\n alt Jörg comment 88.000 i/100ms\n Jörg 27.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 100.805 (± 6.0%) i/s - 3.014k in 30.017257s\n Rubocop 156.208 (± 5.1%) i/s - 4.688k in 30.090375s\n superb rain 3.916k (± 6.7%) i/s - 116.982k in 30.018596s\n nullTerminator 1 0.078 (± 0.0%) i/s - 3.000 in 38.298137s\n nullTerminator 2 179.632 (± 2.8%) i/s - 5.400k in 30.087853s\n superb rain comment 186.696 (± 3.2%) i/s - 5.598k in 30.020062s\n Jörg comment 906.260 (± 3.5%) i/s - 27.200k in 30.051472s\n alt Jörg comment 886.155 (± 4.5%) i/s - 26.576k in 30.056778s\n Jörg 315.734 (± 3.5%) i/s - 9.477k in 30.056682s\n\nComparison:\n superb rain: 3915.9 i/s\n Jörg comment: 906.3 i/s - 4.32x (± 0.00) slower\n alt Jörg comment: 886.2 i/s - 4.42x (± 0.00) slower\n Jörg: 315.7 i/s - 12.40x (± 0.00) slower\n superb rain comment: 186.7 i/s - 20.97x (± 0.00) slower\n nullTerminator 2: 179.6 i/s - 21.80x (± 0.00) slower\n Rubocop: 156.2 i/s - 25.07x (± 0.00) slower\n Lax_Sam: 100.8 i/s - 38.85x (± 0.00) slower\n nullTerminator 1: 0.1 i/s - 49987.27x (± 0.00) slower\n\nWarming up --------------------------------------\n Lax_Sam 10.000 i/100ms\n Rubocop 16.000 i/100ms\n superb rain 270.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 20.000 i/100ms\n superb rain comment 16.000 i/100ms\n Jörg comment 93.000 i/100ms\n alt Jörg comment 93.000 i/100ms\n Jörg 31.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 105.366 (± 2.8%) i/s - 3.160k in 30.011009s\n Rubocop 161.379 (± 3.1%) i/s - 4.848k in 30.077855s\n superb rain 4.217k (± 3.3%) i/s - 126.360k in 30.003990s\n nullTerminator 1 0.062 (± 0.0%) i/s - 2.000 in 32.717686s\n nullTerminator 2 182.726 (±12.0%) i/s - 5.360k in 30.016244s\n superb rain comment 171.714 (±15.1%) i/s - 4.960k in 29.997313s\n Jörg comment 920.739 (±11.8%) i/s - 26.877k in 29.999270s\n alt Jörg comment 945.642 (± 4.5%) i/s - 28.365k in 30.061167s\n Jörg 299.195 (± 4.3%) i/s - 8.959k in 30.008053s\n\nComparison:\n superb rain: 4216.8 i/s\n alt Jörg comment: 945.6 i/s - 4.46x (± 0.00) slower\n Jörg comment: 920.7 i/s - 4.58x (± 0.00) slower\n Jörg: 299.2 i/s - 14.09x (± 0.00) slower\n nullTerminator 2: 182.7 i/s - 23.08x (± 0.00) slower\n superb rain comment: 171.7 i/s - 24.56x (± 0.00) slower\n Rubocop: 161.4 i/s - 26.13x (± 0.00) slower\n Lax_Sam: 105.4 i/s - 40.02x (± 0.00) slower\n nullTerminator 1: 0.1 i/s - 67484.66x (± 0.00) slower\n\nTruffleRuby 20.2\nWarming up --------------------------------------\n Lax_Sam 1.188k i/100ms\n Rubocop 739.000 i/100ms\n superb rain 648.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 243.000 i/100ms\n superb rain comment 281.000 i/100ms\n Jörg comment 15.000 i/100ms\n alt Jörg comment 26.000 i/100ms\n Jörg 371.000 i/100ms\nCalculating -------------------------------------\n Lax_Sam 11.608k (± 4.9%) i/s - 348.084k in 30.062217s\n Rubocop 8.132k (± 5.3%) i/s - 243.870k in 30.074370s\n superb rain 6.759k (± 5.5%) i/s - 202.176k in 30.010548s\n nullTerminator 1 0.081 (± 0.0%) i/s - 3.000 in 43.395539s\n nullTerminator 2 2.497k (±20.4%) i/s - 70.713k in 29.999344s\n superb rain comment 6.563k (±10.9%) i/s - 189.113k in 30.043814s\n Jörg comment 386.749 (±36.2%) i/s - 9.495k in 30.002080s\n alt Jörg comment 356.131 (±21.9%) i/s - 9.906k in 30.019783s\n Jörg 3.725k (± 5.0%) i/s - 111.671k in 30.057561s\n\nComparison:\n Lax_Sam: 11608.3 i/s\n Rubocop: 8132.2 i/s - 1.43x (± 0.00) slower\n superb rain: 6759.3 i/s - 1.72x (± 0.00) slower\n superb rain comment: 6562.7 i/s - 1.77x (± 0.00) slower\n Jörg: 3725.0 i/s - 3.12x (± 0.00) slower\n nullTerminator 2: 2497.0 i/s - 4.65x (± 0.00) slower\n Jörg comment: 386.7 i/s - 30.02x (± 0.00) slower\n alt Jörg comment: 356.1 i/s - 32.60x (± 0.00) slower\n nullTerminator 1: 0.1 i/s - 142749.98x (± 0.00) slower\n\nWarming up --------------------------------------\n Lax_Sam 1.091k i/100ms\n Rubocop 1.140k i/100ms\n superb rain 138.000 i/100ms\n nullTerminator 1 1.000 i/100ms\n nullTerminator 2 139.000 i/100ms\n superb rain comment 120.000 i/100ms\n Jörg comment 32.000 i/100ms\n alt Jörg comment 140.000 i/100ms\n Jörg 1.061k i/100ms\nCalculating -------------------------------------\n Lax_Sam 12.065k (± 2.5%) i/s - 362.212k in 30.041589s\n Rubocop 11.798k (± 4.8%) i/s - 353.400k in 30.029941s\n superb rain 1.382k (± 5.7%) i/s - 41.262k in 30.010554s\n nullTerminator 1 0.017 (± 0.0%) i/s - 1.000 in 58.565986s\n nullTerminator 2 1.369k (± 5.0%) i/s - 41.005k in 30.026253s\n superb rain comment 1.386k (± 4.3%) i/s - 41.520k in 30.016684s\n Jörg comment 596.986 (± 8.0%) i/s - 17.728k in 30.071800s\n alt Jörg comment 1.301k (±21.7%) i/s - 35.140k in 30.020553s\n Jörg 10.311k (± 4.9%) i/s - 308.751k in 30.023219s\n\nComparison:\n Lax_Sam: 12065.1 i/s\n Rubocop: 11797.7 i/s - same-ish: difference falls within error\n Jörg: 10310.9 i/s - 1.17x (± 0.00) slower\n superb rain comment: 1385.9 i/s - 8.71x (± 0.00) slower\n superb rain: 1381.6 i/s - 8.73x (± 0.00) slower\n nullTerminator 2: 1369.2 i/s - 8.81x (± 0.00) slower\n alt Jörg comment: 1301.1 i/s - 9.27x (± 0.00) slower\n Jörg comment: 597.0 i/s - 20.21x (± 0.00) slower\n nullTerminator 1: 0.0 i/s - 706606.12x (± 0.00) slower\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:33:19.893",
"Id": "491372",
"Score": "0",
"body": "I think it's a reasonable assumption, and true with my test data which you reused, that most values are *not* a new maximum. So your solution would be faster if it optimized for the common case by only checking `>= maximum` at first (and distinguishing the two cases only inside). So putting all the loser elements through only *one* comparison instead of two. See https://repl.it/repls/EsteemedWateryDecagon#main.rb"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:37:31.940",
"Id": "491373",
"Score": "0",
"body": "Now I can't decide if I should re-benchmark with your optimization or with a monotonically increasing array :-D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:45:55.973",
"Id": "491374",
"Score": "0",
"body": "Just increasing or strictly increasing? :-) Either way I think my data is more realistic and less of a special case (that's why I created it like that)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T19:38:55.477",
"Id": "503090",
"Score": "0",
"body": "Fascinating, especially Lax Sam's sprint to the finish. For better readabiity of that method you might consider `max_num, max_num_count = array.inject([0, 0]) { |(max_num, max_num_count), age| ...`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T16:14:10.920",
"Id": "250430",
"ParentId": "249128",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249132",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T15:54:32.717",
"Id": "249128",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Better way to count the number of occurrences of a maximum number in the array in Ruby"
}
|
249128
|
<p>I created a library with two CLOS class to implement a deque structure similar to the one available in C++, plus a few Lisp-ian twists. The two classes are <code>node</code>, which implements a doubly linked list, and <code>deque</code>, which uses <code>node</code> to implement the actual deque.</p>
<p>The main deque operations are available, including push and pop on both ends, an iterate macro (<code>do-deque</code>), search (element or position of an element), and check-if-null. Individual elements of the deque are also <code>setf</code>able.</p>
<p>Here's the beast.</p>
<pre><code>;;;; Deque class
;;; Node class to create doubly linked lists
(defclass node ()
((content
:initarg :content
:accessor content)
(prev
:initform nil
:accessor prev)
(next
:initform nil
:accessor next)))
(defun make-node (content &key prev next)
"Creates a new node, doubly linked to nodes prev and next. Returns the new node"
(let ((n (make-instance 'node :content content)))
(if prev (setf (next prev) n (prev n) prev))
(if next (setf (prev next) n (next n) next))
(values n)))
(defun copy-node (node)
"Returns a copy of node"
(make-node (content node) :prev (prev node) :next (next node)))
(defun bind-nodes (a b)
"Bind nodes a and b, placing a after b"
(setf (next a) b (prev b) a))
(defmethod print-object ((obj node) stream)
"Prints a node object and its content. Output has the format:
<NODE content sole|first|middle|last>
The descriptors mean:
* sole - the node is not linked to other nodes
* first - the node is the first in a list
* middle - the node is in the middle of a list
* last - the node is the last in a list"
(print-unreadable-object (obj stream :type t)
(with-accessors ((content content)
(next next)
(prev prev))
obj
(format stream "~a ~:[~:[sole~;first~]~;~:[last~;middle~]~]" content prev next))))
(defun print-list (lst &key from-end)
"Prints out the items of a linked list in separate lines"
(let ((direction (if from-end 'prev 'next)))
(loop for i = lst then (slot-value i direction)
while i do (pprint i))))
(defmacro do-linked-list ((var lst &key from-end) &body body)
(let ((i (gensym)))
"Iterates over lst in either direction"
`(loop for ,i = ,lst
then (,(if from-end 'prev 'next) ,i)
while ,i
do (let ((,var (content ,i))) (progn ,@body)))))
(defun make-linked-list (lst)
"Creates a doubly linked list from a common list. Returns
pointers to the first and last elements in the list and the
number of nodes in the list."
(if lst
(loop with 1st = (make-node (car lst))
for i in lst
for j = 1st then (make-node i :prev j)
counting t into n
finally (return (values 1st j n)))
(values nil nil 0)))
;;; Deque class
(defclass deque ()
((element-count
:initarg :element-count
:accessor element-count)
(first-element
:initform nil
:accessor first-element)
(last-element
:initform nil
:accessor last-element)))
(defmethod print-object ((obj deque) stream)
"Prints a deque object. Output has the format:
<DEQUE :elements <element-count> :contents (first ... last)>"
(print-unreadable-object (obj stream :type t)
(with-accessors ((first first-element)
(last last-element)
(c element-count)
(p pointer))
obj
(format stream "~[empty~:;:elements ~:*~d :content ~:*(~[~;~a~;~a ~a~:;~a ... ~a~])~]"
c
(if first (content first))
(if last (content last))))))
(defun make-deque (&optional lst)
"Constructor for deque object. Takes a list as argument and returns a deque
with the same elements in order."
(multiple-value-bind (first last n)
(make-linked-list lst)
(let ((d (make-instance 'deque :element-count n)))
(setf (first-element d) first
(last-element d) last)
(values d))))
;;; Ancillary functions for pop and append functions
(declaim (inline add-first-element remove-single-element))
(defmethod add-first-element ((obj deque) element)
"Adds one element to an empty deque"
(let ((new-node (make-node element)))
(setf (element-count obj) 1
(first-element obj) new-node
(last-element obj) new-node)))
(defmethod remove-single-element ((obj deque))
"Empties a deque containing one element"
(setf (element-count obj) 0
(first-element obj) nil
(last-element obj) nil))
(defmethod empty-deque-p ((obj deque))
"Tests whether a deque is empty"
(zerop (element-count obj)))
(defmethod append-element ((obj deque) element)
"Add one element to the end of a deque. Return the enlarged deque."
(if (empty-deque-p obj)
(add-first-element obj element)
(progn (make-node element :prev (last-element obj))
(incf (element-count obj))
(setf (last-element obj)
(next (last-element obj)))))
(values obj))
;;; Functions for appending, prepending and removing elements from
;;; either end of the deque.
(defmethod prepend-element ((obj deque) element)
"Add one element to the start of a deque. Return the enlarged deque."
(if (zerop (element-count obj))
(add-first-element obj element)
(progn (make-node element :next (first-element obj))
(incf (element-count obj))
(setf (first-element obj)
(prev (first-element obj)))))
(values obj))
(defmethod pop-last ((obj deque))
"Remove one element from the end of a deque. Return the shortened deque."
(let ((result (unless (zerop (element-count obj))
(content (last-element obj)))))
(case (element-count obj)
(0
(values nil nil))
(1
(remove-single-element obj)
(values result t))
(otherwise
(setf (last-element obj) (prev (last-element obj))
(next (last-element obj)) nil)
(decf (element-count obj))
(values result t)))))
(defmethod pop-first ((obj deque))
"Remove one element from the start of a deque. Return the shortened deque."
(let ((result (unless (zerop (element-count obj))
(content (first-element obj)))))
(case (element-count obj)
(0
(values nil nil))
(1
(remove-single-element obj)
(values result t))
(otherwise
(setf (first-element obj) (next (first-element obj))
(prev (first-element obj)) nil)
(decf (element-count obj))
(values result t)))))
(defmethod insert-element ((obj deque) content position)
"Inserts an element containing 'content' in position 'position' (zero offset).
Returns the resulting deque."
(cond ((zerop position)
(prepend-element obj content))
((= position (element-count obj))
(append-element obj content))
(t
(loop repeat position
for j = (first-element obj) then (next j)
finally (progn (make-node content :prev j :next (next j))
(incf (element-count obj))))))
(values obj))
(defmethod nth-element ((obj deque) n &key from-end &aux (c (element-count obj)))
"Returns the nth element of a deque. If from-end is non-nil, returns the nth element before last."
(assert (<= n c)
()
"Index out of range. Position ~d requested, but deque has only ~d elements" n c)
(loop with d = (if from-end 'prev 'next)
repeat (1+ n)
for k = (slot-value obj (if from-end 'last-element 'first-element))
then (slot-value k d)
finally (return (content k))))
(defmethod change-nth-element ((obj deque) pos value &key from-end &aux (c (element-count obj)))
"Changes the value of the 'pos' element in a deque to 'value'.
If 'from-end' is T, the deque is traversed in reverse order."
(assert (<= pos c)
()
"Index out of range. Position ~d requested, but deque has only ~d elements" pos c)
(loop with d = (if from-end 'prev 'next)
repeat (1+ pos)
for k = (slot-value obj (if from-end 'last-element 'first-element))
then (slot-value k d)
finally (return (setf (content k) value))))
(define-setf-expander nth-element (obj n &key from-end)
"Makes individual elements of a deque setf-able using the change-nth-element function."
(let ((input (gensym)))
(values '()
'()
`(,input)
`(progn (change-nth-element ,obj ,n ,input :from-end ,from-end) ,input)
`(nth-element obj pos &key from-end))))
(defmacro do-deque ((var deque &key from-end) &body body)
"Executes the closure 'body' for each element of a deque. If from-end is t,
iterates over the deque in reverse order."
`(do-linked-list (,var
,@(if from-end `((last-element ,deque) :from-end t)
`((first-element ,deque))))
,@body))
(defmethod find-element ((obj deque) element)
"Finds the first occurrence of element in a deque, scanning it from
start to end. Returns the element if successful, nil otherwise"
(let ((i (first-element obj)))
(block nil
(tagbody
::loop
(if (eq (content i) element) (return-from nil (content i)))
(setf i (next i))
(if (null i) (return-from nil nil))
(go ::loop)))))
(defmethod find-element-pos ((obj deque) element)
"Finds the position of element in a deque, scanning it from start to end.
Returns the element if successful, nil otherwise"
(let ((i (first-element obj)) (pos 0))
(block nil
(tagbody
::loop
(if (eq (content i) element) (return-from nil pos))
(setf i (next i) pos (1+ pos))
(if (null i) (return-from nil nil))
(go ::loop)))))
</code></pre>
<p><strong>Test cases</strong></p>
<p>Create a deque from a list</p>
<pre><code>CL-USER> (defvar v (make-deque '(1 2 3 4 5 6)))
V
</code></pre>
<p><code>deque</code> and <code>node</code> have their own print-methods.</p>
<pre><code>CL-USER> v
#<DEQUE :elements 6 :content (1 ... 6)>
CL-USER> (make-node 0)
#<NODE 0 sole>
</code></pre>
<p>Append and prepend elements</p>
<pre><code>CL-USER> (append-element v 7)
#<DEQUE :elements 7 :content (1 ... 7)>
CL-USER> (prepend-element v 0)
#<DEQUE :elements 8 :content (0 ... 7)>
</code></pre>
<p>Pop first or last element. In both cases, the second value indicates whether an element was removed. <code>pop-first</code> and <code>pop-last</code> will return <code>Nil Nil</code> if the deque is empty.</p>
<pre><code>CL-USER> (pop-first v)
0
T
CL-USER> v
#<DEQUE :elements 7 :content (1 ... 7)>
CL-USER> (pop-last v)
7
T
CL-USER> v
#<DEQUE :elements 6 :content (1 ... 6)>
</code></pre>
<p>Iterate over a deque (in either direction)</p>
<pre><code>CL-USER> (do-deque (p v) (format t "~d~%" p))
1
2
3
4
5
6
NIL
CL-USER> (do-deque (p v :from-end t) (format t "~d~%" p))
6
5
4
3
2
1
NIL
</code></pre>
<p>Random access to elements (from either direction, like in standard functions <code>position</code> or <code>find</code>)</p>
<pre><code>CL-USER> (nth-element v 0)
1
CL-USER> (nth-element v 0 :from-end t)
6
</code></pre>
<p>Individual elements are <code>setf</code>able.</p>
<pre><code>CL-USER> (setf (nth-element v 0) 1000) => #(1000 2 3 4 5 6)
1000
CL-USER> (setf (nth-element v 0 :from-end t) 6000) => #(1000 2 3 4 5 6000)
6000
</code></pre>
<p>Simplified versions of <code>find</code> and <code>position</code> are also implemented.</p>
<pre><code>CL-USER> (find-element v 2)
2
CL-USER> (find-element v 6000)
6000
CL-USER> (find-element-pos v 2)
1
</code></pre>
<p>This is a work in progress, but the basic functionality is up and running. I intend to add some more bells and whistles and then wrap everything up in a package so as to hide the inner workings (i.e. nodes and stuff).</p>
<p>Any feedback is appreciated.</p>
<p>Thanks,</p>
|
[] |
[
{
"body": "<p>little review based on this style guide: https://lisp-lang.org/style-guide/, itself much based on Google's.</p>\n<ul>\n<li>the slots order should be accessor, initarg, initform, type.</li>\n<li>use the :type slot. They are mostly for documentation, but recent versions of SBCL (> 1.5.9) do static type checking of class slots.</li>\n<li>I'd put at least a :documentation slot for the class.</li>\n<li><code>lst</code>: in CL we can have variables named <code>list</code>.</li>\n<li><code>car lst</code>: if lst is a proper list it certainely should be <code>first</code>.</li>\n<li>you should avoid &aux: <a href=\"https://google.github.io/styleguide/lispguide.xml?showone=Defining_Functions#Defining_Functions\" rel=\"nofollow noreferrer\">https://google.github.io/styleguide/lispguide.xml?showone=Defining_Functions#Defining_Functions</a></li>\n<li>could you use a setf-function instead of the define-setf-expander macro?</li>\n</ul>\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun (setf nth-element ()) …)\n</code></pre>\n<p><a href=\"https://lispcookbook.github.io/cl-cookbook/functions.html#setf-functions\" rel=\"nofollow noreferrer\">https://lispcookbook.github.io/cl-cookbook/functions.html#setf-functions</a></p>\n<ul>\n<li>tagbody and go in the end?? Maybe you want the <code>do</code> macro?</li>\n</ul>\n<p>Anyways, the code was very readabde to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T19:42:56.927",
"Id": "489044",
"Score": "0",
"body": "Thank you for your input.\n\nI tried using a function for 'setf' but it didn't work on the first time. Now I got it right!\n\nI agree that `lst` was not a good variable name choice, but I wanted to avoid using a function name--I find it confusing--and the list isn't a proper list, so I replaced it with `nodes`.\n\nI used `tagbody` because the `find` function could potentially iterate over a large number of nodes, so I sought to avoid a macro. I also think it's such a trivial function that using `do` or `loop` would add unnecessary complexity."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T10:58:46.317",
"Id": "249209",
"ParentId": "249134",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249209",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:08:14.740",
"Id": "249134",
"Score": "3",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Deque class in Common Lisp"
}
|
249134
|
<p>I am pretty new to assembly I would like criticism on two "methods" I have written. One converts string to int and the other prints an int to stdout. Any advise helps out.</p>
<pre><code>bits 64
section .data
endl db 10, 0
endlLength equ $ - endl
section .bss
string resb 100
section .text
global _start
global _strToInt
global _printInt
_start:
mov rbp, rsp
;get int from user
mov rax, 0
mov rdi, 0
lea rsi, [string]
mov rdx, 100
syscall
;make string to int
push string
call _strToInt
pop r8
push rax
call _printInt
pop rax
mov rax, 1
mov rdi, 1
mov rsi, endl
mov rdx, endlLength
syscall
mov rax, 60
mov rbx, 0
syscall
;last value pushed to stack must be address to string. stores int in rax
_strToInt:
;prolog
push rbp
mov rbp, rsp
;save registers
push rbx
;actual code
xor rax, rax
mov rbx, 10 ;will be used to multiply by 10 later
mov rcx, [rbp + 16]
cmp byte[rcx], '-' ;check to see if value is negetive
jne _convertStringLoop
inc rcx ;increment the address
_convertStringLoop:
xor rdx, rdx ;clear rdx
mul rbx ;multiply rax by 10
mov dl, [rcx] ;get 1 byte from rcx address
sub dl, '0' ;seb by '0' to get actual value
add rax, rdx ;add it to rax
inc rcx
cmp byte[rcx], 10 ;see if new line char. exit if new line char
je _exitConvertStringLoop
cmp byte[rcx], 0 ;see if end of line char. exit if end of line
jne _convertStringLoop
_exitConvertStringLoop:
mov rcx, [rbp + 16]
cmp byte[rcx], '-' ;if not negetive jump
jne _exitStrToInt
not rax ;1's complement (make negetive)
inc rax ;2's complement (make negetive)
_exitStrToInt:
;restore registers
pop rbx
;epilog
pop rbp
ret
;last value pushed to stack will be printed
_printInt:
;prolog
push rbp
mov rbp, rsp
;save registers
push rbx
;actual code
mov rsi, rsp
mov rax, [rbp + 16] ;get the value that user wants to print
mov rbx, 10 ;will be used to divide by 10 later
xor rcx, rcx
cqo
cmp rdx, -1 ;check to see if negetive
jne _divisionLoop ;if not negetive jump
;print negetive sign
mov [rsi + 1], byte '-'
mov rax, 1
mov rdi, 1
inc rsi
mov rdx, 1
syscall
dec rsi
;convert to positive number
mov rax, [rbp + 16]
;imul rax, -1
dec rax
not rax
xor rcx, rcx
_divisionLoop:
xor rdx, rdx
div rbx ;divides number by 10 to move over last digit into rdx reg
add dl, '0'
dec rsi
mov [rsi], dl
inc rcx ; count for how many digits added to stack
cmp rax, 0
jnz _divisionLoop ;jump if the division did not result in a zero
;print all the values
mov rax, 1
mov rdi, 1
mov rdx, rcx
syscall
;restore register
pop rbx
;epilog
pop rbp
ret
</code></pre>
<p>One more thing I wanted to ask was is it better to do</p>
<pre><code> mov rax, -20
mov rbx, -1
imul rbx
</code></pre>
<p>or</p>
<pre><code> mov rax, -20
dec rax
not rax
</code></pre>
<p>when I know a number is negetive and I want to turn it to a positive.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T05:37:18.400",
"Id": "488303",
"Score": "2",
"body": "Welcome to CodeReview@SE. For X86 integer negation, you'd have to argue why to avoid [the proper instruction](https://stackoverflow.com/q/4534503)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:17:00.623",
"Id": "488565",
"Score": "0",
"body": "thank you for the recommendation!"
}
] |
[
{
"body": "<h3>Warming up</h3>\n<p>A good thing that I see missing from your program is writing comments about the function numbers and more.</p>\n<pre><code>mov rdi, 0 ; STDIN\nmov rax, 0 ; SYS_READ\nsyscall\n...\nmov rdi, 1 ; STDOUT\nmov rax, 1 ; SYS_WRITE\nsyscall\n\nmov rdi, 0 ; OK\nmov rax, 60 ; SYS_EXIT\nsyscall\n</code></pre>\n<p>Here's an improvement that you can make:</p>\n<blockquote>\n<pre><code>section .data\nendl db 10, 0\nendlLength equ $ - endl\n</code></pre>\n</blockquote>\n<p>The output to STDOUT is length driven. It's not useful to zero terminated this newline. All you could get is that ASCII character 0 gets displayed needlessly.</p>\n<h3>There are some errors in your code</h3>\n<blockquote>\n<pre><code>mov rax, 60\nmov rbx, 0\nsyscall\n</code></pre>\n</blockquote>\n<p>The first argument must go in <code>RDI</code>. You wrote <code>RBX</code>. Habit from 32-bit ?</p>\n<hr />\n<blockquote>\n<pre><code>_convertStringLoop:\n xor rdx, rdx ;clear rdx\n mul rbx ;multiply rax by 10\n mov dl, [rcx] ;get 1 byte from rcx address\n sub dl, '0' ;seb by '0' to get actual value\n add rax, rdx ;add it to rax\n</code></pre>\n</blockquote>\n<p>You have misplaced that <code>xor rdx, rdx</code> instruction. The <code>mul rbx</code> instruction that follows will modify <code>RDX</code> as part of its operation. If the input that you get from the user at the keyboard is really big, then <code>RDX</code> can become non-zero! But wait! You need <code>RDX</code> to be zero so the addition can work correctly...</p>\n<p>This will work fine zero-extending <code>DL</code> into <code>EDX</code> into <code>RDX</code>:</p>\n<pre><code>_convertStringLoop:\n mul rbx ; multiply rax by 10\n movzx edx, byte [rcx] ; Get 1 byte from RCX address and put in RDX\n sub dl, '0' ; seb by '0' to get actual value\n add rax, rdx ; add it to rax\n</code></pre>\n<p>and this will work too and allows to not use <code>RBX</code> at all (saves many instructions):</p>\n<pre><code>_convertStringLoop:\n imul rax, 10 ; multiply rax by 10\n movzx edx, byte [rcx] ; Get 1 byte from RCX address and put in RDX\n sub dl, '0' ; seb by '0' to get actual value\n add rax, rdx ; add it to rax\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>;print negetive sign\nmov [rsi + 1], byte '-'\nmov rax, 1\nmov rdi, 1\ninc rsi\nmov rdx, 1\nsyscall\ndec rsi\n</code></pre>\n</blockquote>\n<p>This code overwrites the value of <code>RBX</code> that you're trying to preserve on the stack!\nYou need to offset by a negative number or else decrement <code>RSI</code> beforehand:</p>\n<pre><code>; print negative sign\ndec rsi\nmov byte [rsi], '-'\nmov rdx, 1\nmov rdi, 1 ; STDOUT\nmov rax, 1 ; SYS_WRITE\nsyscall\ninc rsi\n</code></pre>\n<h3>Some better ways of doing things</h3>\n<blockquote>\n<pre><code>cqo\ncmp rdx, -1 ;check to see if negetive\njne _divisionLoop ;if not negetive jump\n</code></pre>\n</blockquote>\n<p>You can test if <code>RAX</code> contains a negative number simply by testing the register with itself and then inspecting the sign flag:</p>\n<pre><code>test rax, rax\njns _divisionLoop ; RAX is positive\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>cmp byte[rcx], '-' ;if not negetive jump\njne _exitStrToInt\nnot rax ;1's complement (make negetive)\ninc rax ;2's complement (make negetive)\n</code></pre>\n</blockquote>\n<p>The instruction set offers you the <code>NEG</code> instruction to negate a number:</p>\n<pre><code>cmp byte [rcx], '-' ; If not negative jump\njne _exitStrToInt\nneg rax\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>cmp rax, 0\njnz _divisionLoop ;jump if the division did not result in a zero\n</code></pre>\n</blockquote>\n<p>To find out if a register is 0, you can test it with itself and inspect the zero flag. This shaves off a byte and generally produces faster code:</p>\n<pre><code>test rax, rax\njnz _divisionLoop\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:16:13.177",
"Id": "488564",
"Score": "0",
"body": "Thank you so MUCH! I really do appreciate you going over my code. I'm actually in tears of JOY!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:18:32.127",
"Id": "488566",
"Score": "1",
"body": "Then good tears, I hope..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:02:24.553",
"Id": "249289",
"ParentId": "249137",
"Score": "5"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/questions/249137/criticism-on-x86-64-nasm-assembly-strtoint-and-printint-implementation#answer-249289\">Sep Roland pointed out</a>, it's really important to specify the significance of the numeric constants you're using. Rather than adding comments on each line though, I'm a huge fan of using the nasm preprocessor to define C-style symbolic constants.</p>\n<pre><code>%define STDIN 0\n%define STDOUT 1\n%define STDERR 2\n\n%define SYSCALL_READ 0\n%define SYSCALL_WRITE 1\n%define SYSCALL_EXIT 60\n</code></pre>\n<p>If these macros are defined in the same file, you can just use them like you would in C.</p>\n<pre><code>mov rax,SYSCALL_READ\nmov rdi,STDIN\nsyscall\n...\nmov rax,SYSCALL_WRITE\nmov rdi,STDOUT\nsyscall\n</code></pre>\n<p>Having thus specified what the constants represent, this frees up the space on the side for comments on why you're doing what you're doing, why you're not doing it a different way, important warnings for anyone who might later want to make changes, etc.</p>\n<p>In other words, I prefer to use the preprocessor for the <em>what</em> and comments for the <em>why</em>. This is obviously just down to personal preference though, and to be quite honest I think most of us would prefer any comments anywhere in any format over the abyss of nothingness we usually get to wade through.</p>\n<p>Regarding your code organization, I like the nested indentation you used, I've actually never seen that before, and it actually made me laugh. It's a great idea! I would still also recommend using <a href=\"https://www.nasm.us/xdoc/2.15.05/html/nasmdoc3.html#section-3.9\" rel=\"nofollow noreferrer\">local labels</a> because it allows you to reuse label names as long as you don't do it within the same global label.</p>\n<p>For example:</p>\n<pre><code>_strToInt:\n ;prolog\n push rbp\n mov rbp, rsp\n ;save registers\n push rbx\n\n ;actual code\n xor rax, rax\n mov rbx, 10 ;will be used to multiply by 10 later\n\n mov rcx, [rbp + 16]\n cmp byte[rcx], '-' ;check to see if value is negetive\n jne _convertStringLoop\n inc rcx ;increment the address\n\n ._convertStringLoop:\n xor rdx, rdx ;clear rdx\n mul rbx ;multiply rax by 10\n mov dl, [rcx] ;get 1 byte from rcx address\n sub dl, '0' ;seb by '0' to get actual value\n add rax, rdx ;add it to rax\n inc rcx\n cmp byte[rcx], 10 ;see if new line char. exit if new line char\n je _exitConvertStringLoop\n cmp byte[rcx], 0 ;see if end of line char. exit if end of line\n jne _convertStringLoop\n\n ._exitConvertStringLoop:\n mov rcx, [rbp + 16]\n cmp byte[rcx], '-' ;if not negetive jump\n jne _exitStrToInt\n not rax ;1's complement (make negetive)\n inc rax ;2's complement (make negetive)\n\n ._exit:\n ;restore registers\n pop rbx\n ;epilog\n pop rbp\n ret\n</code></pre>\n<p>Prepending a period to your <code>_strToInt</code> subroutine labels to convert them into local labels now means you could for instance write a <code>_strToFloat</code> subroutine that also contained a sensibly named loop label called <code>.convertStringLoop</code>. There are also a billion subroutines that could reasonably contain an <code>._exit</code> label, so local labels allow you to use descriptive labels without polluting the module's global namespace.</p>\n<p>Much less importantly, <a href=\"https://www.nasm.us/xdoc/2.15.05/html/nasmdoc7.html#section-7.1\" rel=\"nofollow noreferrer\">you don't need to declare <code>BITS 64</code></a> in order to assemble in 64 bits. Nasm knows the output needs to be in 64 bits when you declare a 64-bit output format. This is necessary only when you want to assemble a flat binary file in long mode, since (as the documentation explains) raw binary files are probably going to be bootloaders or DOS files, both of which execute in 16-bit real mode.</p>\n<p>Of course, there's no harm in explicitly declaring it anyways. If you felt compelled to explicitly declare the target processor of your choosing, however, I might instead suggest declaring the <a href=\"https://www.nasm.us/xdoc/2.15.05/html/nasmdoc7.html#section-7.11\" rel=\"nofollow noreferrer\">CPU feature level</a> instead, although the default is again usually okay.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T03:22:39.243",
"Id": "490993",
"Score": "0",
"body": "Thank you for telling me how to make local labels it saves me a lot of time!!! And I appreciate the criticism it means a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T00:40:13.603",
"Id": "250208",
"ParentId": "249137",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T23:51:53.627",
"Id": "249137",
"Score": "4",
"Tags": [
"assembly",
"x86",
"nasm"
],
"Title": "Criticism on x86_64 nasm assembly strToInt and printInt implementation"
}
|
249137
|
<p>I'm relatively new to python and coding in general, and I decided that this would be a good little practice project. This was also my first project involving classes and objects so I kept their implementation a little basic just to get the feel of it. I would appreciate any constructive criticism on how I could improve things like my readability, efficiency, and if there were easier ways to do things.</p>
<p>The intended output of the program is to simulate interacting with a very basic bank or ATM. I had no intention of actually storing any account information in a separate file, so each account pin is completely arbitrary and only serves as a medium to make the simulation a little more realistic. The program is fully functional as far as I can tell, though there is the possibility of some bugs slipping through the cracks</p>
<pre><code>import random
import time
class Accounts:
# Defining Account instance variables.
def __init__(self, pin, balance, annualInterestRate=3.4):
self.pin = pin
self.balance = balance
self.annualInterestRate = annualInterestRate
# Class function to return the monthly interest rate.
def getMonthlyInterestRate(self):
return self.annualInterestRate / 12
# class function to calculate difference between the balance and the amount withdrawn.
def withdraw(self, amount):
self.balance -= amount
# class function to calculate the sum between the balance and the amount deposited.
def deposit(self, amount):
self.balance += amount
# Class function to calculate the product of the balance and the annual interest rate.
def getAnnualInterest(self):
return self.balance * self.annualInterestRate
# Class function to calculate the product of the balance and the monthly interest rate.
def getMonthlyInterest(self):
return self.balance * self.getMonthlyInterestRate()
# Revieves pin from user input and validates input.
def getAccountPin():
while True:
pin = input("\nEnter four digit account pin: ")
try:
pin = int(pin)
if pin >= 1000 and pin <= 9999:
return pin
else:
print(f"\n{pin} is not a valid pin... Try again")
except ValueError:
print(f"\n{pin} is not a vaild pin... Try again")
# Recieves user input for option selection and validates selection.
def getSelection():
while True:
selection = input("\nEnter your selection: ")
try:
selection = int(selection)
if selection >= 1 and selection <= 4:
return selection
else:
print(f"{selection} is not a valid choice... Try again")
except ValueError:
print(f"{selection} is not a valid choice... Try again")
# Returns the current working accounts balance.
def viewBalance(workingAccount):
return workingAccount.balance
# Recieves user input and validates if input is either yes, y, no, or n.
def correctAmount(amount):
while True:
answer = input(f"Is ${amount} the correct ammount, Yes or No? ")
try:
answer = answer.lower()
if answer == "y" or answer == "yes":
return True
elif answer == "n" or answer == "no":
return False
else:
print("Please enter a valid response")
except AttributeError:
print("Please enter a valid response")
# Recieves user input on amount to withdraw and validates inputed value.
def withdraw(workingAccount):
while True:
try:
amount = float(input("\nEnter amount you want to withdraw: "))
try:
amount = round(amount, 2)
if amount > 0 and ((workingAccount.balance) - amount) > 0:
answer = correctAmount(amount)
if answer == True:
print("Verifying withdraw")
time.sleep(random.randint(1, 2))
return amount
elif (((workingAccount.balance) - amount) < 0):
print("\nYour balance is less than the withdraw amount")
elif amount == 0:
answer = correctAmount(amount)
if answer == True:
print("Canceling withdraw")
time.sleep(random.randint(1, 2))
return amount
else:
print("\nPlease enter an amount greater than or equal to 0")
except TypeError:
print("\nAmount entered is invalid... Try again")
except ValueError:
print("\nAmount entered is invalid... Try again")
# Recieves user input on amount to deposit and validates inputed value.
def deposit(workingAccount):
while True:
try:
amount = float(input("\nEnter amount you want to deposit: "))
try:
amount = round(amount, 2)
if amount > 0:
answer = correctAmount(amount)
if answer == True:
print("Verifying deposit")
time.sleep(random.randint(1, 2))
return amount
elif amount == 0:
answer = correctAmount(amount)
if answer == True:
print("Canceling deposit")
time.sleep(random.randint(1, 2))
return amount
else:
print("\nPlease enter an amount greater than or equal to 0")
except TypeError:
print("\nAmount entered is invalid... Try again")
except ValueError:
print("\nAmount entered is invalid... Try again")
# End of program to print out account information and return false to end main loop
def exitATM(workingAccount):
print("\nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", workingAccount.annualInterestRate)
print("Monthly Interest Rate: ", workingAccount.annualInterestRate / 12)
print("Thanks for using this ATM")
return False
def main():
# Creating all accounts possible, could be stored or read from a file/database instead for better functionality overall.
accounts = []
for i in range(1000, 9999):
account = Accounts(i, 0)
accounts.append(account)
# ATM Processes loop
loop = True
while loop == True:
pin = getAccountPin()
print(pin)
# Account session loop
while loop == True:
# Menu Selection
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
selection = getSelection()
# Getting working account object by comparing pins
for acc in accounts:
# Comparing user inputted pin to pins created
if acc.pin == pin:
workingAccount = acc
break
# View Balance
if selection == 1:
print(f"\nYour balance is ${viewBalance(workingAccount)}")
# Withdraw
elif selection == 2:
workingAccount.withdraw(withdraw(workingAccount))
print(f"\nUpdated Balance: ${workingAccount.balance}")
# Deposit
elif selection == 3:
workingAccount.deposit(deposit(workingAccount))
print(f"\nUpdated Balance: ${workingAccount.balance}")
# Exit
elif selection == 4:
loop = exitATM(workingAccount)
# Invalid input
else:
print("Enter a valid choice")
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:35:25.723",
"Id": "488334",
"Score": "4",
"body": "Beware: monthly interest rate is NOT 1/12th of the annual interest rate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T21:00:42.993",
"Id": "488347",
"Score": "3",
"body": "So I can't have 0805 as my pin?"
}
] |
[
{
"body": "<p>Nice implementation, few suggestions:</p>\n<ul>\n<li><p>it's not realistic to use the pin as the account id. To make it more realistic you could ask for the account id first and then for the pin. Entering the account id would be the simulation of "inserting the card in the ATM".</p>\n</li>\n<li><p>The function <code>getAccountPin()</code> requests input from the user, a better name would be <code>requestAccountPin()</code></p>\n</li>\n<li><p>The function <code>viewBalance</code> below could be a method of <code>Accounts</code> instead of a global function:</p>\n<pre><code>def viewBalance(workingAccount):\n # Returns the current working accounts balance\n return workingAccount.balance\n</code></pre>\n</li>\n<li><p>To simplify the function <code>withdraw(workingAccount)</code> move the checks on the balance directly in <code>Accounts.withdraw</code>. For example:</p>\n<pre><code>def withdraw(self, amount):\n if amount > 0 and self.balance - amount >= 0:\n self.balance -= amount\n return True\n return False\n</code></pre>\n</li>\n<li><p>Same for <code>deposit(workingAccount)</code>, it can be simplified by moving some of the logic into <code>Accounts.deposit</code>:</p>\n<pre><code>def deposit(self, amount):\n if amount > 0:\n self.balance += amount\n return True\n return False\n</code></pre>\n</li>\n<li><p>The class <code>Accounts</code> contains the information of a single account, so you can just call it <code>Account</code></p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T03:24:36.780",
"Id": "249143",
"ParentId": "249138",
"Score": "11"
}
},
{
"body": "<p>Your code is nicely structured into short well-named functions, that's great to see. Here's a few points to improve:</p>\n<ul>\n<li><p>check <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> convention about variables naming. Function and variable names should follow <code>snake_case</code>, so instead of <code>def viewBalance(workingAccount):</code> it's better to use <code>def view_balance(working_account):</code></p>\n</li>\n<li><p>try-except blocks should be wrapping relevant code as tightly as possible. If you will wrap your whole code into one big try-except, then technically no error will happen, but sometime you can catch an exception you don't intend to catch, and it can be handled improperly. For example in <code>withdraw</code> function you have two wide nested try-except blocks with the same message. They can be merged together, and they can (should) wrap only the relevant lines. The nice side-effect is that the other code will be less indented, which can improve code readability.</p>\n</li>\n<li><p>there's also a bug in there. In first condition you are checking if the withdrawn amount is greater than zero, but it should be <em>greater or equal</em> instead.</p>\n</li>\n<li><p>you're calling <code>correctAmount()</code> only in case the amount is acceptable or zero, but it should be called even if the balance is incorrect (which can happen more likely exactly because of incorrectly entered amount). And in such case instead of repeating it three times, you can call it only once before doing the branching logic.</p>\n</li>\n</ul>\n<pre><code>def withdraw(working_account):\n while True:\n # try-except block should be wrapping the relevant code as tightly as possible\n try:\n amount = float(input("\\nEnter amount you want to withdraw: "))\n amount = round(amount, 2)\n except (ValueError, TypeError):\n print("\\nAmount entered is invalid... Try again")\n continue\n\n # dont repeat `correct_amount` in multiple places\n if not correct_amount(amount):\n continue\n\n # the second condition should be >= instead of >\n if amount > 0 and (working_account.balance - amount) >= 0:\n print("Verifying withdraw")\n time.sleep(random.randint(1, 2))\n return amount\n\n elif (working_account.balance - amount) < 0:\n print("\\nYour balance is less than the withdraw amount")\n elif amount == 0:\n print("Canceling withdraw")\n time.sleep(random.randint(1, 2))\n return amount\n else:\n print("\\nPlease enter an amount greater than or equal to 0")\n</code></pre>\n<ul>\n<li>the following are just small gotchas you'd discover over time yourself, but here's a shortcut path: in Python you don't have to compare values explicitly. Everything except <code>0</code>, <code>None</code>, <code>""</code>, <code>False</code> and empty collections is evaluated to <code>True</code>, so your comparison can be shortened:</li>\n</ul>\n<pre><code>while loop == True:\n do_something()\n# you can use only `while loop:` instead:\nwhile loop:\n loop = "any value, the condition will still work"\n</code></pre>\n<ul>\n<li>similarly, if you need to compare a return value you get from function, but then you don't work with it further, you don't have to assign it to a temporary variable:</li>\n</ul>\n<pre><code>answer = correctAmount(amount)\nif answer == True:\n print("Verifying withdraw")\n\n# you can write this instead:\nif correct_amount(amount):\n print("Verifying withdraw")\n</code></pre>\n<ul>\n<li>comparisons can be chained together:</li>\n</ul>\n<pre><code>if pin >= 1000 and pin <= 9999:\n return pin\n# you can use following:\nif 1000 <= pin <= 9999:\n return pin\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T03:32:52.733",
"Id": "249144",
"ParentId": "249138",
"Score": "10"
}
},
{
"body": "<p>I notice a couple of areas that I think could be improved:</p>\n<ul>\n<li><p>Generally, Python code uses <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"noreferrer\">snake case</a> instead of <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"noreferrer\">camel case</a> for formatting variable names. So for example:</p>\n<pre><code>def getMonthlyInterestRate(self):\n return self.annualInterestRate / 12\n</code></pre>\n<p>Would become:</p>\n<pre><code>def get_monthly_interest_rate(self):\n return self.annualInterestRate / 12\n</code></pre>\n<p>But this really isn't super important. As long as you stay consistent with either one, your code will be readable.</p>\n</li>\n<li><p>In <code>getAccountPin</code>, <code>if pin >= 1000 and pin <= 9999:</code> can be simplified too <code>1000 <= pin <= 9999</code>. This can also be done for your other in range conditionals (e.x: <code>selection >= 1 and selection <= 4</code> to <code>if 1 <= selection <= 4:</code>).</p>\n</li>\n<li><p>I'm not sure why <code>viewBalance</code> needs to exist? Just get the working account's balance directly using <code>.balance</code>, no need for a getter function here. In general, it's considered better practice to avoid using getters when possible.</p>\n</li>\n<li><p>In <code>deposit</code> and <code>withdraw</code>, you don't need nested <code>try/except</code> blocks. <code>except</code> can take one, <em>or more</em>, errors to intercept: In your case<code>except (ValueError, TypeError)</code>. This will make your code much cleaner.</p>\n</li>\n<li><p>I think <code>deposit</code> and <code>withdraw</code> should be methods of <code>Accounts</code> objects, not standalone methods. If <code>Accounts</code> represents bank accounts, it make sense to associate the action of withdrawing and depositing money with the bank accounts.</p>\n</li>\n<li><p><code>deposit</code> never uses its argument <code>workingAccount</code>.</p>\n</li>\n<li><p>Avoid using the <code>if var == True</code>. It's much simpler and cleaner to just do <code>if var</code> to test whether or not <code>var</code> is <code>True</code>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T03:41:03.343",
"Id": "249145",
"ParentId": "249138",
"Score": "6"
}
},
{
"body": "<p>You're on a good start and already have several useful comments in other reviews.</p>\n<p>A lot of the code is concerned with the details of getting input from the user\n-- and it is both tedious and repetitive. I would encourage you to think about\nhow one might generalize the user input process: display message; get input;\nconvert the reply to a meaningful value; validate the value; print a message\nand/or return a value. Here's a rough sketch of the idea:</p>\n<pre><code>def getAccountPin():\n return get_user_input(\n message = 'Enter four digit account pin',\n converter = int,\n validator = (lambda x: x in range(1000, 10000)),\n )\n\ndef getSelection():\n return get_user_input(\n message = 'Enter your selection',\n converter = int,\n validator = (lambda x: x in range(1, 5)),\n )\n\ndef get_user_input(message, converter, validator):\n while True:\n reply = input('\\n' + message + ': ')\n try:\n value = converter(reply)\n except Exception:\n print('Invalid entry. Try again')\n if validator(value):\n return value\n else:\n print('Bad value. Try again')\n</code></pre>\n<p>Some of your current functions fit that approach, but others present some interesting\n(and probably solvable) challenges. Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T03:32:52.300",
"Id": "249195",
"ParentId": "249138",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T00:30:33.590",
"Id": "249138",
"Score": "10",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented"
],
"Title": "ATM code for account balance, withdrawals and deposits"
}
|
249138
|
<p>I've written the following data analysis code (using just a couple lines from CERN's ROOT data analysis framework). It's designed to find coincidences in three sets of data (timestamps from an experiment for a given year) by pairing up each timestamp in one dataset with the closest possible timestamp in both the second and third datasets, then sorting those pairings by maxval - minval, and keeping only the closest "unique" coincidences (no two coincidences may share a timestamp, and each coincidence is a triplet, with one timestamp contributed by each dataset). The code works perfectly, however it's a bit messy and could probably use some cleaning up. Perhaps there are some clever tricks for simplifying some of this that I'm unaware of as well. Please do be very critical, I appreciate the feedback.</p>
<p>My code:</p>
<pre><code>int binary_search(const vector<double> &vec, const double key) {
int high = vec.size();
int low = 0;
unsigned int mid;
while(low <= high){
mid = low + (high-low)/2;
if(vec[mid] == key) return mid;
else if(vec[mid] < key) low = mid + 1;
else high = mid - 1;
}
return mid;
}
void binary(){
ROOT::RDataFrame statn1("D", "./path/to/data");
ROOT::RDataFrame statn2("D", "./path/to/data");
ROOT::RDataFrame statn3("D", "./path/to/data");
vector<double> vec2, vec3;
statn2.Foreach([&](double tstamp){vec2.push_back(tstamp);},{"UNIX"});
statn3.Foreach([&](double tstamp){vec3.push_back(tstamp);},{"UNIX"});
vector<vector<double> > coincidences;
statn1.Foreach([&](double tstamp){},
int res_i = binary_search(vec2, tstamp);
double p = dabs(tstamp-vec2[res_i]);
double q = dabs(tstamp-vec2[res_i+1]);
double r = dabs(tstamp-vec2[res_i-1]);
if(r<q && r<p) --res_i;
else if(q<r && q<p) ++res_i;
int res_j = binary_search(vec3, tstamp);
p = dabs(tstamp-vec3[res_j]);
q = dabs(tstamp-vec3[res_j+1]);
r = dabs(tstamp-vec3[res_j-1]);
if(r<q && r<p) --res_j;
else if(q<r && q<p) ++res_j;
double first = tstamp-vec2[res_i];
double second = tstamp-vec3[res_j];
double third = vec2[res_i] - vec3[res_j];
double fourth = std::min(std::min(first, second), third);
coincidences.push_back({tstamp, vec2[res_i], vec3[res_j], first, second, third, fourth});
{"UNIX"});
std::sort(coincidences.begin(), coincidences.end(),
[](const vector<double>& A, const vector<double>& B){
return A[6] < B[6];
});
std::set<double> cache;
for(auto pair : coincidences){
if(cache.find(pair[1]) == cache.end() && cache.find(pair[2]) == cache.end()) {
std::cout << "Coincidence found!\n";
cache.insert(pair[1]); cache.insert(pair[2]);
}
}
}
</code></pre>
<p>EDIT: CERN's ROOT framework can be found at <a href="https://root.cern.ch" rel="nofollow noreferrer">https://root.cern.ch</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T01:01:39.643",
"Id": "488287",
"Score": "0",
"body": "Are these 2 functions members of a class, and if so could you please include the rest of the class. Can you please provide a link to the CERN's ROOT data analysis framework."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T01:11:19.637",
"Id": "488289",
"Score": "1",
"body": "@pacmaninbw They are not. I've added a link to ROOT (root.cern.ch). Note that the only lines using ROOT are the first 6 of `binary()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T01:12:36.957",
"Id": "488290",
"Score": "1",
"body": "@pacmaninbw I should add that, perhaps it's a bit confusing that this does not have, for instance, an `int main()` function. This is running in the ROOT intepereter which, while *almost* perfectly ISO compliant, has a couple small quirks, such as having the main function be a void with the name being the same as the filename. Here, `void binary()` is the equivalent of `int main()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:12:17.650",
"Id": "488325",
"Score": "1",
"body": "does it have extra brace at `statn1.Foreach([&](double tstamp){},` and it should be lambda with all tabbed code instead?"
}
] |
[
{
"body": "<h3>Undefined behavior</h3>\n<p>There's UB in case when empty vector passed to the <code>binary_search</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>unsigned int mid;\n</code></pre>\n<p>it is uninitialised and will pop whatever compiler think he want in release mode. To solve this issue it is require initialise value with some error value (usually it is <code>~0</code> but you can choose your own), or use <code>std::optional</code> (c++17) and handle error case in lambda.\nprobably it is not an issue if vectors guaranteed to be non-empty and there's at least one proper value inside them.</p>\n<h3>mix of signed and unsigned types</h3>\n<p>Return type of <code>binary_search</code> is <code>int</code>, but branches can be <code>unsigned int</code>.\nAs it is actually return position in vector best way to use special unsigned integral type macro <code>size_t</code> meant to be used like this. So final check will be like.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>...\nconstexpr size_t ERR = ~0;\nsiz_t res_i = binary_search(vec2, tstamp);\nif (ERR == res_i) return; // early exit from lambda\n...\n</code></pre>\n<p>But that kind of handling raise question about how to handle <code>res_i--</code> if binary search return position 0. It probably will return INT_MAX for according integral type, but that kind of subtraction is implementation defined behavior so result defined by compiler.</p>\n<h3>potential out of bounds</h3>\n<p>if binary search return <code>0</code> position access to <code>-1</code> will crash your program.</p>\n<pre><code>double r = dabs(tstamp-vec2[res_i-1]);\n</code></pre>\n<p>tightly related to previous issues.\nprobably it is not an issue if found position never meant to be 0</p>\n<h3>unnecessary variable reusing</h3>\n<p>If your program don't meant to be run on some embed device this kind of optimization basically do nothing - compilers usually smart enough to get rid of it by themselves. Probably good idea create some small function and <code>p</code>,<code>q</code>,<code>r</code> manipulations in it. Also it will prevent chance to make copy-paste errors</p>\n<pre><code>size_t someRoutine(double tstamp, const auto& vec, size_t res) {\n double p = dabs(tstamp-vec[res]); \n double q = dabs(tstamp-vec[res+1]); \n double r = dabs(tstamp-vec[res-1]);\n \n if(r<q && r<p) return res-1;\n if(q<r && q<p) return res+1;\n return res;\n}\n//...\nres_i = someRoutine(tstamp, vec2, res_i);\nres_j = someRoutine(tstamp, vec3, res_j);\n\n</code></pre>\n<h3>structs clearer than vector</h3>\n<p>it is good idea to create a struct instead of using a vector - less memory print, clearer usage.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct SomData{\n double tstamp, vec2,vec3, first, second, third, fourth;\n};\n//...\ncoincidences.push_back({tstamp, vec2[res_i], vec3[res_j], first, second, third, fourth});\n// OR\n// coincidences.emplace_back(tstamp, vec2[res_i], vec3[res_j], first, second, third, fourth); // construct struct in-place, \n//...\nstd::sort(coincidences.begin(), coincidences.end(),\n [](const SomData& A, const SomData>& B){\n return A.fourth < B.fourth;\n});\n///...\ncache.insert(pair.vec2);cache.insert(pair.vec3);\n</code></pre>\n<h3>no need to use find if you don't need an iterator</h3>\n<p>maps ands sets have convenient method <code>count</code> which represents amount of items found by the key. You just need to check whether its zero or one</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(cache.count(pair.vec2) == 0 && cache.count(pair.vec3) == 0) {\n std::cout << "Coincidence found!\\n";\n cache.insert(pair.vec2);\n cache.insert(pair.vec3);\n}\n</code></pre>\n<h3>cycle copy elements</h3>\n<p>probably just missed <code>&</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for(const auto& pair : coincidences){\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:33:26.923",
"Id": "249167",
"ParentId": "249139",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249167",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T00:52:23.560",
"Id": "249139",
"Score": "3",
"Tags": [
"c++",
"algorithm"
],
"Title": "Data analysis code (finds coincidences in three sets of data)"
}
|
249139
|
<p>I'm after some constructive criticism on my code and maybe some ways to simplify before I expand it to include other sites. I am new to R and coding and have been working on this problem for weeks now.</p>
<p>I need to graph the last 10 days of data from 20 remote sites. There are 3 csv files from each site that I bring in via FTP. I will be running this every half hour as new data is written to the csv files.</p>
<p>My main problem has been the dynamic IP address/folder path which changes every month. So on the first day of the month, the csv files I download will be in a new folder.</p>
<p>My fix so far has been to download the last months data and this months new data, then combine these and filter for last 10 days only. I have a working solution but it's not very elegant and after the 10th day of each month it is downloading data which I don't even need or use.</p>
<p>What I would like is to only download the new data every half hour and append to the old data. Also accounting for any site outage which happens occasionally.</p>
<p>I realise my code is not reproducible, but it is working and I am mainly looking for red flags/tips to shorten or better ways of writing/other ideas to consider.</p>
<p>So here it is, I really appreciate the criticism, go hard, but be kind :)</p>
<pre><code>#SiteA
SiteAip <- "10.10.10.10"
SiteA <- "usernamea"
PW <- "passwd"
#SiteB
SiteBip <- "20.20.20.20"
SiteB <- "usernameb"
PW <- "passwd"
library(tidyverse)
library(data.table)
library(lubridate)
# This months date format to build folder path for current month download
Year <-format(Sys.Date(), format="%Y")
Month <- format(Sys.Date(), format="%B")
MM <- format(Sys.Date(), format="%m")
# Last months date format to build folder path for last month download
LM <- format(Sys.Date() %m+% months(-1), format="%B")
Lmon <- format(Sys.Date() %m+% months(-1), format="%m")
LY <- format(Sys.Date() %m+% months(-1), format="%Y")
# Download last month csv1 file
SiteAcsv1old <- glue::glue("ftp://{SiteA}:{PW}@{SiteAip}/1data/SiteA/{LY}/{LM}/SiteA}{LY}-{Lmon} csv1.txt")
SiteAcsv1old <- fread(SiteAcsv1old, header = FALSE, select = c(1, 3, 4),
col.names = c("DateTime", "Latitude", "Longitude"), sep = " ")
# Download this month csv1 file
SiteAcsv1new <- glue::glue("ftp://{SiteA}:{PW}@{SiteAip}/1data/SiteA/{Year}/{Month}/SiteA}{Year}-{MM} csv1.txt")
SiteAcsv1new <- fread(SiteAcsv1new, header = FALSE, select = c(1, 3, 4),
col.names = c("DateTime", "Latitude", "Longitude"), sep = " ")
#append new to old csv1 data
SiteAcsv1app <- unique(rbindlist(list(SiteAcsv1old, SiteAcsv1new)))
# Last 10 days of csv1 data
SiteAcsv1ten <- SiteAcsv1app %>%
filter(between(as_datetime(DateTime), Sys.Date() - 10, Sys.Date()))
#Last month csv2 file
SiteAcsv2old <- glue::glue("ftp://{SiteA}:{PW}@{SiteAip}/1data/SiteA/{LY}/{LM}/SiteA}{LY}-{Lmon}.csv2")
SiteAcsv2old <- fread(SiteAcsv2old, header = FALSE, select = c( 1, 2, 3, 5, 6, 18),
col.names = c("DateTime", "A", "B", "C", "D", "E"), sep = ",")
#This month csv2 file
SiteAcsv2new <- glue::glue("ftp://{SiteA}:{PW}@{SiteAip}/1data/SiteA/{Year}/{Month}/SiteA}{Year}-{MM}.csv2")
SiteAcsv2new <- fread(SiteAcsv2new, header = FALSE, select = c( 1, 2, 3, 5, 6, 18),
col.names = c("DateTime", "A", "B", "C", "D", "E"), sep = ",")
#append new to old csv2 data
SiteAcsv2app <- unique(rbindlist(list(SiteAcsv2old, SiteAcsv2new)))
# Last 10 days of csv2 data
SiteAcsv2ten <- SiteAcsv2app %>%
filter(between(as_datetime(DateTime), Sys.Date() - 10, Sys.Date()))
#Last month csv3 file
SiteAcsv3old <- glue::glue("ftp://{SiteA}:{PW}@{SiteAip}/1data/SiteA/{LY}/{LM}/SiteA}{LY}-{Lmon}.csv3")
SiteAcsv3old <- fread(SiteAcsv3old, header = FALSE, select = c( 1, 3),
col.names = c("DateTime", "F"), sep = ",")
#This month csv3 file
SiteAcsv3new <- glue::glue("ftp://{SiteA}:{PW}@{SiteAip}/1data/SiteA/{Year}/{Month}/SiteA}{Year}-{MM}.csv3")
SiteAcsv3new <- fread(SiteAcsv3new, header = FALSE, select = c( 1, 3),
col.names = c("DateTime", "F"), sep = ",")
#append new to old csv3 data
SiteAcsv3app <- unique(rbindlist(list(SiteAcsv3old, SiteAcsv3new)))
# Last 10 days of csv3 data
SiteAcsv3ten <- SiteAcsv3app %>%
filter(between(as_datetime(DateTime), Sys.Date() - 10, Sys.Date()))
# Timestamps for csv1/csv2/csv3 are different (out by a few minutes)
# I need to round each of these down to the nearest half hour and merge data tables on "DateTime"
# Round "DateTime" to previous half hour -
SiteAcsv1ten[, DateTime:=as_datetime(DateTime, tz = "Australia/Queensland")]
SiteAcsv1ten[, DateTime := floor_date(DateTime, "30 minutes")]
SiteAcsv2ten[, DateTime:=as_datetime(DateTime, tz = "Australia/Queensland")]
SiteAcsv2ten[, DateTime := floor_date(DateTime, "30 minutes")]
SiteAcsv3ten[, DateTime:=as_datetime(DateTime, tz = "Australia/Queensland")]
SiteAcsv3ten[, DateTime := floor_date(DateTime, "30 minutes")]
# merge csv2/csv3/csv1 by DateTime
SiteAall <- Reduce(merge, list(SiteAcsv2ten, SiteAcsv3ten, SiteAcsv1ten))
# Plot data - Just basic for the moment, I will add labels and pretty up later
SiteAplot1 <- ggplot(SiteAall) +
geom_line(aes(DateTime, B), colour="green") +
geom_line(aes(DateTime, C), color="orange")
SiteAplot1 + labs(title = "SiteA1")
SiteAplot2 <- ggplot(SiteAall) +
geom_line(aes(DateTime, D), colour="red") +
geom_line(aes(DateTime, F), color="blue")
SiteAplot2 + labs(title = "SiteA2")
## working up to here
############################################################################################################
#SiteB
# Same as SiteA but with necessary changes
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T05:31:18.123",
"Id": "488302",
"Score": "0",
"body": "Welcome to CodeReview@SE. Which version of FTP - *RFC 3659* including [MLST](https://tools.ietf.org/html/rfc3659#section-7)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T05:49:15.353",
"Id": "488307",
"Score": "0",
"body": "Cheers for the welcome. No idea about any of that. But FTP is working fine for my purposes and seems pretty quick. File sizes are only about 30 - 300KB. Although I am not sure how it will go when I will be importing about 150 csv files by FTP every half hour."
}
] |
[
{
"body": "<p>So, here is the criticism. :)</p>\n<p>Generally, you can improve your code (and concurrently also solve most of your scaling up issues) by reorganizing your code into reusable functions and using descriptive variable names.</p>\n<p>Please note that I did not check if the code below executes withouth an error!</p>\n<h1>Library Imports at the Top Source Code</h1>\n<p>Generally, you put library imports at the top of the source code. Except you give some explanation of why you did not do it.</p>\n<h1>Scaling to more Sites</h1>\n<h2>Site Credentials</h2>\n<p>Since you want to scale you code up to N sites, your code is clearly not sustainable. This starts here</p>\n<pre class=\"lang-r prettyprint-override\"><code>#SiteA\nSiteAip <- "10.10.10.10"\nSiteA <- "usernamea"\nPW <- "passwd"\n\n#SiteB\nSiteBip <- "20.20.20.20"\nSiteB <- "usernameb"\nPW <- "passwd"\n</code></pre>\n<p>and this continous till the end of your code. Can you imagine touching all of your code if you want to add just one site? Ideally, this would all be done automatically. For now, I would propose the following.</p>\n<pre class=\"lang-r prettyprint-override\"><code>get.site.credentials <- function(path.to.site.credentials)\n{\n return(read.csv(file = path.to.site.credentials, # YOUR SETTINGS GO HERE))\n}\n</code></pre>\n<p>and then below your library imports you simply do</p>\n<pre class=\"lang-r prettyprint-override\"><code>df.site.credentials <- get.site.credentials(path = PATH)\n</code></pre>\n<p>and <code>PATH</code> should be the path to your csv file.</p>\n<h2>Downloading CSV files</h2>\n<p>Downloading your csv files is also a repetitive task. So, we can wrap this into a function too.</p>\n<pre class=\"lang-r prettyprint-override\"><code>get.csv.file.via.ftp <- function(site.user.name, site.pw, site.ip,\n date.year, date.month, date.mm)\n{\n # I'm not sure what you want to do here exactly, though .....\n ftp.url <- glue::glue("ftp://{site.user.name}:{site.pw}@{site.ip}/1data/SiteA/{date.year}/{date.month}/SiteA}{date.year}-{date.mm}.csv3")\n\n df <- fread(ftp.url,\n header = FALSE,\n select = c( 1, 3), \n col.names = c("DateTime", "F"), sep = ",")\n\n return(df)\n}\n</code></pre>\n<p>Please look carefully at variable <code>ftp.url</code>. This might not work for all of your code, e.g. when you have url's that are different. However, it is easy to fix this too. One way, for exampe, would be to introduce an <code>if</code> statement into the function that lets you choose your <code>url</code>.</p>\n<h1>Month Format generation</h1>\n<p>Your code to get the date formats is unbelivabely similar. Hence, we can abstract here to.</p>\n<pre class=\"lang-r prettyprint-override\"><code>get.date.month <- function(integer)\n{\n my.date <- c()\n\n my.date$year <- format(Sys.Date() % m + % months(integer), format="%Y")\n my.date$month <- format(Sys.Date() % m + % months(integer), format="%B")\n my.date$mm <- format(Sys.Date() % m + % months(integer), format="%m")\n\n return(my.date)\n}\n\nget.date.current.month <- function()\n{\n return(get.date.month(0))\n}\n\nget.date.last.month <- function()\n{\n return(get.date.month(-1))\n}\n</code></pre>\n<p>By first abstracting the code into function <code>get.date.month</code> and then building two wrappers around it with <code>get.date.current.month</code> and <code>get.date.last.month</code> you seprate your code clearly and your intention becomes clear. Further, it avoids mistakes in the future because no one should touch the wrapper functions. Of course, you don't have to be that expressive. Also, I would try to find better function names.</p>\n<h1>Final Comment</h1>\n<p>There are more things that can be improved in your code, mostly through abstracting most of your code into functions and using descriptive variables names - as stated at the beginning.</p>\n<p>HTH!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:01:04.807",
"Id": "252155",
"ParentId": "249141",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T02:08:24.647",
"Id": "249141",
"Score": "3",
"Tags": [
"datetime",
"r",
"ftp"
],
"Title": "Does this R code look ok to expand out to other sites?"
}
|
249141
|
<p>I try to implement the features of the js <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="nofollow noreferrer">Promise</a> using Go.
Currently, I had implemented <code>Promise.all()</code>, <code>Promise.allSettled()</code> and <code>Promise.race()</code> static methods.</p>
<p>Code here:</p>
<pre class="lang-golang prettyprint-override"><code>package go_promise
import (
"sort"
)
type Promiser interface {
AllSettled(iterable []Workload) []Result
All(iterable []Workload) []Result
Race(iterable []Workload) *Result
}
type promise struct {
}
type Workload func(args ...interface{}) interface{}
type Result struct {
Idx int
R interface{}
}
func NewPromise() *promise {
return &promise{}
}
func (p *promise) AllSettled(iterable []Workload) []Result {
if len(iterable) == 0 {
return nil
}
c := make(chan struct{}, len(iterable))
r := make([]Result, len(iterable))
for idx, iter := range iterable {
iter := iter
idx := idx
go func() {
r[idx].Idx = idx
r[idx].R = iter()
c <- struct{}{}
}()
}
for i := 0; i < len(iterable); i++ {
<-c
}
sort.Slice(r, func(i, j int) bool {
return r[i].Idx < r[j].Idx
})
close(c)
return r
}
func (p *promise) All(iterable []Workload) []Result {
if len(iterable) == 0 {
return nil
}
c := make(chan Result, len(iterable))
errc := make(chan Result, 1)
r := []Result{}
for idx, iter := range iterable {
iter := iter
idx := idx
go func() {
result := iter()
if err, ok := result.(error); ok {
errc <- Result{Idx: idx, R: err}
} else {
c <- Result{Idx: idx, R: result}
}
}()
}
for {
select {
case result := <-errc:
return []Result{result}
case result := <-c:
r = append(r, result)
if len(r) == len(iterable) {
sort.Slice(r, func(i, j int) bool {
return r[i].Idx < r[j].Idx
})
return r
}
}
}
}
func (p *promise) Race(iterable []Workload) *Result {
if len(iterable) == 0 {
return nil
}
c := make(chan *Result, len(iterable))
for _, iter := range iterable {
iter := iter
go func() {
r := Result{R: iter()}
c <- &r
}()
}
return <-c
}
</code></pre>
<p>unit test:</p>
<pre class="lang-golang prettyprint-override"><code>package go_promise_test
import (
"errors"
"reflect"
"testing"
"time"
go_promise "github.com/mrdulin/golang/src/go-promise"
)
func workloadGen(i interface{}, options ...interface{}) go_promise.Workload {
return func(args ...interface{}) interface{} {
var sec time.Duration = 1
if len(options) != 0 {
sec = options[0].(time.Duration)
}
time.Sleep(time.Second * sec)
return i
}
}
func TestPromise_AllSettled(t *testing.T) {
t.Run("should settle all workloads and return results", func(t *testing.T) {
p := go_promise.NewPromise()
w1 := workloadGen(1)
w2 := workloadGen(2)
w3 := workloadGen(3)
ws := []go_promise.Workload{w1, w2, w3}
got := p.AllSettled(ws)
want := []go_promise.Result{{Idx: 0, R: 1}, {Idx: 1, R: 2}, {Idx: 2, R: 3}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got: %+v, want: %+v", got, want)
}
})
t.Run("should settle empty workloads and return nil", func(t *testing.T) {
p := go_promise.NewPromise()
ws := []go_promise.Workload{}
got := p.AllSettled(ws)
var want []go_promise.Result
if !reflect.DeepEqual(got, want) {
t.Fatalf("got: %#v, want: %#v", got, want)
}
})
}
func TestPromise_All(t *testing.T) {
t.Run("should handle all workloads", func(t *testing.T) {
p := go_promise.NewPromise()
w1 := workloadGen(1)
w2 := workloadGen(2)
w3 := workloadGen(3)
ws := []go_promise.Workload{w1, w2, w3}
got := p.All(ws)
want := []go_promise.Result{{Idx: 0, R: 1}, {Idx: 1, R: 2}, {Idx: 2, R: 3}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got: %#v, want: %#v", got, want)
}
})
t.Run("should reject the promise when any workload is rejected", func(t *testing.T) {
p := go_promise.NewPromise()
err := errors.New("network")
w1 := workloadGen(1)
w2 := workloadGen(2)
w3 := workloadGen(err)
ws := []go_promise.Workload{w1, w2, w3}
got := p.All(ws)
want := []go_promise.Result{{Idx: 2, R: err}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got: %+v, want: %+v", got, want)
}
})
}
func TestPromise_Race(t *testing.T) {
t.Run("should race all resolved promise", func(t *testing.T) {
p := go_promise.NewPromise()
var t1 time.Duration = 2
var t2 time.Duration = 1
w1 := workloadGen(1, t1)
w2 := workloadGen(2, t1)
w3 := workloadGen(3, t2)
ws := []go_promise.Workload{w1, w2, w3}
got := p.Race(ws)
want := &go_promise.Result{Idx: 0, R: 3}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got: %+v, want: %+v", got, want)
}
})
t.Run("should race promises with a rejected promise", func(t *testing.T) {
p := go_promise.NewPromise()
err := errors.New("network")
var t1 time.Duration = 2
var t2 time.Duration = 1
w1 := workloadGen(1, t1)
w2 := workloadGen(2, t1)
w3 := workloadGen(err, t2)
ws := []go_promise.Workload{w1, w2, w3}
got := p.Race(ws)
want := &go_promise.Result{Idx: 0, R: err}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got: %+v, want: %+v", got, want)
}
})
}
</code></pre>
<p>unit test result:</p>
<pre class="lang-bsh prettyprint-override"><code>☁ go-promise [master] ⚡ go test -v -race
=== RUN TestPromise_AllSettled
=== RUN TestPromise_AllSettled/should_settle_all_workloads_and_return_results
=== RUN TestPromise_AllSettled/should_settle_empty_workloads_and_return_nil
--- PASS: TestPromise_AllSettled (1.00s)
--- PASS: TestPromise_AllSettled/should_settle_all_workloads_and_return_results (1.00s)
--- PASS: TestPromise_AllSettled/should_settle_empty_workloads_and_return_nil (0.00s)
=== RUN TestPromise_All
=== RUN TestPromise_All/should_handle_all_workloads
=== RUN TestPromise_All/should_reject_the_promise_when_any_workload_is_rejected
--- PASS: TestPromise_All (2.01s)
--- PASS: TestPromise_All/should_handle_all_workloads (1.00s)
--- PASS: TestPromise_All/should_reject_the_promise_when_any_workload_is_rejected (1.00s)
=== RUN TestPromise_Race
=== RUN TestPromise_Race/should_race_all_resolved_promise
=== RUN TestPromise_Race/should_race_promises_with_a_rejected_promise
--- PASS: TestPromise_Race (2.01s)
--- PASS: TestPromise_Race/should_race_all_resolved_promise (1.00s)
--- PASS: TestPromise_Race/should_race_promises_with_a_rejected_promise (1.00s)
PASS
ok github.com/mrdulin/golang/src/go-promise 5.354s
</code></pre>
<p>Although there is no data race condition problem, I am not sure if there are goroutine memory leaks, performance issues, and other issues that have not been considered. Please help me review my code, thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T12:36:41.690",
"Id": "249152",
"Score": "3",
"Tags": [
"javascript",
"go",
"promise"
],
"Title": "Go language implementation of js promise static method"
}
|
249152
|
<p>I recently reviewed a PR and saw the following.</p>
<pre><code>const parts = someString.split('.');
return parts[parts.length - 1];
</code></pre>
<p>was changed to</p>
<pre><code>const [last] = someString.split('.').reverse();
return last;
</code></pre>
<p>I commented that I am against the change for the reasons that it is harder to read and not performant.</p>
<p>The answer was that it is only hard to read, because I am not used to it and that performance does not matter if you use big frameworks like React for example.</p>
<p>Who is right and why?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T00:13:24.283",
"Id": "488363",
"Score": "8",
"body": "How much is this profession being dumbed down that `parts[parts.length - 1]` is considered \"hard to read\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T01:05:40.403",
"Id": "488370",
"Score": "1",
"body": "\"performance does not matter if you use big frameworks like React for example\" - they have a point so: when you replace pile of poorly written code that searches dom to manually replace value one-by-one with big heavily optimized framework like Reach you have a lot of free room to write slower code till you match your original slow version..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T01:46:43.587",
"Id": "488371",
"Score": "2",
"body": "@Will It looks like the OP is saying the second method is hard to read, not the `parts[parts.length - 1]` part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T03:08:24.997",
"Id": "488380",
"Score": "1",
"body": "@KodosJohnson Yes, and I agree with the OP, but some of the answers below and presumably the person responsible for OP's PR do imply that `parts[parts.length - 1]` is somehow hard to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T16:51:40.730",
"Id": "488438",
"Score": "0",
"body": "Using `const [last] = array` makes no sense here.\nIt's the same as `const last = array[0]`, but harder to read.\nTo me, it almost looks like they intentionally obfuscated their code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T06:44:00.367",
"Id": "488489",
"Score": "1",
"body": "@12Me21 Although it is *technically* the first element in the array, how is `const [last] = array` in any way difficult to read, let alone considered an obfuscation? Anyone familiar with object destructuring (so common in React now) ought to at least have some basic understanding of its cousin, array destructuring. I think more important to the code review the OP did was if *that* change was even necessary to begin with as it appears to have been a completely superfluous implementation change on the coder's part. \"Just because\" isn't really a valid reason to change working production code."
}
] |
[
{
"body": "<p>Well, it depends if the performance is an objective or it isn't. Now, I always would prefer good performance; now respect to the person who said "performance does not matter if you use big frameworks like React" oh, you don't really mean that, is Facebook that slow ?(Facebook uses React) do you know what implies to have a slow social network? Slow transactional operations not because the backend isn't optimized but the front? It is less users because they're boored waiting your app to response and switch to another media.</p>\n<p>Now, the second code fragment</p>\n<pre><code>const [last] = someString.split('.').reverse();\nreturn last;\n</code></pre>\n<p>is slower and does not exhibit the advantages of the language you are working with so why bother to even write it, if it's redundant?</p>\n<p>I mean, why would you need to reverse a substring to return the first character on it? (after reversed)</p>\n<p>You clearly can do</p>\n<pre><code>const parts = someString.split('.');\nreturn parts[parts.length - 1];\n</code></pre>\n<p>and that doesn't cost more time and is descriptive.</p>\n<p><em>The features of any language are there not to create "smart looking code" but to create more effective and efficient code.</em></p>\n<hr />\n<p>Note, as <a href=\"https://codereview.stackexchange.com/users/167260/certainperformance\">CertainPerformance</a> mentioned</p>\n<pre><code>return someString.split('.').pop();\n</code></pre>\n<p>is a great solution, easier to read, write and virtually takes the same time that the first fragment. (virtually, because internally those are different operations)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:50:19.833",
"Id": "249160",
"ParentId": "249153",
"Score": "5"
}
},
{
"body": "<p>I'm not entirely enthusiastic about either. The <code>parts[parts.length - 1]</code> using manual index lookup and subtraction may well take a moment to recognize, "Oh, this is getting the last element of the array". The second, using <code>.reverse()</code> followed by destructuring of the first item also could take a moment to think about before you understand what exactly it's doing.</p>\n<p>As an alternative, consider using <code>.pop()</code> instead, I think it's more intuitive than both:</p>\n<pre><code>return someString\n .split('.')\n .pop();\n</code></pre>\n<p>The only (tiny) downside is that the above isn't functional, since it mutates the split array - but that's OK, since the array isn't being used anywhere else.</p>\n<p>It's true that performance for something like this isn't really something to worry about if this is used in a larger project - what matters more is if it's easier to understand what the code is doing.</p>\n<p>Remember that if something isn't immediately intuitive, that's what comments are for, though all of these cases are self-documenting enough that it's not needed.</p>\n<p>Another way to make it easier to recognize what's going on would be to put this into a function with a descriptive name, such as <code>getLastProperty</code> (if the input is meant to show a path to a nested property lookup, for example - name it as appropriate for how it's meant to be used).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:52:56.133",
"Id": "488321",
"Score": "2",
"body": "Perhaps not so intuitive but a great solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:05:52.967",
"Id": "488323",
"Score": "0",
"body": "in this particular example, the value is returned. But what if it wasn't returned right away? I think it would be very misleading to mutate `parts` then (after `const parts = someString.split('.');` WDYT?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:13:17.050",
"Id": "488326",
"Score": "3",
"body": "@WilliMentzel Sure, if the array needs to be used later, then mutation via `.pop` earlier could well cease to be the right approach. If that was the situation, I'd use the index method instead, it's easier to read than the `.reverse()` / destructuring method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:15:31.953",
"Id": "488327",
"Score": "0",
"body": "@CertainPerformance Even if the array wouldn't be used (for now) but had a greater scope (vs. being returned right away) it would also be bad to mutate it because somewhere in the function someone might end up using this array thinking it is still complete. So, using pop only makes sense in this particular case (returning right away) would you agree?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:25:31.767",
"Id": "488328",
"Score": "3",
"body": "@Willi It depends how much of a stickler you are on a functional paradigm. Mutation is bad when it makes the code harder to read than the alternative, but I don't consider it a cardinal sin; sometimes aiming to be as functional as possible makes the code more confusing than the alternative. For example, when you want to (eventually) do something with a deeply nested object via a property string, splitting by `.` and then popping off the last item to have [(1) array of all properties but the last (2) the last property string] is [what I'd do](https://stackoverflow.com/a/56571772)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:25:34.920",
"Id": "488329",
"Score": "3",
"body": "YMMV; it's up to you, the standards of your codebase, and the situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T03:00:20.110",
"Id": "488379",
"Score": "2",
"body": "@WilliMentzel - In this case the nobody can use the array generated because it is not saved in any variable. However, if you have the array stored in a variable then do `x.slice().pop()`. There is zero arguments against using `pop`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T16:23:21.037",
"Id": "488436",
"Score": "1",
"body": "FWIW, you can do something similar without mutation by doing `x.split('.').slice(-1)`. Not sure it's more readable to the average coder though, which is ultimately the main argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T20:51:00.283",
"Id": "488465",
"Score": "0",
"body": "As @JosiahNunemaker said, just use `.slice(-1)`. It doesn't mutate the array and returns a **shallow copy** of the array items, but into a new array. The only downside is that you need to do `.slice(-1)[0]` to get the *value*. Otherwise, you get an array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T04:54:00.203",
"Id": "488483",
"Score": "0",
"body": "\"Perhaps not so intuitive but a great solution.\" Your solution was my immediate thought when I saw both OP snippets, like... why would they do either of those?"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:51:09.633",
"Id": "249161",
"ParentId": "249153",
"Score": "13"
}
},
{
"body": "<p><strong>tl;dr at the end.</strong></p>\n<p>In terms of 'performance', js engines are pretty well optimized. For something like this, performance should not be part of your argument against a given piece of code. In terms of readability, they are very similar so either works. There are better ways to think through this though.</p>\n<p>When it comes to PRs I would ponder on a few questions:</p>\n<ol>\n<li>What does the PR code in question actually change?</li>\n</ol>\n<p>Between the two snippets of code, there are no changes to the API of the calling code and no implementation changes to accommodate any edge cases. They work the same way and there are no visible upsides. So why change it? Original takes it here. DFWAB!</p>\n<ol start=\"2\">\n<li>Does the code add/remove unnecessary steps?</li>\n</ol>\n<pre><code>const parts = someString.split('.');\nreturn parts[parts.length - 1];\n</code></pre>\n<p>This reads as:</p>\n<ol>\n<li>Split <code>someString</code> into an (<code>'.'</code> character delimited) array</li>\n<li>Label (step 1) <code>parts</code></li>\n<li>Take <code>parts</code>'s <code>length</code> property and subtract <code>1</code></li>\n<li>Retrieve <code>parts</code>'s element at <code>index</code> (step 3)</li>\n<li><code>return</code> (step 4)</li>\n</ol>\n<pre><code>const [last] = someString.split('.').reverse();\nreturn last;\n</code></pre>\n<p>This reads as:</p>\n<ol>\n<li>Split <code>someString</code> into an (<code>'.'</code> delimited) array</li>\n<li><code>reverse</code> the elements in (step 1)</li>\n<li>Label the first element in (step 2) <code>last</code></li>\n<li><code>return</code> <code>last</code></li>\n</ol>\n<p>Here the PR code changes the approach and removes a step. Is it necessary though? This is more left to opinion, and I am sure you will get opinions for/against both. IMHO "split an array then reverse that array" are simpler to reason about because it is declarative. I can see a string being split into pieces in my head and then <code>reverse</code>-ing the original order so the first element becomes the last (supported by the const label <code>last</code>). In the original, I have to reason about arrays, their properties, and why I have to access its length at all. I say that the PR code takes this. Not by much though.</p>\n<ol start=\"3\">\n<li>What is the intention of the code?</li>\n</ol>\n<p>This code's intention regardless of implementation is to take a string and give back a substring starting one character after the last <code>'.'</code> in the string. Both implementations perform acrobatics just to pull this off. The main fault in terms of implementation is 'why do we have to turn the string into an array' when the string possesses all the necessary methods?</p>\n<p>Here is an example that beats out both cases and how it performs in these metrics:</p>\n<pre><code>return someString.slice(someString.lastIndexOf('.') + 1);\n</code></pre>\n<ol>\n<li>No changes from the original code BUT adds clear benefits. (win)</li>\n<li>Removes unnecessary/takes fewer steps and is more declarative. (win)</li>\n<li>States the true intention of the code clearly. (huge win)</li>\n</ol>\n<p>BONUS: IT'S A ONE LINER! WOOHOO!</p>\n<p>Now I know people tend to not see this as a benefit but I think shorter code with higher stats (as described above) is better than more code performing equally or worse.</p>\n<p>The code reads as:</p>\n<ol>\n<li>Take <code>someString</code> and find the <code>lastIndexOf</code> <code>'.'</code></li>\n<li>Add <code>1</code> to (step 1)</li>\n<li><code>slice</code> <code>someString</code> starting at the index (step 2)</li>\n<li><code>return</code> (step 3)</li>\n</ol>\n<p>Just a small note: if I were certain that this was all the code in the calling function I would turn it into <code>someString => someString.slice(someString.lastIndexOf('.') + 1)</code> and eliminate step 4 since the return is implicit and the function can be seen as the result of the first three steps.</p>\n<p>In terms of intention, this line is literally saying (as the steps also describe): "Slice this string starting at the index following the last index of <code>'.'</code>. It's just clear.</p>\n<p><strong>tl;dr</strong></p>\n<p>Neither one is 'right' because performance is irrelevant and both snippets are fairly similar in readability. Instead of 'readability' (whatever that means, highly subjective) look at these metrics when it comes to PRs:</p>\n<ol>\n<li>Does the PR actually implement changes? (original wins)</li>\n<li>Does the PR add/remove unnecessary STEPS? (PR wins)</li>\n<li>Does the pull request make the intention of the code clearer? (tied loss)</li>\n</ol>\n<p>A better change which beats the other two in all categories (for reference) could be something like this:</p>\n<pre><code>return someString.slice(someString.lastIndexOf('.') + 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:12:16.103",
"Id": "488442",
"Score": "4",
"body": "`array[array.length-1]` is idiomatic in so many languages that I think it would make sense to consider it as one step. I imagine most people would immediately recognize that as \"get the last item in the array\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:17:01.263",
"Id": "488470",
"Score": "0",
"body": "Steps, as I describe in the post, disregard an individual's ability to chunk understood steps together. The focus is on what the person reading might have to go through, at a bare minimum, to read the code. I do not think it wise to assume everyone reading the code will have a predetermined background, hence my decision to not chunk those into one step."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T19:43:03.657",
"Id": "249178",
"ParentId": "249153",
"Score": "9"
}
},
{
"body": "<p>Here's my take:</p>\n<pre class=\"lang-js prettyprint-override\"><code>return someString.substring(someString.lastIndexOf('.') + 1);\n</code></pre>\n<p>The readability issue could be argued either way, it's really personal preference. I don't think the change in the PR makes the code materially better or easier to read.</p>\n<p>To hear 'performance doesn't matter' just makes me queasy. In your application it might not have much of an effect, but why go out of your way to make code slower if it doesn't really make the code much easier to read.</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 ITERATIONS = 350000;\nconst TEST_STRING = 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z';\nconsole.log('------------------------------ START ------------------------------')\n\nfunction time(s, fn) {\n const start = performance.now();\n for (let i = 0; i < ITERATIONS; i++) {\n fn(TEST_STRING);\n }\n const end = performance.now();\n const time = end - start;\n console.log(`${s}: ${time}`);\n}\n\ntime('Length-1', s => { const arr = s.split('.'); return arr[arr.length - 1]; });\ntime('Reverse', s => { const [last] = s.split('.').reverse('.'); return last; });\ntime('lastIndexOf', s => s.substring(s.lastIndexOf('.') + 1));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T13:26:09.417",
"Id": "489125",
"Score": "0",
"body": "I know that nobody asked, but as a C++ programmer, this is the only answer that doesn't sound crazy to me. I would never even consider tokenizing a string and then reversing an entire array just to get the last element in a string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T01:09:32.197",
"Id": "489771",
"Score": "0",
"body": "@JPhi1618 Exactly this. Years ago I agreed about not caring too much because JS was used mostly for fluffing some bits on the browser. However, a substantial number of backends today use JS. I hope that those developers are aware of what the code they write is actually doing rather than just its return value."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:56:05.730",
"Id": "249245",
"ParentId": "249153",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T12:58:34.493",
"Id": "249153",
"Score": "9",
"Tags": [
"react.js",
"typescript"
],
"Title": "Returning the last segment of a split string"
}
|
249153
|
<p>I have created a module that validates the credentials against different databases.</p>
<pre><code>module Authentication
DATABASES = %w[mysql mssql oracle].freeze
DATABASES.each do |database|
define_method("#{database}_connect") do |args|
client = case database
when 'mysql' then Mysql2::Client.new args.merge(ssl_mode: :disabled)
when 'mssql' then TinyTds::Client.new args
when 'oracle' then OCI8.new(args[:username], args[:password], "//#{args[:host]}:#{args[:port]}/#{args[:service_name]}")
end
case database
when 'mysql', 'oracle' then true
when 'mssql' then client.active?
end
end
end
def database_authentication_success?(database:, host:, port:, service_name:, username:, password:)
options = {host: host, port: port, service_name: service_name, username: username, password: password}
case database
when 'mysql' then mysql_connect(options)
when 'mssql' then mssql_connect(options)
when 'oracle' then oracle_connect(options)
end
end
end
</code></pre>
<p>Please let me know, how can it be improved?</p>
|
[] |
[
{
"body": "<p>What is the use case and rationale for this module? I can see what it does, but I'm struggling to understand why I'd want to do it.</p>\n<p>The fact that you have three almost identical <code>case</code> statements to drive the behaviour is a 'code smell'. In most other OO languages you'd use inheritance or an interface and a factory method to determine which subclass of an object to create (with a single <code>case</code> statement). In that case, the objective is to abstract away the differences between connecting to the databases behind an interface (which is what you seem to be trying to do in method <code>database_authentication_success?</code>). But the metaprogramming code generates explicitly-named methods for connecting to each type of database, which seems to do the opposite and makes it harder to use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:19:52.167",
"Id": "249163",
"ParentId": "249154",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:21:58.647",
"Id": "249154",
"Score": "1",
"Tags": [
"ruby",
"meta-programming",
"modules"
],
"Title": "Ruby: Database Authentication Module"
}
|
249154
|
<p>I'd like to know what you think of my insertion sort version. I tried to be pythonic and avoid <code>while</code> loops with "ugly" index-management:</p>
<pre><code>def sort(a):
for i, x in enumerate(a):
for j, y in enumerate(a):
if y >= x:
a.insert(j, a.pop(i))
break
</code></pre>
<p>On lists of 1000 random numbers, it seems to be about four times faster (23 ms vs 96 ms) than the implementation from the <a href="https://codereview.stackexchange.com/a/139058">top-voted answer</a> for the <a href="https://codereview.stackexchange.com/q/139056/230375">top result</a> for searching <a href="https://codereview.stackexchange.com/search?q=%5Bpython%5D+insertion+sort">[python] insertion sort</a>.</p>
<p>Benchmark code:</p>
<pre><code>from random import random
from time import perf_counter as timer
from statistics import median
n = 1000
repeat = 50
def insertionSort(lst):
for index in range(1, len(lst)):
currentvalue = lst[index]
position = index
while position > 0 and lst[position - 1] > currentvalue:
lst[position] = lst[position - 1]
position = position - 1
lst[position] = currentvalue
def sort(a):
for i, x in enumerate(a):
for j, y in enumerate(a):
if y >= x:
a.insert(j, a.pop(i))
break
solutions = insertionSort, sort
for r in range(1, 6):
print('Round %d:' % r, end='')
a = [random() for _ in range(n)]
for solution in solutions:
times = []
for _ in range(repeat):
copy = a.copy()
t0 = timer()
solution(copy)
times.append(timer() - t0)
assert copy == sorted(a)
print(' %6.2f ms' % (median(times) * 1e3), end='')
print()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:12:15.643",
"Id": "488338",
"Score": "0",
"body": "(A) In what context does it make sense to squeeze extra bits of efficiency sorting small lists using insertion sort? (B) How are you benchmarking this? Ideally, add benchmarking code to the question. (C) Assuming that the benchmarking is not flawed, it is a puzzling outcome, since Python lists are not well optimized for inserts and pops from the middle. Perhaps there's an explanation for the non-intuitive outcome, but it might have more to do with Python implementation details than general algorithmic features. I suppose it could be an interesting question for that reason alone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:38:45.320",
"Id": "488350",
"Score": "0",
"body": "@FMc (A) Wasn't really about speed but about being pythonic. From what I've seen, sorting algorithms tend to heavily use indices, even in Python implementations (like that other solution I pointed to). I don't like it. I much prefer Python's for-loops over iterables rather than while-loops with indices. So I set out to do that. The faster speed came as a side-effect. (B) See updated question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:13:01.213",
"Id": "488352",
"Score": "0",
"body": "No problems jump out at me in the benchmarking, and I'm surprised by the result. It does seem like a question better suited for StackOverflow than CodeReview. If you do migrate it to StackOverflow I would encourage you to include the other variant as well. It's the most puzzling, because I would have expected `a.insert(a.index(y), a.pop(i))` to be very slow indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:16:19.500",
"Id": "488353",
"Score": "0",
"body": "@FMc That said, I also *am* interested in speed. Not so much about speed of insertion sort, but about speed in Python, and perhaps we can learn something here. Although, I think insertion sort isn't completely useless but is often used as \"base case\", sorting small parts when sorting a larger list with let's say merge sort. That *still* is somewhat moot in Python, as I'm not gonna beat the built-in sort in general. Although I perhaps *could* beat it when I have a long list and I know that a large prefix is already sorted (since the built-in will first need to figure that out)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:24:12.427",
"Id": "488354",
"Score": "0",
"body": "@FMc I don't really see how this is better suited to SO then CR. This is pretty much a golden example of a question that Code Review wants - an OP that cares about readability, speed and anything else, but mostly wants to learn. The amount of questions like this that get close on SO on the other hand..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:27:56.357",
"Id": "488356",
"Score": "0",
"body": "Correction about that last part with large already sorted prefix: I don't think my insertion sort would beat the built-in. Not as written, and also not with a modification of starting the outer loop later in the string where the \"new data\" (after the sorted prefix) starts. If I know all the new data is larger than the prefix data, I'd slice the new data out, sort it with the built-in, and write it back. And if the new data *isn't* larger than the prefix data, taking it out and using `bisect.insort` might beat applying the built-in sort, but that's really not my insertion sort anymore then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:43:47.770",
"Id": "488377",
"Score": "0",
"body": "@Peilonrayz I suppose I didn't explain myself well. The most interesting issue here is the benchmarking outcome, at least in my opinion. And that question feels more like SO than CR. But, yes, any code can be reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:46:04.830",
"Id": "488378",
"Score": "0",
"body": "@FMc If we focus on just the benchmarking then I guess it's equally valid on both CR and SO as we have the [tag:performance] tag for things like that."
}
] |
[
{
"body": "<p>Most of the produced <code>j</code> indexes won't be used, so that's wasteful. Turns out that searching the one that we <em>do</em> need is faster. This further reduced the time to 19 ms:</p>\n<pre><code>def sort(a):\n for i, x in enumerate(a):\n for y in a:\n if y >= x:\n a.insert(a.index(y), a.pop(i))\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:08:06.240",
"Id": "488324",
"Score": "0",
"body": "(Found this after posting the question and wasn't sure whether to edit it, and I think it works as a review.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T14:07:02.740",
"Id": "249162",
"ParentId": "249157",
"Score": "0"
}
},
{
"body": "<h1>Code review</h1>\n<p>You should use better variable names then <code>a</code>, <code>x</code> and <code>y</code>. But otherwise since your code works your code is fine.</p>\n<h1>Performance</h1>\n<p>It seems a couple of users are confused why Python has strange performance.</p>\n<h2>Enumerate vs index</h2>\n<p>This is pretty simple both <code>enumerate</code> and <code>index</code> have the same time and space complexity.</p>\n<p>If we have a list of <code>False</code> and set one to <code>True</code> and want to find the index of that, both will run in <span class=\"math-container\">\\$O(n)\\$</span> time. It may seem like <code>enumerate</code> is <span class=\"math-container\">\\$O(1)\\$</span> however it is the same as <code>zip(range(len(sequence)), sequence)</code> and we know <code>range</code> is <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>The difference in speed that we can see is because <code>index</code> is just faster than <code>enumerate</code>.</p>\n<h2>Your insertion sort vs Grajdeanu Alex's</h2>\n<p>This comes down to Python being slower than C. If we look at the core of Grajdeanu's solution:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>currentvalue = lst[index]\nposition = index\n\nwhile position > 0 and lst[position - 1] > currentvalue:\n lst[position] = lst[position - 1]\n position = position - 1\n\nlst[position] = currentvalue\n</code></pre>\n</blockquote>\n<p>This is doing two things:</p>\n<ol>\n<li><p>Finding the index to stop iterating to:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>while position > 0 and lst[position - 1] > currentvalue:\n</code></pre>\n</blockquote>\n</li>\n<li><p>Performing an optimized version of <code>insert</code> and <code>pop</code>. This is as they only touch a subset of the array, but <code>insert</code> and <code>pop</code> touch the entire array, worst case. (Python lists are arrays in the backend.)</p>\n</li>\n</ol>\n<p>If you were to translate Grajdeanu Alex's solution into C the code would out perform your <code>insert</code> and <code>pop</code>.</p>\n<h2>Bisecting</h2>\n<p>There's a nice property about insertion sort, as you're iterating through the data <em>everything before your index is sorted</em>. This means we can use a better algorithm to find where to insert into.</p>\n<p>We can use the strategy you use in the <a href=\"https://puzzling.stackexchange.com/q/3074\">Guess a Number Between 1-100</a>. By halving the amount of the list we have to search each check we can find where to insert into in <span class=\"math-container\">\\$O(\\log(n))\\$</span> time. This is faster than than the <span class=\"math-container\">\\$O(n)\\$</span> that your <code>enumerate</code> and Grajdeanu's algorithms are running in.</p>\n<p>There is a library for this, <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\"><code>bisect</code></a>, and most of the legwork is in C too, so it's nice and fast.</p>\n<h1>My timings</h1>\n<p>My code to get the timings:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>import time\nimport math\nimport random\nimport copy\nimport bisect\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom graphtimer import flat, Plotter, TimerNamespace\n\n\nclass Iteration(TimerNamespace):\n def test_baseline(data):\n pass\n\n def test_iterate(data):\n for value in data:\n pass\n\n def test_enumerate_list(data):\n for item in list(enumerate(data)):\n pass\n\n def test_enumerate_partial(data):\n for item in enumerate(data):\n pass\n\n def test_enumerate(data):\n for i, value in enumerate(data):\n pass\n\n\nclass Insertion(TimerNamespace):\n def test_baseline(data, i, value_i, j, value_j):\n pass\n\n def test_plain(data, i, value_i, j, value_j):\n data.insert(j, data.pop(i))\n\n def test_index(data, i, value_i, j, value_j):\n data.insert(data.index(value_j), data.pop(i))\n\n def test_python(data, i, value_i, j, value_j):\n while i < j:\n data[j] = data[j - 1]\n j -= 1\n data[j] = value_i\n\n\nclass Joined(TimerNamespace):\n def test_enumerate_plain(data, i, value_i, j, value_j):\n for j, value_j in enumerate(data):\n if value_i <= value_j:\n data.insert(j, data.pop(i))\n\n def test_enumerate_index(data, i, value_i, j, value_j):\n for j, value_j in enumerate(data):\n if value_i <= value_j:\n data.insert(data.index(value_j), data.pop(i))\n\n def test_iterate_index(data, i, value_i, j, value_j):\n for value_j in data:\n if value_i <= value_j:\n data.insert(data.index(value_j), data.pop(i))\n break\n\nclass Sorts(TimerNamespace):\n def test_manuel_base(a):\n for i, x in enumerate(a):\n for j, y in enumerate(a):\n if y >= x:\n a.insert(j, a.pop(i))\n break\n\n def test_manuel_insert(a):\n for i, x in enumerate(a):\n for y in a:\n if y >= x:\n a.insert(a.index(y), a.pop(i))\n break\n\n def test_other(lst):\n for index in range(1, len(lst)):\n currentvalue = lst[index]\n position = index\n while position > 0 and lst[position - 1] > currentvalue:\n lst[position] = lst[position - 1]\n position = position - 1\n lst[position] = currentvalue\n\n def test_peilon(lst):\n output = []\n for item in lst:\n bisect.insort(output, item)\n\n\nmemoize = {}\n\n\ndef create_args(size, *, _i):\n size = int(size)\n key = size, _i\n if key in memoize:\n return copy.deepcopy(memoize[key])\n array = random_array(size)\n j = random.randrange(0, size)\n array[:j] = sorted(array[:j])\n i = 0\n while array[i] < array[j]:\n i += 1\n output = array, i, array[i], j, array[j]\n memoize[key] = output\n return output\n\n\ndef random_array(size):\n array = list(range(int(size)))\n random.shuffle(array)\n return array\n\n\ndef main():\n fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, subplot_kw=dict(xscale='log', yscale='log'))\n axis = [\n (Iteration, {'args_conv': lambda i: [None]*int(i)}),\n (Insertion, {'args_conv': create_args, 'stmt': 'fn(args[0].copy(), *args[1:])'}),\n (Joined, {'args_conv': create_args, 'stmt': 'fn(args[0].copy(), *args[1:])'}),\n (Sorts, {'args_conv': random_array, 'stmt': 'fn(args[0].copy(), *args[1:])'}),\n ]\n for graph, (plot, kwargs) in zip(iter(flat(axs)), axis):\n (\n Plotter(plot)\n .repeat(10, 2, np.logspace(1, 4), **kwargs)\n .min()\n .plot(graph, title=plot.__name__)\n )\n plt.show()\n\nif __name__ == '__main__':\n main()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(click to expand)<br />\n<a href=\"https://i.stack.imgur.com/916hw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/916hw.png\" alt=\"enter image description here\" /></a></p>\n<h2>Iteration</h2>\n<ul>\n<li><p><code>test_baseline</code><br />\nThe timings are flat as they are the time it takes to run the test suit. When determining the performance of each function we need to see how far away from the baseline it is.</p>\n</li>\n<li><p><code>test_enumerate</code> & <code>test_enumerate_partial</code><br />\nThese are roughly the same and so we know that <code>enumerate</code>, and not tuple unpacking, is the factor at play that is taking up a lot of performance.</p>\n</li>\n<li><p><code>test_enumerate</code>, <code>test_enumerate_list</code> & <code>test_iterate</code><br />\nWe can see adding more <span class=\"math-container\">\\$O(n)\\$</span> operations makes the code slower. However <code>enumerate</code> is a pretty slow function.</p>\n</li>\n</ul>\n<p>In all <code>enumerate</code> is slow.</p>\n<h2>Insertion</h2>\n<ul>\n<li><p><code>test_baseline</code><br />\nSince we are copying the data in the test suit we see that at times the other functions are running the fastest that they can.</p>\n<p>This is to be expected as we are running tests on a partially sorted array. Ranging from no sort to fully sorted.</p>\n</li>\n<li><p><code>test_plain</code><br />\nWe can see that <code>data.insert(j, data.pop(i))</code> is really fast and is consistently around <code>test_baseline</code>. This means if <code>enumerate</code> was faster than <code>data.index</code> then the other answer would not be true.</p>\n</li>\n<li><p><code>test_index</code> & <code>test_python</code><br />\nFrom the areas we can see that optimized Python runs significantly slower than Python's C methods.</p>\n<p>This is to be expected, Python is slow.</p>\n</li>\n</ul>\n<h2>Joined</h2>\n<p>These merge the above two together to show the impact of the difference in timings.\nThese are a single insertion of a full insertion sort.</p>\n<p>Unsurprisingly given the previous timings <code>test_enumerate_plain</code> is by far the slowest.</p>\n<h2>Sorts</h2>\n<p>This shows that whilst your changes are fast, <a href=\"https://codereview.stackexchange.com/a/180007\">my answer from '17</a> is a pretty darn fast insertion sort.</p>\n<h1>Complexity vs Performance</h1>\n<p>It should be apparent that in Python these are two entirely different metrics. Complexity is more important when playing on a level playing field, which isn't the case in Python.</p>\n<p>But just because Python isn't a level playing field doesn't make it useless. When programming if you try to get the best performance complexity wise then you'll have a good baseline to then optimize from. From here you can then focus on performance which is harder to reason with and harder to compare. And worst case converting the code into C will be far easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T00:02:07.983",
"Id": "488896",
"Score": "1",
"body": "Comments are not for extended discussions. This conversation has been [moved to chat](https://chat.stackexchange.com/rooms/113050/discussion-on-answer-by-peilonrayz-my-insertion-sort-version)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T14:16:02.127",
"Id": "249395",
"ParentId": "249157",
"Score": "2"
}
},
{
"body": "<h2>In which we defend the honor of <code>enumerate()</code></h2>\n<p>Although I learned from and appreciated the write-up by <a href=\"https://codereview.stackexchange.com/a/249395/4612\">Peilonrayz</a>, I was not\nconvinced by all of the characterizations. Also, I had some specific questions\nnot covered in those benchmarks, so I explored on my own using the script\nbelow. These notes cover a few things I learned and reframe the discussion\na bit.</p>\n<p><strong><code>enumerate()</code> itself is not slow</strong>. Merely invoking the <code>enumerate()</code> callable\nis an <code>O(1)</code> operation, because it does nothing with the underlying iterable of\nvalues other than store an iterator created from the original iterable.</p>\n<p><strong>Is consuming an iterable via <code>enumerate()</code> slow</strong>? That depends on what the\nalternative is. Compared to direct iteration (<code>for x in xs</code>), yes it's slower\nand the magnitude of the slowdown is not trivial. But we use <code>enumerate()</code> for\na reason: we need the indexes too. In that context, there are three obvious\nalternatives: manage the index yourself (<code>i += 1</code>), use <code>range()</code> for iteration\nand then obtain the value by via get-item (<code>x = xs[i]</code>), or ask Python to\ncompute the index (<code>i = xs.index(x)</code>). Compared to those alternatives,\n<code>enumerate()</code> is quite good: it's a little faster than managing the index\nyourself or using <code>range()</code>, and it is substantially faster than using\n<code>list.index()</code> every time. In that light, saying that "<code>index()</code> is just faster\nthan <code>enumerate()</code>" seems not quite right -- but perhaps I misunderstood or\nthere are errors in my findings.</p>\n<p><strong>Should you worry about tuple unpacking when using <code>enumerate()</code></strong>. No, it adds\nalmost nothing. And especially don't avoid <code>enumerate()</code> on performance grounds\nif it forces you to use get-item on the tuple (<code>i = x[0]</code>), because that is\nslower than direct unpacking.</p>\n<p><strong>Some evidence</strong>. The numbers below are for a run of the script with\n<code>--count=1000</code> (how many numbers to be sorted) and <code>--trials=100</code> (how many times\ndid we measure to get the statistics). The output here just adds up the total\nof the times for all trials (<code>--stat=total</code>), but you can also run the code to\nsee mean, min, and max as well (those results tell similar stories). For each\nfunction, the table shows both a scaled value (2nd column) and the raw value\n(3rd column). The scaled values are easier to compare because they are\nexpressed as a ratio relative to the minimum value in that column. The comment\ncolumn has a schematic summary of function's behavior.</p>\n<pre><code># Just calling enumerate().\n# Nothing slow here: O(1).\n\nenumerate_call_baseline : 1.0 : 0.000018 # it = None\nenumerate_call : 2.0 : 0.000035 # it = enumerate()\n\n# Direct Python iteration.\n# If you need an index, don't use xs.index(x) as a general approach.\n\niterate_baseline : 38.4 : 0.000678 # for x in xs: pass\niterate_with_index : 190.0 : 0.003351 # for x in xs: i += 1\niterate_range_getitem : 198.6 : 0.458601 # for i in range(len(xs)): x = xs[i]\niterate_get_index : 24850.3 : 0.438433 # for x in xs: i = xs.index(x)\n\n# Iteration with enumerate().\n# Slow only when compared to a no-op for loop.\n# If you need the indexes, use enumerate().\n\nenumerate_consume : 155.6 : 0.002746 # for x in it: pass\nenumerate_consume_unpack : 157.4 : 0.002778 # for i, x in it: pass\nenumerate_consume_getitem : 263.8 : 0.005475 # for x in it: x[0]\n</code></pre>\n<p><strong>Sometimes <code>index()</code> is faster.</strong> Here are the benchmarks for the sorting\nfunctions we have discussed. As others have reported, the classic compare-swap\nstategy is worse than those relying on the insert-index-pop family of methods.</p>\n<pre><code>sort_baseline : 1.0 : 0.007389 # xs.sort()\nsort_classic_swap : 618.4 : 4.569107 # classic compare-swap\nsort_insert_index_pop : 122.5 : 0.905445 # xs.insert(xs.index(x2), xs.pop(i))\nsort_insert_pop : 150.7 : 1.113629 # xs.insert(j, xs.pop(i))\n</code></pre>\n<p><strong>I find that counterintuitive at first glance</strong>. When reading through the code\nof <code>sort_insert_index_pop()</code>, my first impression was puzzlement. In\nparticular, don't <code>insert()</code>, <code>index()</code>, and <code>pop()</code> each imply linear\nscans/shifts of the data? That seems bad, right? Moreover, having done the\nenumerate benchmarks, I am not entirely convinced by an explanation <em>based\nsolely</em> on the general point that language operations implemented in C (such as\n<code>list.index()</code>) have a big speed advantage over the language operations\nimplemented directly in Python. Although that point is both true and important,\nthe enumerate benchmarks prove that in the general case, retrieving indexes via\n<code>xs.index(x)</code> is very slow. Out of the two forces -- the speed of the C-based\n<code>list</code> methods vs the inefficiency of those costly scans/shifts -- which one\nhas a larger magnitude within the context of the short-circuiting behavior of\ninsertion sort?</p>\n<p><strong>Summary of the tradeoffs</strong>. The table below tries to summarize the advantages\nand disadvantages of the two approaches. The insert-index-pop approach uses the\nfastest looping style in its inner loop, makes many fewer swaps, in a faster\nlanguage -- but the swap itself is algorithmically inefficient. We know from\nthe benchmarks how those tradeoffs weigh out in the end, but I cannot say with\nconfidence that a survey of experienced Python engineers would have necessarily\npredicted this empirical outcome in advance -- and that is what we mean when we\ndescribe something as counterintuitive.</p>\n<pre><code> | classic-swap | insert-index-pop\n-------------------------------------------------------\n | |\nLooping machinery | |\n | |\n- for x in xs | . | inner\n- enumerate()/range() | outer | outer\n- while COND | inner | .\n | |\nSwaps | |\n | |\n- Number | N * N / 2 | N\n- Cost per swap | 1 | N * 1.5\n- Language | Python | C\n</code></pre>\n<p><strong>The code</strong>:</p>\n<pre><code>import argparse\nimport sys\nfrom collections import namedtuple\nfrom random import randint, shuffle\nfrom time import time\n\n####\n# Benchmarking machinery.\n####\n\n# Groups of functions that we will benchmark.\nFUNC_NAMES = {\n 'enumerate': [\n # Just calling enumerate().\n 'enumerate_call_baseline', # it = None\n 'enumerate_call', # it = enumerate()\n # Direct Python iteration.\n 'iterate_baseline', # for x in xs: pass\n 'iterate_with_index', # for x in xs: i += 1\n 'iterate_range_getitem', # for i in range(len(xs)): x = xs[i]\n 'iterate_get_index', # for x in xs: i = xs.index(x)\n # Iteration with enumerate().\n 'enumerate_consume', # for x in it: pass\n 'enumerate_consume_unpack', # for i, x in it: pass\n 'enumerate_consume_getitem', # for x in it: x[0]\n ],\n 'sort': [\n 'sort_baseline', # xs.sort()\n 'sort_classic_swap', # classic index-based compare-swap\n 'sort_insert_index_pop', # xs.insert(xs.index(x2), xs.pop(i))\n 'sort_insert_pop', # xs.insert(j, xs.pop(i))\n ],\n 'check_sorts': [],\n}\n\n# Constants and simple data types.\nSTAT_NAMES = ('count', 'total', 'mean', 'min', 'max')\nVALUE_NAMES = ('randint', 'random', 'shuffle', 'direct')\nStats = namedtuple('Stats', STAT_NAMES)\nResult = namedtuple('Result', 'func stats')\n\ndef main(args):\n # Parse command-line arguments.\n ap = argparse.ArgumentParser()\n ap.add_argument('scenario', choices = list(FUNC_NAMES))\n ap.add_argument('--stat', default = 'total', choices = STAT_NAMES)\n ap.add_argument('--count', type = int, default = 1000)\n ap.add_argument('--trials', type = int, default = 100)\n ap.add_argument('--values', default = 'randint', choices = VALUE_NAMES)\n ap.add_argument('--presort', action = 'store_true')\n opts = ap.parse_args(args)\n\n # Generate some values.\n xs = generate_values(opts.count, opts.values, opts.presort)\n\n # Either sanity check to ensure than our sorts actually sort.\n if opts.scenario == 'check_sorts':\n exp = sorted(xs)\n for fname in FUNC_NAMES['sort']:\n ys = xs.copy()\n f = globals()[fname]\n f(ys)\n print(ys == exp, fname)\n\n # Or benchmark some functions.\n else:\n funcs = [globals()[fname] for fname in FUNC_NAMES[opts.scenario]]\n results = measure_funcs(funcs, xs, opts.trials)\n report = list(summarize(opts, results))\n print('\\n'.join(report))\n\ndef generate_values(count, mode, presort = False):\n # Various ways of generating numbers to be sorted or enumerated.\n if mode == 'randint':\n xs = [randint(1, 1000) for _ in range(count)]\n elif mode == 'random':\n xs = [random() for _ in range(count)]\n elif mode == 'shuffle':\n xs = list(range(count))\n shuffle(xs)\n elif mode == 'direct':\n xs = [int(x) for x in mode.split(',')]\n return sorted(xs) if presort else xs\n\ndef measure_funcs(funcs, xs, trials):\n # Benchmark several functions.\n results = []\n for f in funcs:\n stats = measure(trials, f, xs)\n r = Result(f, stats)\n results.append(r)\n return results\n\ndef measure(trials, func, xs):\n # Benchmark one function.\n times = []\n for t in range(trials):\n ys = xs.copy()\n t0 = time()\n func(ys)\n t1 = time()\n times.append(t1 - t0)\n count = len(xs)\n total = sum(times)\n mean = total / len(times)\n return Stats(count, total, mean, min(times), max(times))\n\ndef summarize(opts, results):\n # Generate tabular output.\n\n # Scenario header.\n fmt = '\\n# {} : stat={}, count={}, trials={}'\n header = fmt.format(opts.scenario, opts.stat, opts.count, opts.trials)\n yield header\n\n # For the statistic we are analyzing, get its minimum value.\n min_tup = min(results, key = lambda tup: tup[1])\n min_val = getattr(min_tup[1], opts.stat)\n\n # Print table for that statistic.\n fmt = '{:<30} : {:8.1f} : {:.6f}'\n for f, stats in results:\n val = getattr(stats, opts.stat)\n scaled_val = val / min_val\n row = fmt.format(f.__name__, scaled_val, val)\n yield row\n\n####\n# Benchmarking targets: enumerate() vs alternatives.\n####\n\ndef enumerate_call_baseline(xs):\n it = None\n\ndef enumerate_call(xs):\n it = enumerate(xs)\n\ndef iterate_baseline(xs):\n for x in xs:\n pass\n\ndef iterate_with_index(xs):\n i = 0\n for x in xs:\n i += 1\n\ndef iterate_range_getitem(xs):\n for i in range(len(xs)):\n x = xs[i]\n\ndef enumerate_consume(xs):\n it = enumerate(xs)\n for x in it:\n pass\n\ndef enumerate_consume_getitem(xs):\n it = enumerate(xs)\n for x in it:\n x[1]\n\ndef enumerate_consume_unpack(xs):\n it = enumerate(xs)\n for i, x in it:\n pass\n\ndef iterate_get_index(xs):\n for x in xs:\n i = xs.index(x)\n\n####\n# Benchmarking targets: in-place insertion sorts.\n####\n\ndef sort_baseline(xs):\n xs.sort()\n\ndef sort_classic_swap(xs):\n for i in range(1, len(xs)):\n x = xs[i]\n while i > 0 and xs[i - 1] > x:\n xs[i] = xs[i - 1]\n i -= 1\n xs[i] = x\n\ndef sort_insert_pop(xs):\n for i, x1 in enumerate(xs):\n for j, x2 in enumerate(xs):\n if x2 >= x1:\n xs.insert(j, xs.pop(i))\n break\n\ndef sort_insert_index_pop(xs):\n for i, x1 in enumerate(xs):\n for x2 in xs:\n if x2 >= x1:\n xs.insert(xs.index(x2), xs.pop(i))\n break\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T22:54:46.600",
"Id": "489058",
"Score": "1",
"body": "Something that is an order or two faster, are `pop` and `insert`. Those two combined are about 20 times faster than index alone, on [this test](https://repl.it/repls/NimbleBlissfulSandbox#main.py). And that's for a list of ints, whose comparisons I believe are fairly fast. For more slowly comparing values, `index` will become accordingly slower, while `pop` and `insert` aren't affected."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T21:51:59.093",
"Id": "249459",
"ParentId": "249157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T13:26:09.810",
"Id": "249157",
"Score": "4",
"Tags": [
"python",
"sorting",
"insertion-sort"
],
"Title": "My insertion sort version"
}
|
249157
|
<p>i am rather new at python and this is my very first project i did myself. i am wondering if there is anyway i can improve this or give me advice on making this better. thank you</p>
<pre class="lang-py prettyprint-override"><code>import sys
valid = ["+", "-", "*", "/"]
invalid = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def start():
while True:
a = input("").lower()
for banned in a:
if banned in invalid:
print("error")
else:
sum1 = int(a)
cal = input("")
b = input("").lower()
for banned in b:
if banned in invalid:
print("Error")
start()
else:
sum2 = int(b)
break;
for list in cal:
if list in valid:
if list == "+":
total = sum1 + sum2
print("=" + total)
if list == "-":
total = sum1 - sum2
print(total)
start()
if list == "*":
total = sum1 * sum2
print(total)
start()
if list == "/":
total = sum1 / sum2
print(total)
start()
else:
print("Wrong Format")
start()
start()
</code></pre>
|
[] |
[
{
"body": "<p><strong>Suggestion 1</strong></p>\n<p>Your list of invalid characters and <code>in</code> checks will work just as well as a string, but be shorter and more readable.</p>\n<pre><code>invalid = 'abcdefghijklmnopqrstuvwxyz'\n</code></pre>\n<p>Same applies to the <code>valid</code> array of characters.</p>\n<p><strong>Suggestion 2</strong></p>\n<pre><code>for banned in a:\n</code></pre>\n<p><code>banned</code> is a very confusing variable name for this use. You don't know if it's banned until you've compared it with the <code>invalid</code> list of characters. You should rather use <code>character</code> or <code>letter</code> or a shorter basic name like <code>c</code> or <code>x</code>.</p>\n<p><strong>Suggestion 3</strong></p>\n<pre><code>a = input("").lower()\n</code></pre>\n<p><code>a</code> is also a poor name here since it doesn't tell us what it is. Rather name it <code>input1</code> or something similar, and of course change <code>b</code> to <code>input2</code> or something else that is descriptive.</p>\n<p><strong>Suggestion 4</strong></p>\n<pre><code>for list in cal:\n</code></pre>\n<p><code>list</code> is not just a poorly chosen name that misleads the reader, it's also a keyword / function in Python and should not be used as a variable name in any situation. I suggest <code>operator</code> as a better name since you're taking in an operator for your calculation.</p>\n<p><strong>Suggestion 5</strong></p>\n<p>You're calling <code>start()</code> after every operation except <code>+</code> . This looks like a mistake. Why not for <code>+</code>?</p>\n<p><strong>Suggestion 6</strong></p>\n<pre><code>total = sum1 * sum2\nprint(total)\n</code></pre>\n<p>For every operation, you're saving the total in a new variable and then printing it. But you don't use it for anything else than printing, so you might as well print the result directly without storing it in a variable.</p>\n<pre><code>print(sum1 * sum2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T17:55:27.067",
"Id": "249171",
"ParentId": "249164",
"Score": "1"
}
},
{
"body": "<p>A few comments focused less on line-by-line details and more on how to build\nbetter command-line scripts and on simplifying logic.</p>\n<p><strong>How do I use this program</strong>? Your <code>input()</code> calls\ndon't tell me what's going on. Help, please.</p>\n<p><strong>Users don't enjoy tedious interactions with computers</strong>. Would you rather\ntype a number, press enter, type an operator, press enter, type a number, press\nenter ... OR just enter the darn equation? For example:</p>\n<pre><code>reply = input('Enter equation: INT OP INT: ')\n</code></pre>\n<p><strong>Users really don't enjoy tedious interactions with computers</strong>. With rare\nexceptions, sensible command-line programs don't use <code>input()</code> at all -- or at\nleast not by default. Learn about <code>sys.argv</code> and let your users run your\ncalculator directly, without forcing them to become best buddies with their\ncomputer. Here's what a command-line usage might look like:</p>\n<pre><code>$ python simple-calculator.py 32 + 10\n42\n</code></pre>\n<p><strong>Learn about exception handling</strong>. Rather than getting bogged down in creating\na data structure holding every possible bad input (very hard, especially if you\nconsider all conceivable UTF-8 inputs), just try to do the thing you want to do\n-- with a safety net.</p>\n<pre><code>while True:\n try:\n # Each of these lines could fail. That's OK. Be optimistic!\n s1, op, s2 = reply.split()\n a = int(s1)\n b = int(s2)\n assert op in '+-*/'\n break # Success.\n except Exception as e:\n # The safety net.\n print('Invalid input')\n</code></pre>\n<p><strong>Use data structures to simplify logic</strong>. Wouldn't it be cool to get rid of a\npile of <code>if-else</code> checks and instead just do the thing you want to do directly?\nIn such situations, a data structure can often help. What we need is a way to\ntake an operator and then use it to get a 2-argument function that will perform\nthe math we need. In other words, we need a mapping between operators and the\ncorresponding math functions. Here are 3 ways to achieve that:</p>\n<pre><code>import operator\n\ndef add(a, b):\n return a + b\n\nops = {\n '+': add, # Define your own functions.\n '-': lambda a, b: a - b, # Or lambdas.\n '*': operator.mul, # Or get them from a library.\n '/': operator.truediv,\n}\n\n# With that data structure, our code would reduce to this.\nanswer = ops[op](a, b) # Wrap in try-except to catch divide by 0.\nprint(answer)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:48:14.773",
"Id": "249184",
"ParentId": "249164",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T15:10:09.023",
"Id": "249164",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "improving my simple python calculator"
}
|
249164
|
<p>The following microservice is just handling loan application and response the result of the application is accepted or rejected. It is part of my assignment for an interview.</p>
<p>The project description is that; A user sends them Id, username, surname, and monthly salary via REST API. Assuming that you have got already credit scores in DB,
you must return the loan application result based on that credit score. And then save the application on DB.</p>
<p>They give me the ruleset. And they said that please show what you have got like design patterns, test-driven development, clean code, REST API design, SOLID principles, OOP, etc. Also Docker, MongoDB</p>
<p>But they rejected me. Anyway, I appreciated if you judging my code, need to improve my skills.</p>
<p>I try to use the Strategy and Factory patterns to process the application.</p>
<p>Source code is huge so the project repo is <a href="https://github.com/fuatkarakus/loan-application-service" rel="nofollow noreferrer"><strong>HERE</strong></a>, please check this.</p>
<p><strong>LoanController Class</strong></p>
<pre><code>@Slf4j
@RestController
@RequestMapping(value = "/api")
public class LoanController {
private final LoanApplicantService loanApplicantService;
public LoanController(LoanApplicantService loanApplicantService) {
this.loanApplicantService = loanApplicantService;
}
@PostMapping("/loan")
public ResponseEntity<Response> applyForLoan(@Valid @RequestBody LoanRequest request) {
Response response;
try{
log.info("incoming request: {}", request.getId());
response = Response.builder()
.success(Boolean.TRUE)
.data(loanApplicantService.process(request))
.build();
}catch ( Exception e ) {
log.error("Exception: {}", e.getCause());
response = Response.builder()
.success(Boolean.FALSE)
.message(e.getMessage())
.build();
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
</code></pre>
<p><strong>LoanApplicantService class</strong></p>
<pre><code>@Slf4j
@Service
public class LoanApplicantService implements ILoanApplicantService{
private final LoanApplicantRepository loanApplicantRepository;
private final LoanApplicantResultRepository resultRepository;
private final LoanApplicantScoreService scoreService;
private final SmsService smsService;
public LoanApplicantService(LoanApplicantRepository loanApplicantRepository,
LoanApplicantScoreService scoreService,
LoanApplicantResultRepository resultRepository,
SmsService smsService){
this.loanApplicantRepository = loanApplicantRepository;
this.scoreService = scoreService;
this.resultRepository = resultRepository;
this.smsService = smsService;
}
public LoanResponse process(LoanRequest request) {
// convert request to entity
LoanApplicant applicant = LoanConverter.convertRequest(request).build();
// save request
save(applicant);
// find score
LoanApplicantScore applicantScore = scoreService.findApplicantScoreById(applicant.getId());
// get strategy by score
LoanStrategy strategy = LoanStrategyFactory.getStrategy(applicantScore.getScore(),
applicant.getMonthlySalary());
// execute the result of application
LoanApplicantResult result = strategy.execute(applicantScore, applicant);
// save result of application
resultRepository.save(result);
LoanResponse response = LoanConverter.convertResult(result).build();
// send sms
smsService.sendSMS(applicant);
return response;
}
public LoanApplicant save(LoanApplicant applicant) {
return loanApplicantRepository.save(applicant);
}
}
</code></pre>
<p><strong>LoanStrategyFactory class</strong></p>
<pre><code>public class LoanStrategyFactory {
private LoanStrategyFactory() {}
public static LoanStrategy getStrategy(Integer score, BigInteger salary) {
if (LoanRange.MEDIUM.contains(score) && isSalaryUnderBarrier(salary)) {
return new MediumScoreStrategy();
} else if(LoanRange.HIGH.contains(score)) {
return new HighScoreStrategy();
} else {
return new LowScoreStrategy();
}
}
private static boolean isSalaryUnderBarrier(BigInteger salary) {
return LoanConstant.INCOME_BARRIER.compareTo(salary) > 0;
}
}
</code></pre>
<p><strong>LoanExceptionHandler class</strong></p>
<pre><code>@ControllerAdvice
public class LoanExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
Response response = Response.builder()
.success(Boolean.FALSE)
.message(ex.getMessage())
.build();
return new ResponseEntity<>(response, headers, status);
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
Response response = Response.builder()
.success(Boolean.FALSE)
.message("Required request body is missing")
.build();
return new ResponseEntity<>(response, headers, status);
}
}
</code></pre>
<p><strong>LoanConverter class</strong></p>
<pre><code>public class LoanConverter {
private LoanConverter() { }
public static LoanApplicant.LoanApplicantBuilder convertRequest(LoanRequest loan) {
return Optional.ofNullable(loan).map(d -> LoanApplicant.builder()
.id(loan.getId())
.name(loan.getName())
.surname(loan.getSurname())
.monthlySalary(new BigInteger(loan.getMonthlySalary()))
.phoneNumber(loan.getPhoneNumber()))
.orElseGet(LoanApplicant::builder);
}
public static LoanResponse.LoanResponseBuilder convertResult(LoanApplicantResult loan) {
return Optional.ofNullable(loan).map(d -> LoanResponse.builder()
.amount(loan.getAmount())
.status(loan.getStatus()))
.orElseGet(LoanResponse::builder);
}
}
</code></pre>
<p><strong>LoanRange class</strong></p>
<pre><code>import org.apache.commons.lang3.Range;
public class LoanRange {
private LoanRange() {}
public static final Range<Integer> LOW = Range.between(0, 499);
public static final Range<Integer> MEDIUM = Range.between(499, 999);
public static final Range<Integer> HIGH = Range.between(999, Integer.MAX_VALUE);
}
</code></pre>
<p><strong>LoanControllerTest class</strong></p>
<pre><code>@WebMvcTest
public class LoanControllerTest {
private static final String API = "/api/loan";
MockMvc mockMvc;
private final ObjectMapper objectMapper = new ObjectMapper();
@Autowired
LoanController loanController;
@MockBean
LoanApplicantService loanApplicantService;
@BeforeEach
public void setup() {
this.mockMvc = MockMvcBuilders
.standaloneSetup(loanController)
.setControllerAdvice(new LoanExceptionHandler())
.build();
}
@Test
void whenRequestLoan_thenReturn200() throws Exception {
LoanRequest request = LoanRequest.builder()
.id("12312312312")
.name("fuat")
.surname("kara")
.monthlySalary("1000")
.phoneNumber("5312341234").build();
performRequest(request, status().isOk());
}
@Test
void whenInvalidRequestLoan_thenReturn400() throws Exception {
LoanRequest request = LoanRequest.builder()
.id("123123123123")
.name("fuat")
.surname("kara")
.monthlySalary("1000")
.phoneNumber("5312341234").build();
performRequest(request, status().isBadRequest());
}
@Test
void whenNullRequestLoan_thenReturn400() throws Exception {
mockMvc.perform(post(API))
.andExpect(status().isBadRequest());
}
private ResultActions performRequest(Object request, ResultMatcher matcher) throws Exception {
return performRequest(request, post(API), matcher);
}
private ResultActions performRequest(Object request, MockHttpServletRequestBuilder builder, ResultMatcher matcher) throws Exception {
return mockMvc.perform(
builder
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(matcher);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T01:00:57.783",
"Id": "488369",
"Score": "1",
"body": "Do you have a description of the assignment? If yes please add it to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:22:54.220",
"Id": "488395",
"Score": "0",
"body": "Yes, I will add the description and delete these classes here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:49:42.737",
"Id": "488401",
"Score": "2",
"body": "The code for review needs to be present in the question, see https://codereview.stackexchange.com/help/on-topic"
}
] |
[
{
"body": "<p>Method <code>applyForLoan</code>.</p>\n<ol start=\"0\">\n<li>Either success/failed op, will return an <code>200 OK</code> http response?! Maybe not a good idea, and you may respond something like code <code>500</code>(internal server error) for failed op maybe</li>\n<li>Duplicated statements, such as instancing the <code>response</code> var,<code>success</code> state, and <code>build()</code>ing it.</li>\n</ol>\n<p>I suggest something like following</p>\n<pre class=\"lang-java prettyprint-override\"><code>//not sure if builder is tent, or where is it\nResponse.Builder _resp_builder = Response.builder();\nHttpStatus _status;\ntry{\n log.info("incoming request: {}", request.getId());\n LoanResponse _load_resp = loanApplicantService.process(request);\n _resp_builder.data(_load_resp);\n _status = HttpStatus.OK;\n\n}catch ( Exception e ) {\n log.error("Exception: {}", e.getCause());\n _resp_builder.message(e.getMessage());\n _status = HttpStatus.InternalServerError;//?\n}\nreturn new ResponseEntity(_resp_builder.success(_status==HttpStatus.OK).build(), _status);\n</code></pre>\n<p>About method <code>process</code> in type <code>LoanApplicantService</code>.</p>\n<p>I'm not sure if transactions should be there for those persistency statements, or not. Anyway, the process looks a little scary, since no any return type of each DOA is checked.</p>\n<p>For example, what if request entity cannot be saved? or <code>findApplicantScoreById</code> returns <code>null</code>? No check for results, not a transactions to rollback by any failure, I think not a good move.</p>\n<p>Having some logging could be good.</p>\n<p>Personally I'm not fan of those two POJO/type mapping/converting stuffs, and sometimes this is possible to let a POJO play act of two scheme (e.g. as both input arg, and entity).</p>\n<p>I would split this <code>process</code> method into smaller units, where related statements(e.g. <em>execute</em>, and <em>save result</em> taks) get placed into dedicated types/units.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:21:13.413",
"Id": "488393",
"Score": "0",
"body": "Thanks for your answer, For 0. it is an approach for error handling. You can read some [here](https://blog.restcase.com/rest-api-error-handling-problem-details-response/). You return 200 with Success is False instead of return 500. So your suggestion is not useful. And for rollback scenarios, I use MongoDB. Maybe, you can check the whole project repo from Github."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:54:34.730",
"Id": "249185",
"ParentId": "249168",
"Score": "2"
}
},
{
"body": "<p>First of all, it starts out with an inconsistent coding style: if you have a blank before an opening brace,\nhave it <em>everywhere</em>. If you handed this in to me when <em>applying for a job</em> I'd think you don't take me serious. Apply a code formatter!</p>\n<p>Then, where are tests? If TDD is explicitly <em>asked for</em>, not having a single test is a bad joke. (OK, I've seen\nthat there are some in the repository, but not included in the question.)</p>\n<p>Method <code>applyForLoan</code>: forward declaration of the <code>response</code> variable. Don't do this. As 911992 already mentioned,\nreturning HTTP status 200 <em>in the exception case</em>. Not making use of standard solutions like WebApplicationExeption.\nFurthermore "hiding" the business code in response building, which makes it hard to spot. "Info" logging for clear\ndebug information. Catch-all block for undeclared exceptions.</p>\n<p>I'd have expected something like:</p>\n<pre><code>try {\n LoanResponse loanResponse = loanApplicantService.process(request);\n log.debug("incoming request: {} ==> {}", request.getId(), loanResponse);\n \n return loanResponse; // you should know enough about handing objects as outputs, if you can handle them as inputs\n} catch (LoanServiceException e) { // provided somthing like this exists\n throw new WebApplicationExeption(e, Response.Status.INTERNAL_SERVER_ERROR);\n}\n</code></pre>\n<p>The process method in LoanApplicantService is a jumble of responsibilites from database management to sending sms-messages.\nSeparate concerns. Why is there a <code>save</code> method which delegates to the real <code>save</code>-method. Is there any error handling?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:28:18.387",
"Id": "488399",
"Score": "0",
"body": "Rest of the code in my [Github](https://github.com/fuatkarakus/loan-application-service). Please check the repo, I have %90 test coverage."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:24:30.043",
"Id": "249204",
"ParentId": "249168",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T17:16:46.010",
"Id": "249168",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"design-patterns",
"rest",
"spring"
],
"Title": "Loan application service based on user credit score"
}
|
249168
|
<p>I wrote a dynamic stack in C that uses an array as a structure. I tried to maintain O(1) for push and pop and believe I have done so. I want to know what can be written in a cleaner way and if there are any non-trivial bugs.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int push(int val, int *c);
int pop(int *c);
int *stack;
int main(){
int *c = malloc(sizeof(int));
stack = malloc(sizeof(int));
*c = 0;
int i;
for(;;){
printf("1. Push\n2. Pop\n3. Stack\n4. Quit\n>>> ");
scanf("%d", &i);
if(i == 1){
printf("Value: ");
scanf("%d", &i);
push(i, c);
}
else if(i == 2)
printf("Value popped: %d\n", pop(c));
else if(i == 3)
for(int i = 0; i < *c; i++)
printf("%d\n", stack[i]);
else
break;
}
free(stack);
return 0;
}
int push(int val, int *c){
int *r;
r = realloc(stack, ((*c)+1)*sizeof(int));
if (r == NULL){
free(stack);
exit(0);
}
stack = r;
stack[*c] = val;
++(*c);
return *c;
}
int pop(int *c){
if (!(*c)) return -1;
int x = stack[(*c)-1];
stack[(*c)-1] = NULL;
int *r;
printf("%d\n", *c);
r = realloc(stack, ((*c)-1)*sizeof(int));
if(r == NULL){
free(stack);
exit(0);
}
--(*c);
stack = r;
return x;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T03:45:06.500",
"Id": "488381",
"Score": "1",
"body": "Realloc is O(n), because it has to copy n elements from old array to new array (n is the smaller of new and old size). Since both push and pop call it in almost all cases, they are O(n) themselves. To get armotized O(1) you should realloc by doubling the size when n is power of two instead of adding one space for every new element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:24:15.727",
"Id": "488397",
"Score": "1",
"body": "@slepic Good points and suggestions. push O(n) okay, but pop's realloc will not need to do an actual copy. _\"The function **may** move the memory block to a new location\"_ so indeed can be said to be O(1). A stack as linked list of oversized fixed-length arrays might even be better."
}
] |
[
{
"body": "<h1>Create a <code>struct</code> that encapsulates all the details of a stack</h1>\n<p>The problem is that your stack just looks like a pointer to an <code>int</code>, indistinguishable from other pointers to <code>int</code>s. And the first element it points to is treated differently from the other elements. In this case, it is better to create a struct that keeps track of the allocated memory and the size of it, like so:</p>\n<pre><code>struct Stack {\n size_t size;\n int *data;\n};\n</code></pre>\n<p>You initialize it as follows:</p>\n<pre><code>struct Stack stack = {0, NULL};\n</code></pre>\n<p>Now you should change <code>push()</code> and <code>pop()</code> to take a pointer to a <code>struct stack</code>:</p>\n<pre><code>void push(struct Stack *stack, int val) {\n stack->size++;\n int *new_data = realloc(stack->data, stack->size * sizeof *stack->data);\n\n if (!new_data) {\n // error handling here, or just\n abort();\n }\n \n stack->data = stack->new_data;\n stack->data[stack->size - 1] = val;\n}\n</code></pre>\n<p>And similar for <code>pop()</code>. Note that it is common to have functions that operate on an object take the pointer to that object as the first parameter. Also, I made the function return <code>void</code>, there is no need to return the size of the stack size that information is already available to the caller.</p>\n<h1>Avoid using global variables</h1>\n<p>You should avoid using global variables if possible. My example code above no longer requires there to be a global <code>stack</code>. This change allows the code to manage multiple stacks without conflicts.</p>\n<h1>Add functions to create and destroy stacks</h1>\n<p>Instead of requiring the caller to know how to properly initialize a <code>struct Stack</code> and to free it after use, create functions that do this for you. That allows you to change the internals of <code>struct Stack</code> later, without having to change all the places where a stack is used.</p>\n<h1>Use a common prefix to avoid name conflicts</h1>\n<p><code>push()</code> and <code>pop()</code> are very generic names. There are many more things that can have push and pop operations, such as FIFO queues. I recommend you use a common prefix for all data structures and functions for your stack. This can simply be <code>Stack</code> or <code>stack</code> if you think that is unlikely to conflict with anything else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T20:32:34.357",
"Id": "249180",
"ParentId": "249169",
"Score": "6"
}
},
{
"body": "<p>The review by @G. Sliepen is sound and I agree with everything said there. In addition:</p>\n<ul>\n<li><p><em>Never</em> hide pointers behind a <code>typedef</code>! This makes the code very confusing to read for C programmers including yourself. You might think you pass data by value when you aren't, and similar confusing situations.</p>\n</li>\n<li><p><code>... = malloc(sizeof(int));</code> It is inefficient to just allocate 1 item and then almost immediately have to <code>realloc</code>. Note that all dynamic memory location is slow upon creation, and we should drive to minimize the amount of calls to <code>malloc</code>/<code>realloc</code>. Calling them frequently also leads to <em>heap fragmentation</em>, which can lead to wasted memory use and other problems.</p>\n<p>Instead, allocate a "large enough" estimate the first time you call <code>malloc</code>. Maybe 100 items instead. And each time you run out of memory, don't <code>realloc</code> just 1 item more, allocate a lot more and keep track of how much room you have allocated, and how much of that memory you are using.</p>\n<p>Similarly, there is no need to shrink the amount of allocated memory each time you pop something. Deallocation is also slow. Just decrease a counter that keeps track of how much of the allocated memory you are using.</p>\n<p>Stuff like this is what's actually matters when it comes to program performance. "Big O" theory, far less so.</p>\n</li>\n<li><p><code>stack[(*c)-1] = NULL;</code> is incorrect, a bug. You should never assign NULL to common variables, only to pointers. NULL might as well be defined as a pointer type and then this code would break.</p>\n<p>In fact you don't need to clear non-used memory at all, that's pointless.</p>\n</li>\n<li><p>A style issue, but make it a habit to always use <code>{ }</code> even when there is just a single line inside the statement following <code>if/else</code> or loop statements. And avoid sloppy one-liners such as <code>if (!(*c)) return -1;</code></p>\n</li>\n<li><p>The variable name <code>i</code> should only be used for loop iterators. The name <code>i</code> in a loop actually stands for <em>iterator</em>. Don't use it for other purposes like taking user input.</p>\n</li>\n<li><p>Don't use "magic numbers" in the code, such as <code>else if(i == 3)</code>. Use textual constants instead. For example:</p>\n<pre><code> enum\n {\n PUSH = 1,\n POP = 2,\n PRINT = 3,\n QUIT = 4,\n };\n</code></pre>\n</li>\n<li><p>With the above enum, we can clear up the for loop and if statements quite a bit, making the code a bit longer but far more maintainable:</p>\n<pre><code>int user_choice = 0;\nwhile(user_choice != QUIT)\n{\n printf("1. Push\\n2. Pop\\n3. Stack\\n4. Quit\\n>>> ");\n scanf("%d", &user_choice);\n\n switch(user_choice) \n {\n case PUSH: \n {\n printf("Value: ");\n scanf("%d", &i);\n push(i, c);\n break;\n }\n\n case POP:\n {\n printf("Value popped: %d\\n", pop(c));\n break;\n }\n\n case PRINT:\n {\n for(int i = 0; i < *c; i++)\n {\n printf("%d\\n", stack[i]);\n }\n break;\n }\n\n default:\n user_choice = QUIT; // defensive programming, quit upon all invalid choises\n } // switch(user_choice) \n} // while(user_choice != QUIT)\n</code></pre>\n<p>(Note that I deliberately didn't make <code>user_choice</code> an enum type. I did this only because <code>scanf("%d", &user_choice);</code> on an enum isn't safe. Otherwise, a <code>typedef enum</code> would have been preferable to <code>int</code>.)</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T06:58:24.753",
"Id": "249201",
"ParentId": "249169",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249201",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T17:20:20.950",
"Id": "249169",
"Score": "2",
"Tags": [
"performance",
"c",
"stack",
"complexity"
],
"Title": "Dynamic Array Based Stack in C"
}
|
249169
|
<p>I've been tasked with adding <em>RTL support</em> to Material UI project. I've stripped non-essential code down to a simplified version of the <code>UI/Theme</code> module. My solution involves the following:</p>
<ul>
<li>a <code>language</code> module which has a list of RTL language identifiers and some methods for determining language <em>directionality</em>;</li>
<li>a theme-specific <code>i18n</code> module that defines the <code>initial</code> styles and the relevant style property <em>accessors</em>;</li>
<li>refactoring the <code>DefaultTheme</code> for using the <em>i18n-related</em> styles and ensuring updates whenever language <em>directionality</em> has changed.</li>
</ul>
<p>The entry point is <code>getTheme</code>, which now receives an object containing both the <code>themeName</code> and the current <code>language</code>.</p>
<p>I'm looking for an evaluation of clean code and the overall quality of this implementaion. Thanks in advance.</p>
<hr>
<p>Original <code>UI/Theme/index.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>import DefaultTheme from './DefaultTheme';
export const themes = {
'default': DefaultTheme,
};
export const getTheme = (themeName) =>
themes[themeName] || themes['default'];
</code></pre>
<p>New <code>UI/Theme/index.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>import DefaultTheme from './DefaultTheme';
export const themes = {
[DefaultTheme.name]: DefaultTheme,
};
export function getTheme({ themeName, language }) {
if (themes[themeName] == null) {
console.warn(`No theme named '${themeName}'; using '${DefaultTheme.name}'`);
return DefaultTheme;
}
return themes[themeName];
};
</code></pre>
<hr>
<p>Original <code>UI/Theme/DefaultTheme.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { createMuiTheme } from '@material-ui/core/styles';
// Theme for Material-UI components
const muiTheme = createMuiTheme({
overrides: {
MuiTypography: {
h6: {
fontWeight: 400,
},
},
MuiInput: {
underline: {
'&:before': {
borderBottom: `1px solid #BBBBBB`,
},
},
},
MuiIconButton: {
root: {
color: '#111',
},
},
MuiTab: {
textColorPrimary: {
color: '#fff',
},
root: {
paddingTop: 0,
paddingBottom: 0,
minHeight: 32,
},
},
MuiButtonBase: {
root: {
cursor: 'default',
},
},
MuiTableCell: {
sizeSmall: {
paddingTop: 0,
paddingBottom: 0,
},
},
MuiCheckbox: {
root: {
marginTop: -9,
marginBottom: -9,
},
},
MuiButton: {
root: {
borderRadius: 0,
fontWeight: 400,
},
},
},
});
const theme = {
muiTheme,
};
export default theme;
</code></pre>
<p>New <code>UI/Theme/DefaultTheme.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { createMuiTheme } from '@material-ui/core/styles';
import { derive, compose, blend } from '../../Utils/Object';
import { text, initial as i18n } from './i18n';
// Theme for Material-UI components
const muiTheme = createMuiTheme({
overrides: {
...i18n,
MuiTypography: blend({
h6: {
fontWeight: 400,
},
}, [text.root]),
MuiInput: blend({
underline: {
'&:before': {
borderBottom: `1px solid #BBBBBB`,
},
},
}, [text.root]),
MuiIconButton: {
root: {
color: '#111',
},
},
MuiTab: blend({
textColorPrimary: {
color: '#fff',
},
root: {
paddingTop: 0,
paddingBottom: 0,
minHeight: 32,
},
}, [text.root]),
MuiButtonBase: {
root: {
cursor: 'default',
},
},
MuiTableCell: {
sizeSmall: {
paddingTop: 0,
paddingBottom: 0,
},
},
MuiCheckbox: {
root: {
marginTop: -9,
marginBottom: -9,
},
},
MuiButton: blend({
root: {
borderRadius: 0,
fontWeight: 400,
},
}, [text.label]),
},
});
const theme = {
/**
* Obtains the `muiTheme` instance.
*
* This property accessor ensures that the `muiTheme` instance
* will be reapplied by `ThemeProvider` on every update, _only_
* when language directionality has changed.
*/
get muiTheme() {
const former = language.is_ltr;
const current = language.is_ltr;
return former !== current ? derive(muiTheme) : muiTheme;
},
};
export default compose({ name: 'default', }, theme);
</code></pre>
<hr>
<p>New <code>UI/Theme/i18n.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>function _direction(key) {
return {
[key]: {
get direction() {
const { is_ltr } = language;
return is_ltr ? 'unset' : 'rtl';
},
},
};
}
export const text = {
root: _direction('root'),
label: _direction('label'),
};
function _order(key) {
return {
[key]: {
get order() {
const { is_ltr } = language;
return is_ltr ? 'unset' : (styles.order?.rtl ?? 100);
},
},
};
}
export const icon = {
root: _order('root'),
};
const styles = {
order: {
rtl: 100,
},
};
export default styles;
export const initial = {
MuiTypography: text.root,
MuiInput: text.root,
MuiTab: text.root,
MuiFormControlLabel: text.root,
MuiTextField: text.root,
MuiButton: text.label,
MuiSvgIcon: icon.root,
};
</code></pre>
<p>New <code>Utils/i18n/language.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { isObject, isString } from '../Object';
const _rtl = new Set([
/******* Hebrew scripts *******/
'he'/* Hebrew */,
'ji'/* Yiddish */,
'yi'/* Yiddish */,
/******* Arabic scripts *******/
'ar'/* Arabic */,
'az'/* Azerbaijani */,
'jv'/* Javanese */,
'ks'/* Kashmiri */,
'kk'/* Kazakh */,
'ku'/* Kurdish */,
'ms'/* Malay */,
'ml'/* Malayalam */,
'ps'/* Pashto */,
'fa'/* Persian */,
'pa'/* Punjabi */,
'sd'/* Sindhi */,
'so'/* Somali */,
'tk'/* Turkmen */,
'ug'/* Uighur */,
'ur'/* Urdu */,
]);
export default class Language {
constructor(name) {
this._name = '--';
if (isString(name)) {
this._name = /^([\w]{2})?/.exec(name)[1] ?? this._name;
}
}
get direction() {
return this.is_ltr ? 'ltr' : 'rtl';
}
get is_ltr() {
return !_rtl.has(this._name);
}
get name() {
return this._name;
}
static from(lang) {
return isObject(lang) ? lang : new Language(lang);
}
static directionFor(lang) {
return Language.from(lang)?.direction;
}
static is_ltr(lang) {
return Language.from(lang)?.is_ltr;
}
}
</code></pre>
<p>New <code>Utils/Object.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>/**
* Useful for storing some metadata for e.g. `explode()` and `assemble()`.
*/
const _records = new WeakMap();
/**
* When given a `record` argument, stores it in `_records` with `subject`
* as the key; otherwise, returns the value in `_records` stored at
* `subject`.
*/
function _refer(subject, record) {
if (subject instanceof Void) return;
if (arguments.length < 2) return _records.get(subject);
_records.set(subject, record);
return record;
}
/**
* Useful for checking is some value is `null` or `undefined`.
*/
export const Void = {
[Symbol.hasInstance](subject) {
return typeof subject === 'undefined' || subject === null;
},
}
/**
* Useful for checking if some value is falsy and not `undefined`.
*/
export const False = {
[Symbol.hasInstance](subject) {
return subject !== undefined && !subject;
},
}
/**
* Useful for checking if some value is truthy.
*/
export const True = {
[Symbol.hasInstance](subject) {
return !!subject;
},
}
/**
* Useful for checking if some value supports iteration.
*/
export const Iterable = {
[Symbol.hasInstance](subject) {
if (subject instanceof Void) return false;
return isFunction(subject[Symbol.iterator]);
},
}
/**
* Useful for checking if some value is a generator.
*/
export const Generator = {
[Symbol.hasInstance](subject) {
if (subject instanceof Void) return false;
return subject[Symbol.toStringTag] === 'Generator';
},
}
export function isObject(subject) {
return typeof subject === 'object';
}
export function isString(subject) {
return typeof subject === 'string';
}
/**
* Checks if given `subject` is an _actual_ number, i.e. not NaN.
*/
export function isNumber(subject) {
return typeof subject === 'number' && !isNaN(subject);
}
export const { isArray } = Array;
export function isFunction(subject) {
return typeof subject === 'function';
}
export const { isExtensible } = Object;
/**
* Check if given `subject` has a property named '`key`'.
*/
export function scan(subject, key) {
return subject != null ? Reflect.has(subject, key) : false;
}
/**
* Useful for getting some value (by given `key`) from given `subject`
* in a null-safe manner.
*
* Example:
* tap(foo, bar)
* where `foo` may be nullish and/or the key stored in `bar` may or may
* not exist in `foo`.
*/
export function tap(subject, key) {
return subject != null ? Reflect.get(subject, key) : undefined;
}
/**
* Obtains the enumerable own property keys of given `subject`,
* in a null-safe manner.
*/
export function keysOf(subject) {
return subject != null ? Object.keys(subject) : undefined;
}
/**
* Does the same as `keysOf()`, however it falls back to an empty array
* instead of `undefined`.
*/
keysOf.loose = function(subject) {
return keysOf(subject) ?? [];
}
/**
* Obtains the enumerable own property entries on given `subject`;
* properly handles Array and Function inputs.
*
* Example:
* explode(null)
* returns `undefined`.
*
* Example:
* explode({ get foo() { return 'bar'; } })
* returns `[['foo', 'bar']]`.
*
* Example:
* explode(Object.assign(['foo', 'bar'], { baz: 'qux' }))
* returns `[['baz', 'qux']]` and stores `['foo', 'bar']` (i.e. the
* original array object) in `_records`, for later.
*/
export function explode(subject) {
if (subject instanceof Void) return;
const out = Object.entries(subject);
switch (true) {
case isArray(subject):
const record = _refer(out, []);
return out.filter(([k, v]) => {
if (/\s/.test(k)) return true;
const i = parseInt(k);
if (!isNumber(i)) return true;
record[i] = v;
return false;
});
case isFunction(subject):
case subject instanceof Generator:
_refer(out, subject);
return out;
}
}
function _assemble(target, source) {
if (target instanceof Void) return target;
if (!(source instanceof Iterable)) return target;
for (const [key, value] of source) {
target[key] = value;
}
return target;
}
/**
* Constructs a new object from the entries found by iterating
* given `subject`. Uses any values found in `_records` (stored
* by previous calls to `explode()` for e.g.). If any `sources`
* are given, they are '_assemble'd to given `subject` (if
* non-nullish).
*/
export function assemble(subject, ...sources) {
if (arguments.length === 0) return {};
if (sources.length === 0) {
if (subject instanceof Void) return;
const schema = isArray(subject) ? subject : subject.entries();
const record = _refer(schema);
if (isArray(record)) {
return _assemble([...record], schema);
}
// TODO: Handle `Function` and `Generator` here
return Object.fromEntries(schema);
}
if (subject instanceof Void) return subject;
for (const source of sources) {
_assemble(subject, source);
}
return subject;
}
/**
* Assigns all enumerable own values from each element of
* `sources` onto given `target`, in a null-safe manner.
*/
export function extend(target, ...sources) {
if (target instanceof Void) return target;
return Object.assign(target, ...sources);
}
/**
* Returns the value at given second argument (as key) if a string,
* otherwise constructs a new object with all of given `subject`'s
* properties filtered by the contents of the second argument (as
* `keys`).
*/
export function extract(subject, keys) {
if (subject instanceof Void) return subject;
if (isString(keys)) return subject[keys];
if (!(keys instanceof Iterable)) return { ...subject };
const out = {};
for (const key of keys) {
const value = subject[key];
if (value === undefined) continue;
out[key] = value;
}
return out;
}
/**
* Obtains the descriptor of given `subject`'s own property at
* given `key`.
*/
function _describe(subject, key) {
if (subject instanceof Void) return;
return Object.getOwnPropertyDescriptor(subject, key);
}
/**
* Obtains the descriptor of given `subject`'s own property at
* given `key`, or all property descriptors if no `key` is given;
* only the enumerable own properties are inspected.
*/
export function describe(subject, key) {
if (subject instanceof Void) return;
if (arguments.length > 1) return _describe(subject, key);
return assemble(keysOf(subject).map(k => [k, _describe(subject, k)]));
}
/**
* Attaches (`define`s) given property (`key` + `spec`) or properties
* (given as `key`) onto `target`, in a null-safe manner.
*/
export function define(target, key, spec) {
if (target instanceof Void) return target;
if (arguments.length > 2) {
key = {
[key]: {
...spec,
configurable: spec?.configurable ?? true,
enumerable: spec?.enumerable ?? true,
...(
scan(spec, 'value') ?
{ writable: spec?.writable ?? false } :
null
),
},
};
}
if (key instanceof Void) return target;
return Object.defineProperties(target, key);
}
/**
* Attaches (`define`s) given `key`-`value` pair as a new property
* upon given `target`, in a null-safe manner.
*/
export function install(target, key, value) {
return define(target, key, { value, writable: true, });
}
/**
* Obtains an unified descriptors object based on given `sources`.
*/
function toSchema(sources) {
return extend({}, ...sources.map(src => describe(src)));
}
/**
* Defines all enumerable own properties of each given `schema`
* onto given `target`. Returns a loose replica of given `target`
* if no `schema` is given.
*
* Example:
* merge({ foo: 'foo' }, { get bar() { return 'bar'; } })
* returns:
* { foo: 'foo', get bar() { return 'bar'; } }
*/
export function merge(target, ...schemas) {
if (!isExtensible(target)) return target;
if (schemas.length === 0) return merge({}, target);
return define(target, toSchema(schemas));
}
/**
* Constructs a new object inheriting given `subject` and
* enhanced by given `schema`, in a null-safe manner.
*/
export function derive(subject, schema) {
return Object.create(subject ?? null, schema ?? undefined);
}
/**
* Returns a new getter descriptor which returns the value at
* given `key` from given `subject`.
*/
function _getter(subject, key) {
return {
get() { return subject[key]; },
configurable: true,
enumerable: true,
};
}
/**
* Constructs a new object which effectively `mirrors` given `subject`
* via delegation by defining property getters to corresponding
* own enumerable properties of `subject`. If `inherit` is truthy,
* the given `subject` is also inherited.
*/
export function mirror(subject, inherit) {
if (subject instanceof Void) return subject;
const schema = assemble(keysOf(subject).map((k) => [k, _getter(subject, k)]));
return inherit ? derive(subject, schema) : define({}, schema);
}
/**
* Constructs a new object that inherits from givenb `template`
* and also has all enumerable own properties of every given
* `schema` defined.
*/
export function compose(template, ...schemas) {
return derive(template, toSchema(schemas));
}
/**
* This is basically a deep version of `merge()` that recursively
* `merge`s given `extra` on given `target`.
*/
function _blend(target, extra) {
if (!isExtensible(target)) return merge(extra);
for (const key of keysOf.loose(extra)) {
const spec = describe(extra, key);
if (scan(target, key)) {
install(target, key, _blend(target[key], extra[key]));
} else {
define(target, key, spec);
}
}
return target;
}
/**
* This is basically a deep version of `merge()` that recursively
* `merge`s every element of given `extra`s array on given `target`.
*
* Example:
* blend({ foo: { bar: 'baz' } }, { foo: { get baz() { return 'qux'; } } })
* returns `{ foo: { bar: 'baz', get baz() { return 'qux'; } } }`.
*
* Example:
* blend({ foo: { bar: 'baz', qux: 'quux' } }, { foo: { bar: 'qux' } })
* returns `{ foo: { bar: 'qux', qux: 'quux' } }`.
*/
export function blend(target, extras) {
if (target instanceof Void) return target;
if (!(extras instanceof Iterable)) return target;
for (const extra of extras) {
target = _blend(target, extra);
}
return target;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T17:04:02.180",
"Id": "488541",
"Score": "1",
"body": "Please don't modify the code in your question after receiving answers, doing so goes against site policy. More reviews may be coming in, and it gets awfully confusing if answers review different versions of the same code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:36:43.587",
"Id": "488637",
"Score": "2",
"body": "(To whoever challenged *authorship of code*: please disclose cause.)"
}
] |
[
{
"body": "<p><strong>Default or named exports?</strong> In some of the modules, you use default exports, and in others, you use named exports. It's not much of a problem, but the inconsistency has a chance of causing problems later, especially once you have lots of modules in a project.</p>\n<blockquote>\n<p>I want to import Foo. Now, do I do <code>import Foo from './Foo';</code> or do I do <code>import { Foo } from './Foo';</code>?</p>\n</blockquote>\n<p>I'd prefer to choose one style and stick with it in most cases.</p>\n<p><strong>Comparison</strong> You have <code>if (themes[themeName] == null) {</code>. This is a bit strange for a few reasons: if a property isn't defined on the object, it'll be <code>undefined</code>, not <code>null</code>. You can use <code>==</code> to coerce <code>undefined</code> on the left to <code>null</code>, but that's weird. Readers of the code will have to understand the <a href=\"https://stackoverflow.com/q/359494\">weird ways that <code>==</code> works</a>, which should not be a requirement. When you need to compare, better to <a href=\"https://eslint.org/docs/rules/eqeqeq\" rel=\"nofollow noreferrer\">always use <code>===</code></a>. Here, since a theme on the <code>themes</code> object will be truthy, I'd consider:</p>\n<pre><code>if (themes[themeName]) {\n return themes[themeName];\n}\n</code></pre>\n<p><strong><code>_rtl</code></strong>: Modules have their own self-contained scope, so I don't think the <code>_</code> adds anything useful, and the variable name could be made more precise by calling it something like <code>rtlLanguages</code>.</p>\n<p><strong>Language constructor and regex</strong> A few things stood out to me here. You have:</p>\n<pre><code>constructor(name) {\n this._name = '--';\n if (isString(name)) {\n this._name = /^([\\w]{2})?/.exec(name)[1] ?? this._name;\n }\n}\n</code></pre>\n<p>You import <code>isString</code> from a big file elsewhere in order to test if <code>name</code> is a string. When I saw that, I thought "<em>Why is that an import and a function call, rather than just a <code>typeof</code> check in the constructor? It sounds like <code>isString</code> is doing a more elaborate check that requires generalization</em>" - but it's actually only doing a <code>typeof</code> check. Putting the logic of such a trivial check so far from where the check is needed doesn't seem right - I'd inline <code>typeof name === 'string'</code> instead, it'll make more sense at a glance.</p>\n<p>The regular expression can be improved.</p>\n<ul>\n<li>If a single character needs to be quantified, there's no need to put it into a character set - just put the quantifier to the right of the token, <code>\\w{2}</code>.</li>\n<li>Optional capture groups aren't very intuitive. I bet if you took a survey of whether a non-matching group returned <code>undefined</code>, <code>null</code>, or the empty string, the results wouldn't be much greater than chance. I'd prefer to have a regular expression that matches 2 characters spanning the whole string instead: <code>/^\\w{2}$/.exec(name)?.[0] || this._name</code></li>\n<li>Rather than assigning to <code>this._name</code> twice, you can alternate with <code>'--'</code> on the right if you want. (Just a suggestion, I find it more elegant, but you might not like it)\n<pre><code>const possibleName = typeof name === 'string' && /^\\w{2}$/.exec(name)?.[0];\nthis._name = possibleName || '--';\n</code></pre>\n</li>\n</ul>\n<p><strong>Language module</strong> The whole language module seems oddly complex. If it were me, I'd find it simpler and more intuitive to just export a function that checks if the passed element is in the Set: <code>export const isLTR = lang => !rtlLanguages.has(lang);</code> and nothing else. You also currently aren't differentiating between languages which are LTR, and languages which are unknown. It may well not matter, depending on how it's used, but that's just something to keep in mind.</p>\n<p><strong>Types</strong> There are quite a lot of places in the code where you're checking the types of arguments before proceeding to operate on them, like <code>if (subject instanceof Void) return false;</code>. You might consider using Typescript to <em>enforce</em> correct typings so that nonsensical function calls generate warnings in the caller. Typescript can turn many potential runtime errors and bugs into easy-to-fix compile-time warnings. It takes some time to get used to, but for anything other than a tiny script, I find it immensely helpful. Just an idea. <a href=\"https://stackoverflow.com/a/59253145\">JSDoc</a> arguments is another more lightweight option.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:52:33.847",
"Id": "249223",
"ParentId": "249170",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249223",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T17:46:52.827",
"Id": "249170",
"Score": "1",
"Tags": [
"javascript",
"i18n"
],
"Title": "Implement RTL functionality in a Material UI app"
}
|
249170
|
<p>I started learning Django and now I want to write some tests for my application. After reading some blog posts and watching youtube tutorials I wrote tests for URLs. Look at below.</p>
<blockquote>
<p><strong>urls.py</strong></p>
</blockquote>
<pre><code>from .views import HomeView, ArticleDetailView, CreatePostView, UpdatePostView, DeletePostView, StatisticcsView, CreatePostCategoryView, CategoryView, LikeView, CreateCommentView
urlpatterns = [
path('', HomeView.as_view(), name="home"),
path('article/<int:pk>', ArticleDetailView.as_view(), name="article_detail"),
path('add_post/', CreatePostView.as_view(), name="add_post"),
path('add_category/', CreatePostCategoryView.as_view(), name="add_category"),
path('article/edit/<int:pk>', UpdatePostView.as_view(), name="update_post"),
path('article/delete/<int:pk>', DeletePostView.as_view(), name="delete_post"),
path('category/<str:cats>/', CategoryView, name="category"),
path('like/<int:pk>', LikeView, name='like_post'),
path('statistics/', StatisticcsView.as_view(), name="statistics"),
path('article/<int:pk>/comment/', CreateCommentView.as_view(), name="add_comment"),
]
</code></pre>
<p><strong>test_urls.py</strong></p>
<pre><code>from django.test import SimpleTestCase
from django.urls import reverse, resolve
from blog.views import HomeView, ArticleDetailView, CreatePostView, CreatePostCategoryView, UpdatePostView, DeletePostView, CategoryView, LikeView, StatisticcsView, CreateCommentView
class TestBlogUrls(SimpleTestCase):
def test_home_url_is_resolved(self):
url = reverse('home')
self.assertEquals(resolve(url).func.view_class, HomeView)
def test_article_detail_url_is_resolved(self):
url = reverse('article_detail', args=[1])
self.assertEquals(resolve(url).func.view_class, ArticleDetailView)
def test_create_post_url_is_resolved(self):
url = reverse('add_post')
self.assertEquals(resolve(url).func.view_class, CreatePostView)
def test_create_post_category_url_is_resolved(self):
url = reverse('add_category')
self.assertEquals(resolve(url).func.view_class, CreatePostCategoryView)
def test_update_post_url_is_resolved(self):
url = reverse('update_post', args=[1])
self.assertEquals(resolve(url).func.view_class, UpdatePostView)
def test_delete_post_url_is_resolved(self):
url = reverse('delete_post', args=[1])
self.assertEquals(resolve(url).func.view_class, DeletePostView)
def test_category_url_is_resolved(self):
url = reverse('category', args=['python'])
self.assertEquals(resolve(url).func, CategoryView)
def test_like_post_url_is_resolved(self):
url = reverse('like_post', args=[1])
self.assertEquals(resolve(url).func, LikeView)
def test_statistics_url_is_resolved(self):
url = reverse('statistics')
self.assertEquals(resolve(url).func.view_class, StatisticcsView)
def test_add_comment_url_is_resolved(self):
url = reverse('add_comment', args=[1])
self.assertEquals(resolve(url).func.view_class, CreateCommentView)
</code></pre>
<p>My question is if this practice is correct or maybe I can write it better. Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:31:51.300",
"Id": "488339",
"Score": "0",
"body": "\"if this practice is correct\" What do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:45:11.057",
"Id": "488341",
"Score": "0",
"body": "I mean whether the tests written in this way are correct (do they have any defects). I also try to make sure there is no other, better solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:49:34.287",
"Id": "488342",
"Score": "0",
"body": "You tested them, right? So you think they're correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:57:42.440",
"Id": "488343",
"Score": "0",
"body": "Yes, I tested them, and all tests passed. But I am not sure if the solution which I presented is the best practice. I want to make sure that such a solution is in line with good practices. If so, that's perfect, otherwise, I'd like to improve my code."
}
] |
[
{
"body": "<p>The tests are technically correct, but the value they have doesn't match the amount of time you spent on them. It looks like you're using class-based views, and in such case I'd expect <code>LikeView</code> and <code>CategoryView</code> in the routes should be called the same way as other views, ie. with <code>.as_view()</code>. If my assumption is correct, then your tests should at least catch this bug, otherwise they are just giving you a false feeling of safety that things work. So you'd need to write another set of tests to check yet another aspect of the routes resolving. That feels like you'd spent all your time just by writing tests. And if each test would test a particular tiny piece of functionality, you'll have a hard time during refactoring when a lot of tests will start breaking needlessly.</p>\n<p>If you want to test that the routes are resolved correctly, it's usually done by using <a href=\"https://docs.djangoproject.com/en/3.1/topics/testing/tools/#the-test-client\" rel=\"nofollow noreferrer\">Test Client</a> and checking the response status is HTTP 200 (or whatever you expect there). But how do you know it was resolved to the correct view? Well you don't, but knowing the name of the resolved class is not really that important. I assume you are (indirectly) testing the whole functionality during development in browser as well, so once the things works, the chance that there will be a regression and a route will suddenly start resolving incorrectly is close to zero. If you want to put even more value in the tests, you should also test the models are modified correctly (eg. after calling <code>delete_post</code>, check if the record is really gone from DB). This kind of tests would look reasonable to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:21:13.747",
"Id": "249192",
"ParentId": "249173",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249192",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:06:34.703",
"Id": "249173",
"Score": "1",
"Tags": [
"python",
"unit-testing",
"django"
],
"Title": "Test django URLs"
}
|
249173
|
<p>This is my first project using Python. I made a simple password generator that checks user input. How can I improve it?</p>
<pre><code>import random
def password_generator():
password = []
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z"]
password_length = 0
password_numbers = []
password_letters = []
# Input the length of the password
while True:
password_length_input = input("Choose the length of your password with numbers between 6 and 15:\n")
if not password_length_input.isnumeric():
print(f"{password_length_input} is not a number, try again:")
continue
else:
password_length = int(password_length_input)
print(f"Password length: {password_length}")
if 6 <= password_length <= 15:
break
else:
print("The password must be between 6 and 15 characters, try again:")
continue
# Input the amount of numbers in password
while True:
password_numbers_input = \
input(f"Choose the amount of numbers you want in your password, max {password_length}\n")
if not password_numbers_input.isnumeric():
print(f"{password_numbers_input} is not a number try again")
continue
elif int(password_numbers_input) > password_length:
password_numbers = 0
print(f"The value is too high, choose maximum {password_length} numbers")
continue
else:
password_numbers = int(password_numbers_input)
print(f"Password numbers: {password_numbers}")
for number in range(0,password_numbers):
password.append(random.randrange(0,9))
break
# Check for numbers and letters in password
while True:
if password_numbers == password_length:
print(f"The password will be only {password_numbers} numbers, no letters.")
break
else:
password_letters = password_length - password_numbers
print(f"""Your password will be {password_length} characters with {password_numbers} numbers and {password_letters} letters.""")
for letter in range(0,password_letters):
password.append(random.choice(letters))
break
random.shuffle(password)
password_string = ''.join([str(item) for item in password])
print(f"Your password is:\n{password_string}")
password_generator()
</code></pre>
<p>Usage example:</p>
<pre><code>Choose the length of your password with numbers between 6 and 15:
Password length: 8
Choose the amount of numbers you want in your password, max 8
Password numbers: 2
Your password will be 8 characters with 2 numbers and 6 letters.
Your password is:
pzc11bmf
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T08:02:29.157",
"Id": "488402",
"Score": "2",
"body": "Are you required to ask the user interactively for the 2 pieces of information? I ask because a more typical design for a password creation script would just get the required parameters directly on the command line and then just print the password, with no interactivity at all: `python create-password 8 2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T12:27:56.033",
"Id": "488417",
"Score": "1",
"body": "Note: [`random`](https://docs.python.org/3/library/random.html) should not be used for security purposes, but you can use [`secrets`](https://docs.python.org/3/library/secrets.html) instead; you probably should replace `random` with `secrets.SystemRandom()` if generating real passwords or any other cryptographically secure value."
}
] |
[
{
"body": "<blockquote>\n<p><strong>First</strong></p>\n</blockquote>\n<p>I suggest creating separate methods for each while loops.</p>\n<blockquote>\n<p><strong>Second</strong></p>\n</blockquote>\n<p>"while True" loop is not a good practice, I think. Instead of that, use condition.</p>\n<blockquote>\n<p><strong>Third</strong></p>\n</blockquote>\n<p>I suggest creating PasswordGenerator class which will contain your code. It will help you to expand your code in the future.</p>\n<p>Base structure for your project</p>\n<pre><code> class PasswordGenerator():\n \n check_declared_password_length():\n ...\n \n check_amount_of_password_numbers():\n ...\n *\n *\n *\n</code></pre>\n<p>For the end remember to create functions with one responsibility. After that, you can write unit tests for each of that and it will be easier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T19:19:24.607",
"Id": "249177",
"ParentId": "249174",
"Score": "3"
}
},
{
"body": "<p>A more straightforward way of generating a random string:</p>\n<pre><code>import random\nimport string\n\n def get_random_string(length):\n letters = string.ascii_lowercase\n result_str = ''.join(random.choice(letters) for i in range(length))\n print("Random string of length", length, "is:", result_str)\n \n get_random_string(8)\n get_random_string(8)\n get_random_string(6)\n</code></pre>\n<p>borrowed from <a href=\"https://pynative.com/python-generate-random-string/\" rel=\"noreferrer\">here</a>, and there are more examples.</p>\n<p>Now if you have specific requirements like a minimum number of digits, you can either tweak the formula, or generate two lists and merge them while shuffling the values.</p>\n<p>There is an example in the link I quoted above: "Generate a random alphanumeric string with a fixed count of letters and digits"\n=> merging two list comprehensions.</p>\n<p>The way you are doing it is procedural but not Pythonic. It is kinda reinventing the wheel.</p>\n<p>At the very least, your list of allowed characters should look like this:</p>\n<pre><code>letters = "abcdefghijklmnopqrstuvwxyz"\n</code></pre>\n<p>Then you pick out a random letter eg <code>letters[3]</code> will return 'd' since the list is 0-based and Python treats strings as sequences of characters. Using shuffle like you are already doing, you can write more concise code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T20:31:51.390",
"Id": "249179",
"ParentId": "249174",
"Score": "6"
}
},
{
"body": "<blockquote>\n<pre><code>letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",`\n "v", "w", "x", "y", "z"]\n</code></pre>\n</blockquote>\n<p>This method of writing the alphabet is very error prone. I would import <code>string</code> and use <code>string.ascii_lowercase</code> in place of <code>letters</code>. If you want to generate your own range of letters for whatever reason, I would write</p>\n<pre><code>letters = [chr(n) for n in range(ord('a'), ord('z') + 1)]\n</code></pre>\n<p>since there's then no danger of omitting or duplicating a letter.</p>\n<hr />\n<blockquote>\n<pre><code>password_length = 0\npassword_numbers = []\npassword_letters = []\n</code></pre>\n</blockquote>\n<p>These default values are never used. The defaults for <code>password_numbers</code> and <code>password_letters</code> don't make sense since those variables hold numbers. I would delete all three lines.</p>\n<hr />\n<blockquote>\n<pre><code>if not password_length_input.isnumeric():\n print(f"{password_length_input} is not a number, try again:")\n continue\nelse:\n password_length = int(password_length_input)\n print(f"Password length: {password_length}")\n</code></pre>\n</blockquote>\n<p>I would instead write</p>\n<pre><code>try:\n password_length = int(password_length_input)\nexcept ValueError:\n print(f"{password_length_input} is not a number, try again:")\n continue\nprint(f"Password length: {password_length}")\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>while True:\n if password_numbers == password_length:\n ...\n break\n else:\n ...\n break\n</code></pre>\n</blockquote>\n<p>There is no sense in having a <code>while</code> loop here since you always break out of it on the first iteration.</p>\n<hr />\n<blockquote>\n<pre><code>range(0,password_numbers)\n</code></pre>\n</blockquote>\n<p>You can just write <code>range(password_numbers)</code>.</p>\n<hr />\n<blockquote>\n<pre><code>password.append(random.randrange(0,9))\n</code></pre>\n</blockquote>\n<p>This will append a digit from 0 to 8 inclusive, never 9. If you want all ten digits you should write <code>random.randrange(10)</code>. Or, perhaps better, use <code>random.choice(string.digits)</code>.</p>\n<hr />\n<blockquote>\n<pre><code>password_string = ''.join([str(item) for item in password])\n</code></pre>\n</blockquote>\n<p>If you use <code>string.digits</code> then every element of <code>password</code> will be a character so you can simplify this to <code>password_string = ''.join(password)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:06:52.160",
"Id": "249182",
"ParentId": "249174",
"Score": "10"
}
},
{
"body": "<p>I definitely <strong>don't recommend using <code>random</code> for generating secure passwords</strong>. The reason being <code>random</code> is predictable and anyone can guess the next set of passwords that it is going to generate. So it is better to replace <code>random</code> with <code>secrets</code> and use <code>secrets.SystemRandom()</code></p>\n<p><strong>Also, note one more flaw as you are using <code>random.choice()</code> method it can repeat the characters while generating. So if you don’t want to repeat the characters and still want to use <code>random</code>, then use <code>random.sample()</code> method.</strong></p>\n<p>If you are looking for a secure and robust password, Python has a module called as secrets, and you could utilize this to generate a random secured password.</p>\n<p>The algorithm used by secrets is less predictable when compared to the random string module generation.</p>\n<pre><code>import secrets\nimport string\n\ndef generateRandomCryptoPassword(length):\n # Generate random password using cryptographic way\n letters = string.ascii_lowercase + string.digits + string.punctuation\n result_str = ''.join(secrets.choice(letters) for i in range(length))\n print("Strong Password using Crpyto of length", length, "is:", result_str)\n\n\ngenerateRandomCryptoPassword(12)\n</code></pre>\n<p>Source : <a href=\"https://itsmycode.com/how-to-generate-a-random-string-of-a-given-length-in-python/\" rel=\"nofollow noreferrer\">Generate a random string of a given length in Python</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T23:41:59.717",
"Id": "529809",
"Score": "1",
"body": "Your assertion that all of `random` is predictable is incorrect. If you read secrets' source then you'll see [`secrets.SystemRandom` is `random.SystemRandom`](https://github.com/python/cpython/blob/9f5fe7910f4a1bf5a425837d4915e332b945eb7b/Lib/secrets.py#L19)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T23:50:01.613",
"Id": "529810",
"Score": "1",
"body": "what you are saying is partially true, it internally uses random.SystemRandom. but t the same time if you look at the secrets.py they do retrieve a random strings in hex first and they convert into base64 which is more secure. (base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T23:32:25.190",
"Id": "268631",
"ParentId": "249174",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:36:00.210",
"Id": "249174",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "First password generator in Python"
}
|
249174
|
<p>So, I am learning Swift and as a little exercise I tried to implement a BruteForce algorithm. That algorithm is pretty simple however it is a bit slow too... Well, I am new to Swift, so maybe some optimisations are possible ?</p>
<p>Let's start with some useful prerequisites:</p>
<pre><code>extension String {
var digits: String { return "0123456789" }
var lowercase: String { return "abcdefghijklmnopqrstuvwxyz" }
var uppercase: String { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }
var punctuation: String { return "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" }
var letters: String { return lowercase + uppercase }
var printable: String { return digits + letters + punctuation }
mutating func replace(at index: Int, with character: Character) {
var stringArray = Array(self)
stringArray[index] = character
self = String(stringArray)
}
}
</code></pre>
<p>Let's now implement the BruteForce algorithm</p>
<pre><code>func indexOf(character: Character, _ array: [String]) -> Int {
return array.firstIndex(of: String(character))!
}
func characterAt(index: Int, _ array: [String]) -> Character {
return index < array.count ? Character(array[index])
: Character("")
}
func generateBruteForce(_ string: String, fromArray array: [String]) -> String {
var str: String = string
if str.count <= 0 {
str.append(characterAt(index: 0, array))
}
else {
str.replace(at: str.count - 1,
with: characterAt(index: (indexOf(character: str.last!, array) + 1) % array.count, array))
if indexOf(character: str.last!, array) == 0 {
str = String(generateBruteForce(String(str.dropLast()), fromArray: array)) + String(str.last!)
}
}
return str
}
</code></pre>
<p>Now we can use it that way</p>
<pre><code>import Foundation
let ALLOWED_CHARACTERS: [String] = String().printable.map { String($0) }
let MAXIMUM_PASSWORD_SIZE: Int = 3
var password: String = ""
// Will strangely ends at 0000 instead of ~~~
while password.count <= MAXIMUM_PASSWORD_SIZE { // Increase MAXIMUM_PASSWORD_SIZE value for more
password = generateBruteForce(password, fromArray: ALLOWED_CHARACTERS)
// Your stuff here
print(password)
// Your stuff here
}
</code></pre>
<p>It will print</p>
<pre><code>0
1
2
[...]
{
|
}
~
00
01
and so on...
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T18:41:05.583",
"Id": "249175",
"Score": "1",
"Tags": [
"swift"
],
"Title": "Simple bruteforce algorithm in Swift"
}
|
249175
|
<p>My program tracks betting odds for the given list of events and sends notifications when odds reach specified value.</p>
<p>The odds are in the database collected by another program. The required odds are in the same database.
Each <code>N</code> seconds the required odds are retrieved from the database, compared with the actual odds and if the latter are good enough, the notification is being sent and required odds get deleted from the "wishlist".</p>
<p><strong>The example of required odds:</strong></p>
<p><code>[1168358979, 'totals', 'under', 10.5, 2.0]</code><br />
<em>Interpretation</em>: we are looking for total under 10.5 in event 1168358979 with required odds >= 2.0</p>
<p>Besides general review of my code I'm highly interested in how to add a feature, which allows to specify what should happen with the "wishlist" when odds are good enough: at the moment the required odds are just deleted, however I would like to have an option to "mute" them for a specific period of time, or raise their value by some magnitude.</p>
<p>The program is split into 3 files:</p>
<ul>
<li><code>odds_tracker.py</code> is an entry point</li>
<li><code>database.py</code> for making database queries</li>
<li><code>telegram.py</code> for sending notifications via telegram</li>
</ul>
<p><em>odds_tracker.py</em></p>
<pre><code>"""
A tool for tracking betting odds for the selected events and sending notifications
when odds reach the value that we are looking for.
"""
from datetime import date
import time
from typing import NamedTuple, Tuple
import database
import telegram
REQUESTS_DELAY = 5
class DesiredOdds(NamedTuple):
"""Represents desired odds."""
event_id: int
bet_type: str
side: str
points: float
price: float
def are_odds_good(desired_odds: DesiredOdds, actual_odds: Tuple[float, float]) -> bool:
"""
Returns True if actual odds are greater than or equal to desired odds.
Returns False otherwise.
"""
if desired_odds.side in ['home', 'over']:
return actual_odds[0] >= desired_odds.price
elif desired_odds.side in ['away', 'under']:
return actual_odds[1] >= desired_odds.price
else:
raise ValueError(f'Side should be home, away, over or under, {desired_odds.side} given.')
def track_odds() -> None:
"""
Tracks odds for the given list of events, sends notification when odds are good.
"""
while True:
tracked_events = database.get_tracked_events()
for event in tracked_events:
desired_odds = DesiredOdds(*event[1:])
actual_odds = database.get_latest_odds(desired_odds.event_id,
desired_odds.bet_type,
desired_odds.points)
if are_odds_good(desired_odds, actual_odds):
send_notification(desired_odds, actual_odds)
database.delete_event(event[0])
time.sleep(REQUESTS_DELAY)
def send_notification(event: DesiredOdds, actual_odds: Tuple[float, float]) -> None:
"""
Sends notification about good odds being available.
"""
if event.side in ['home', 'over']:
odds = actual_odds[0]
else:
odds = actual_odds[1]
event_date, home_team, away_team = database.get_event_info(event.event_id)
message = create_message(event_date, home_team, away_team, event.bet_type,
event.side, event.points, event.price, odds)
telegram.send_message(message)
def create_message(event_date: date, home_team: str, away_team: str, bet_type: str,
side: str, points: float, desired_price: float, odds: float) -> str:
"""
Creates notification about good odds being available.
"""
message = f'{event_date} {home_team} - {away_team} {bet_type} {side} {points}\n'
message += f'{desired_price} required, {odds} current odds. {odds - desired_price:.3f} diff.'
return message
if __name__ == '__main__':
track_odds()
</code></pre>
<p><em>database.py</em></p>
<pre><code>"""
Functionality for interacting with the database.
"""
from contextlib import contextmanager
from datetime import date
from typing import Optional, Tuple
import pymysql
SERVER = 'localhost'
USER = 'root'
PASSWORD = ''
DATABASE = 'bets'
Odds = Tuple[float, float]
TrackedEvent = Tuple[int, str, str, float, float]
TrackedEvents = Tuple[TrackedEvent]
@contextmanager
def get_connection():
"""
Creates database connection.
"""
connection = pymysql.connect(host=SERVER, user=USER, password=PASSWORD, db=DATABASE)
try:
yield connection
finally:
connection.close()
def get_latest_odds(event_id: int, bet_type: str, points: float) -> Odds:
"""
Retrieves the latest odds for the given event with bet_type and points.
"""
with get_connection() as con:
with con.cursor() as cursor:
sql = (
"SELECT left_price, right_price "
"FROM odds "
"WHERE event_id = %s "
"AND bet_type = %s AND points = %s "
"ORDER BY time_updated DESC "
"LIMIT 1"
)
cursor.execute(sql, (event_id, bet_type, points))
result = cursor.fetchone()
return result
def get_tracked_events() -> Optional[TrackedEvents]:
"""
Retrieves all the tracked events.
"""
with get_connection() as con:
with con.cursor() as cursor:
sql = (
"SELECT * "
"FROM tracked_events"
)
cursor.execute(sql)
result = cursor.fetchall()
return result
def get_event_info(event_id: int) -> Tuple[date, str, str]:
"""
Retrieves date and teams for the given event.
"""
with get_connection() as con:
with con.cursor() as cursor:
sql = (
"SELECT match_date, home_team, away_team "
"FROM fixture "
"WHERE event_id = %s"
)
cursor.execute(sql, (event_id))
result = cursor.fetchone()
return result
def delete_event(_id: int) -> None:
"""
Deletes tracked event with given id.
"""
with get_connection() as con:
with con.cursor() as cursor:
sql = (
"DELETE FROM tracked_events "
"WHERE id = %s "
)
cursor.execute(sql, (_id))
con.commit()
</code></pre>
<p><em>telegram.py</em></p>
<pre><code>from typing import Any, Dict
import requests
TELEGRAM_TOKEN = ''
TELEGRAM_ID = ''
BASE_URL = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?'
PARSE_MODE = 'Markdown'
def send_message(message: str) -> Any:
params: Dict[str, Any] = {
'chat_id': TELEGRAM_ID,
'parse_mode': PARSE_MODE,
'text': message,
}
response = requests.get(BASE_URL, params=params)
return response.json()
</code></pre>
|
[] |
[
{
"body": "<p>You are off to a good start indeed. It's evident that this code was carefully\ndone and nothing here looks unreasonable. I do have a few suggestions about\nerror handling, DRY-ing up the code, and code testing/testability.</p>\n<p><strong>HTTP requests can fail</strong>. I'm sure you know that already, but you should be\nhandle that possibility in <code>send_message()</code> with a <code>try-except</code> -- either\ndirectly in the function or at a higher level in the program.</p>\n<p><strong>You might need multiple DB environments sooner than you think</strong>.\nI don't know the larger context for you application, but\nit's not uncommon for a project to immediately (or ultimately) require the\nability to connection to databases in different environments. At a minimum, you\nmight want to write automated tests for this code and therefore will want to\nhave both a real/production DB and a test DB. All of which means that you'll\nneed different credentials and connection parameters for each environment.\nThere are many reasonable ways to address that, but a low-tech approach is to\ndefine a simple function that returns the correct bundle of connection\nparameters (as a dict, namedtuple, whatever) based on either an argument (eg,\n'test' or 'production') and/or an environment variable and/or a command-line\nargument. That's a lot of and-or possibilities, I realize, but there's no\nsingle answer here. The main point is to use your judgment and be reasonable\n(don't try to over-engineer it) as you prepare your code for the need for\ndifferent DB environments.</p>\n<p><strong>DRY up those database query functions</strong>. I did not study every detail, but\nthe DB functions look reasonable in isolation. But viewed from afar, notice the\nrepetitive pattern that is emerging. That's an indicator of a future problem:\nif your program's roster of DB queries keeps growing, you'll end up with a\nmountain of repetitive, almost-but-not-quite equal blocks of tedious code.\nHere's a rough sketch of how to DRY things up (I did not run it, so there might\nbe typos). There are other approaches that would work well, too. But the general\nidea is to get this issue on your radar screen, because this type of repetitive\nDB code can become a real headache if the project gets big.</p>\n<pre><code># This import is a tiny library I wrote. Or you can use enum.Enum for a\n# similar approach (but not quite as convenient, IMHO).\nfrom short_con import constants, cons\n\nSqlQueries = cons('SqlQueries',\n get_latest_odds = (\n 'SELECT left_price, right_price '\n 'FROM odds '\n 'WHERE event_id = %s '\n 'AND bet_type = %s AND points = %s '\n 'ORDER BY time_updated DESC '\n 'LIMIT 1'\n ),\n get_tracked_events = ('SELECT ... etc'),\n get_event_info = ('SELECT ... etc'),\n delete_event = ('DELETE FROM ... etc'),\n)\n\nQueryModes = constants('QueryModes', 'ONE ALL DELETE')\n\n# You might need to use typing.overload to set up the type checks\n# for this general-purpose function, but it is solvable.\ndef run_db_query(query_key, query_params, mode):\n sql = SQL_QUERIES[query_key]\n with get_connection() as con:\n with con.cursor() as cursor:\n cursor.execute(sql, query_params)\n if mode == QueryModes.ONE:\n return cursor.fetchone()\n elif mode == QueryModes.ALL:\n return cursor.fetchall()\n elif mode == QueryModes.DELETE:\n return con.commit()\n else:\n raise ...\n\ndef get_latest_odds(event_id: int, bet_type: str, points: float) -> Odds:\n return run_db_query(\n SqlQueries.get_latest_odds,\n (event_id, bet_type, points),\n QueryModes.ONE,\n )\n\n# Same idea for the other DB functions.\n...\n</code></pre>\n<p><strong>Consider getting out of the world of writing your own SQL</strong>. All that said,\nthere are other libraries that will reduce much of this DB code to almost\nnothing -- everything from full blown ORMs that I would not recommend to more\nlightweight options that merely simplify the mechanics of DB interactions. You\nmight want to look into those options, if you haven't done so already.</p>\n<p><strong>DB interactions can fail</strong>. Same point here: you need some exception\nhandling here. But notice how much easier this fix would be if you DRY up the\nDB code fist (<code>try-except</code> in one place rather than many).</p>\n<p><strong>Lingering magic strings</strong>. There are still some stragglers (<code>home</code>, <code>over</code>,\netc). Define those as constants.</p>\n<p><strong>Test your code and the design will usually improve</strong>. Speaking of tests, do\nyou have any? If not, get that on your project plan (I recommend\n<a href=\"https://docs.pytest.org/en/latest/\" rel=\"nofollow noreferrer\">pytest</a>\nbut there are several reasonable options). When you try to test your\ncode, you'll probably discover the need for other refactoring steps. If\nsomething is difficult to test without awkward mocking and other hoop-jumping,\nuse that pain as a signal that you program design and decomposition might need\nmore adjustments.</p>\n<p><strong>Your feature question</strong>. I don't have much to suggest, because I don't\nhave enough of the details and context. In general, any time you need to\ndo things "later" that means you'll need to persist that fact outside the program\n(in your case, probably in the DB). For example, one might have a simple table\nof <code>MutedDesiredOdds</code> holding the ID of the applicable <code>DesiredOdds</code> entry,\nsome time metadata, and perhaps other simple parameters.\nInside your <code>track_odds()</code> loop, you could also check the DB for any actions\nthat were muted but require attention now. Pretty vague suggestions, I realize,\nbut the specifics could influence the approach considerably.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T23:37:02.907",
"Id": "488665",
"Score": "0",
"body": "Thanks for the review!\n\nAs far as error handling is concerned, I'm aware of it and did that in another code I posted, please take a look https://codereview.stackexchange.com/questions/246150/a-library-for-interacting-with-pinnacle-sports-bets-api\nTalking about database query functions, your suggestions are very useful, how can I reference it in order to get acquainted with that? Also what are the lightweight options to avoid writing SQL-queries manually?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T23:39:07.503",
"Id": "488666",
"Score": "0",
"body": "I don't have any tests at the moment because this code represents a minimal working version so I would like to get some feedback before going any further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T23:41:42.427",
"Id": "488667",
"Score": "0",
"body": "**For example, one might have a simple table of `MutedDesiredOdds` holding the ID of the applicable `DesiredOdds` entry, some time metadata, and perhaps other simple parameters. ** Could you provide a small example so that I can get an idea how it looks like? The details don't matter, only the skeleton of the solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T00:49:00.677",
"Id": "488669",
"Score": "1",
"body": "@KonstantinKostanzhoglo Imagine a different system where our program must complete \"Tasks\" on some basis (daily, hourly, etc). The DB would have a `tasks` table with fields like `id`, `description`, `frequency`, etc. To support the ability to defer tasks under certain conditions, we could have a table called `deferred_tasks` with fields such as: `task_id`, `deferred_at` (timestamp when it was deferred), and maybe `n_deferrals` (how many times we've already deferred the task). Then, in the main program loop, we check not only `tasks` but also `deferred_tasks` to see what actions to take."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T00:54:00.480",
"Id": "488670",
"Score": "0",
"body": "Basically we should add a field into the data definition describing what should be done with the task after it has been executed and then check that field inside the main loop and decide what to do next based on that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T01:00:12.870",
"Id": "488671",
"Score": "1",
"body": "@KonstantinKostanzhoglo Regarding ORMs and such, there are many options and even more opinions. On my last project involving a DB I selected [sqlalchemy](https://www.sqlalchemy.org/), but only the [Core](https://www.sqlalchemy.org/features.html), not the full ORM. But don't necessary take my advice. Do some searching yourself. My anti-ORM concerns might not be as relevant in your specific situation. My project was large, complex, and long-term. On smaller projects, ORMs can work just fine – they are convenient, that's their top selling point."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T19:57:43.370",
"Id": "249324",
"ParentId": "249183",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249324",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T22:24:01.443",
"Id": "249183",
"Score": "8",
"Tags": [
"python"
],
"Title": "Betting odds tracker"
}
|
249183
|
<p>I hope that the word "decompose" is correct, but the problem is simple:
I got two lists after an operation and I want to know what change happend from one list to the other.
As such I want to "decompose" the two lists A and B into "Both", "Only A" and "Only B".</p>
<pre><code>template <class T>
void decompose(std::vector<T*> &a, std::vector<T*> &b, std::vector<T*> &only_a, std::vector<T*> &only_b, std::vector<T*> &both) {
only_a = a;
only_b = b;
for (T* x : a) {
for (T* y : b) {
if (x == y) {
both.push_back(x);
}
}
}
{
auto it = only_a.begin();
while (it != only_a.end()) {
bool erase = false;
for (T* x : both) {
if (x == *it) {
it = only_a.erase(it);
erase = true;
}
}
if (!erase) {
it++;
}
}
}
{
auto it = only_b.begin();
while(it != only_b.end()) {
bool erase = false;
for (T* x : both) {
if (x == *it) {
it = only_b.erase(it);
erase = true;
}
}
if (!erase) {
it++;
}
}
}
}
</code></pre>
<p>I feel like there should be a faster way to do this than three twice intertwined loops.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:24:36.560",
"Id": "488355",
"Score": "2",
"body": "Is the sort order in the result important? Does it matter if the result is sorted? Is the input sorted? If not, is it ok to sort it? Also, is there a reason for limiting it to pointers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:40:27.303",
"Id": "488358",
"Score": "0",
"body": "No, it was just that pointers were what I got (the existance of a == operator is what was important or else there is no \"sameness\" to have the \"both\" defined). I have the feeling like the answers are very different depending on sortedness, so I am rather interested in both cases. Right now this is just data, so maybe there isn't even a way to sort the lists anyway. As such pointers also help as there is an order on addresses.\n\nThough to be precise: In my particular case where I actually use this function I HAVE to use pointers as I decompose lists of UI Elements that are beneath a mouse."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:47:42.813",
"Id": "488360",
"Score": "1",
"body": "If you can compare them for equality you can usually sort them, but that's perhaps not that important. Are there duplicates? I'm asking all this because a possible answer could include [`std::set_difference`](https://en.cppreference.com/w/cpp/algorithm/set_difference) and [`std::set_intersection`](https://en.cppreference.com/w/cpp/algorithm/set_intersection) like in this [example](https://godbolt.org/z/aMx3a6) - but it does come with some limitations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:50:59.617",
"Id": "488361",
"Score": "0",
"body": "No duplicates should be in the tree structure these lists drop out of (they each represent the list of elements beneath a mouse cursor and usually this means that each item is part of only one branch of the ui element tree (I do not know of any ui element that can be part of two pieces of an interface at once)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T05:59:50.583",
"Id": "488389",
"Score": "1",
"body": "Welcome to CodeReview@SE. (`intertwined loops` made me think of coroutines, *nested* would seem more common.)"
}
] |
[
{
"body": "<p>For something easy to read and maintain I'd use <a href=\"https://en.cppreference.com/w/cpp/algorithm/set_difference\" rel=\"nofollow noreferrer\"><code>set_difference</code></a> and <a href=\"https://en.cppreference.com/w/cpp/algorithm/set_intersection\" rel=\"nofollow noreferrer\"><code>set_intersection</code></a> which would work well on sorted ranges with no duplicates:</p>\n<pre><code>std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(both));\n\nonly_a.reserve(a.size() - both.size());\nstd::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(only_a));\n\nonly_b.reserve(b.size() - both.size());\nstd::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::back_inserter(only_b));\n</code></pre>\n<p>...but that requires that you iterate over the ranges three times, and I think you are looking for something more efficient.</p>\n<p>First, I would not start by copying <code>a</code> and <code>b</code> into <code>only_a</code> and <code>only_b</code> respectively. Instead, take inspiration from the example implementations for the standard functions I linked to above and create your own similar algorithm. This requires that <code>T</code>s can be compared with <code>operator<</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <algorithm>\n#include <iterator>\n\ntemplate <class T>\nvoid decompose(std::vector<T>& a,\n std::vector<T>& b,\n std::vector<T>& only_a,\n std::vector<T>& only_b,\n std::vector<T>& both)\n{\n // Sort the input or require the input to be sorted like some algorithms do\n // If you'd like the input to be unchanged, make a and b const and make\n // copies of them instead and sort those copies.\n std::sort(a.begin(), a.end());\n std::sort(b.begin(), b.end());\n\n // clear destination vectors or skip this if you want to append instead\n only_a.clear();\n only_b.clear();\n\n // the actual algorithm - loop for as long as both vectors have elements\n\n auto ait = a.begin();\n auto bit = b.begin();\n\n while(ait != a.end() && bit != b.end()) {\n if(*ait < *bit) {\n only_a.push_back(*ait++); // can only be in a\n } else if(*bit < *ait) {\n only_b.push_back(*bit++); // can only be in b\n } else {\n both.push_back(*ait++); // must be in both\n ++bit;\n }\n }\n\n // Add the remaining elements if not both ait and bit have reached their end()\n if(ait != a.end()) std::copy(ait, a.end(), std::back_inserter(only_a));\n else if(bit != b.end()) std::copy(bit, b.end(), std::back_inserter(only_b));\n}\n</code></pre>\n<p>Or make it even more generic and let it work with iterators only and add the possibility for the user to supply a <a href=\"https://en.cppreference.com/w/cpp/named_req/Compare\" rel=\"nofollow noreferrer\"><em>Compare</em></a> functor. This do require the ranges to be sorted in the same order as they would be if the <em>Compare</em> functor was used with <code>std::sort</code> on the ranges. The default <em>Compare</em> functor is here <code>std::less<></code> that, if not specialized for the type involved, uses <code>operator<</code> to compare the elements.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <functional> // less\n#include <iterator> // iterator_traits\n\ntemplate <\n class First1, class Last1, class First2, class Last2,\n class OnlyAinserter, class OnlyBinserter, class BothInserter,\n class Comp = std::less<typename std::iterator_traits<First1>::value_type>\n // class Comp = std::less<> // <- is sufficient in C++14 and forward\n>\nvoid decompose(First1 ait, Last1 aend, First2 bit, Last2 bend,\n OnlyAinserter onlyait, OnlyBinserter onlybit, BothInserter bothit,\n Comp comp = Comp{})\n{\n // loop for as long as both vectors have elements\n while(ait != aend && bit != bend) {\n if(comp(*ait, *bit)) {\n *onlyait++ = *ait++; // can only be in a\n } else if(comp(*bit, *ait)) {\n *onlybit++ = *bit++; // can only be in b\n } else {\n *bothit++ = *ait++; // must be in both\n ++bit;\n }\n }\n\n // Add the remaining elements if not both ait and bit have reached aend/bend\n if(ait != aend) std::copy(ait, aend, onlyait);\n else if(bit != bend) std::copy(bit, bend, onlybit);\n}\n</code></pre>\n<p>Which can then be called like this using the default <em>Compare</em> functor:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>decompose(a.begin(), a.end(), b.begin(), b.end(), \n std::back_inserter(only_a), std::back_inserter(only_b), std::back_inserter(both));\n</code></pre>\n<p>Or like below, supplying a <em>Compare</em> functor. In this example the ranges are required to be sorted in descending order:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>decompose(a.begin(), a.end(), b.begin(), b.end(), \n std::back_inserter(only_a), std::back_inserter(only_b), std::back_inserter(both),\n [](auto& A, auto& B) { return A > B; } // std::greater<>\n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T00:28:02.720",
"Id": "249189",
"ParentId": "249186",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249189",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T23:04:24.697",
"Id": "249186",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Decompose two vectors"
}
|
249186
|
<p>I'm working on a data analytics dashboard in Node.js as a portfolio piece. I've built a pipeline that gets the data where it needs to be for more processing, however, I feel the below code can be improved but it overlaps with my inexperience with Node.js and async/await.</p>
<p>The below code looks redundant to my eye. I tried to move the second function into the first in an anonymous async function to no avail, and was wondering if the more experience members here had any suggestions?</p>
<pre><code>async function readFilteredStream() {
filteredStream = streamConnect(); //Connects to API
const results = await readStream(filteredStream); //Reads in a sample of data and closes the connection.
return { data: results };
}
async function respondWithSamples() {
const results = await readFilteredStream();
return results;
}
</code></pre>
|
[] |
[
{
"body": "<p>In ES6, when you have a variable that's going to be used as a property of an object, you can use the same variable name as the property so as to use shorthand syntax, if you want:</p>\n<pre><code>const data = await readStream(filteredStream); //Reads in a sample of data and closes the connection. \nreturn { data };\n</code></pre>\n<p>You do:</p>\n<pre><code>filteredStream = streamConnect();\n</code></pre>\n<p>You are assigning to an outer variable named <code>filteredStream</code>. Do you declare and use <code>filteredStream</code> elsewhere? If not, then this is a bug - you're either implicitly creating a property on the global object, or (if you enable strict mode), an error will be thrown. Always declare variables before using them. You might have wanted to do:</p>\n<pre><code>async function readFilteredStream() {\n const filteredStream = streamConnect(); //Connects to API\n const data = await readStream(filteredStream); //Reads in a sample of data and closes the connection. \n return { data };\n}\n</code></pre>\n<p>The <code>respondWithSamples</code> function doesn't do anything useful. It calls <code>readFilteredStream</code> and returns it. It would be easier and make more sense to just use <code>readFilteredStream</code> instead, and remove <code>respondWithSamples</code> - all you're doing is creating another wrapper around the Promise, one which will be resolved wherever the Promise is unwrapped.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T01:36:38.157",
"Id": "249191",
"ParentId": "249190",
"Score": "4"
}
},
{
"body": "<p>I would refactor the second function to simply:</p>\n<pre><code>const readFilteredStream = ()=> streamConnect().then(readStream)\n</code></pre>\n<p>Imho much more readable.</p>\n<p>There's really no point into creating an object with a single key <code>data</code>, it can be done directly on the result of the function call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:50:28.700",
"Id": "249193",
"ParentId": "249190",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249191",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T01:14:35.220",
"Id": "249190",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"async-await"
],
"Title": "Improving Async/Await Javascript Code"
}
|
249190
|
<p>This code tries to solve the sudoku board using the rules of sudoku. When it does not make progress in solving, it assumes a cell value and tries again. Please review my code and help me understand how I can make it better.</p>
<pre><code>import math
import copy
import sys
# GLOBALS
reccursion_depth = 0
dead_end_counter = 0
assumption_counter = 0
solution_counter = 0
# OPTIONS
PRINT_STEPS = False
PRINT_STEP_BOARD = False
PRINT_ASSUMPTION = False
ASSUME_LOWEST_FIRST = True
# When True, assumptions will be made on cells with smallest possible choices, else Left2Right-Top2Down.
FIRST_SOLUTION_ONLY = False
def initiate_board(problem):
board_pos = [[[i for i in range(1,10)] for i in range(9)] for i in range(9)]
for i,row in enumerate(problem):
for j,cell in enumerate(row):
if cell > 0:
board_pos[i][j] = [cell]
return board_pos
def remove_invalid(board_pos):
if PRINT_STEPS: print("Removing Invalid Values..")
org_length = board_length(board_pos) #Used to check if Rule based algorithm made progress.
for i,row in enumerate(board_pos):
for j,cell in enumerate(row):
if len(cell) == 1:
for e in range(9):
# 1. Remove from Row
if e != j:
try:
board_pos[i][e].remove(cell[0])
if len(board_pos[i][e]) == 0:
if PRINT_STEPS: print(f"ROW CHECK: Board is invalid at position ({i},{j})")
return False, False, board_pos
valid_col = False
for counter_col in range(9):
if cell[0] in board_pos[counter_col][e]:
valid_col = True
break
if not valid_col:
if PRINT_STEPS: print(f'COLUMN CHECK: Value {cell[0]} not present in column {e}! ')
return False, False, board_pos
except ValueError:
pass
# 2. Remove from Column
if e != i:
try:
board_pos[e][j].remove(cell[0])
if len(board_pos[e][j]) == 0:
if PRINT_STEPS: print(f"COLUMN CHECK: Board is invalid at position ({e},{j})")
return False, False, board_pos
valid_row = False
for counter_row in range(9):
if cell[0] in board_pos[e][counter_row]:
valid_row = True
break
if not valid_row:
if PRINT_STEPS: print(f'ROW CHECK: Value {cell[0]} not present in row {e}! ')
return False, False, board_pos
except ValueError:
pass
# 3. Remove from Sector
sector_row = math.floor((i) / 3)
sector_col = math.floor((j) / 3)
#print(sector_row, sector_col, ':',cell[0])
for i_sec in range(sector_row*3, (sector_row+1)*3):
for j_sec in range(sector_col*3, (sector_col+1)*3):
if i != i_sec and j !=j_sec:
try:
board_pos[i_sec][j_sec].remove(cell[0])
if len(board_pos[i_sec][j_sec]) == 0:
if PRINT_STEPS: print(f"SECTOR CHECK: Board is invalid at position ({i_sec},{j_sec})")
return False, False, board_pos
# Add check here to ensure every number is an option for the Sector. Missing check will eventually lead to dead end anyways.
except ValueError:
pass
return True, (org_length == board_length(board_pos)), board_pos
def board_length(board_pos):
total_length = 0
for i,row in enumerate(board_pos):
for j,cell in enumerate(row):
total_length +=len(cell)
return total_length
def print_board(board_pos):
if not isinstance(board_pos[0][0], int): print(f'####### SOLUTION NUMBER {solution_counter} #######')
for row in board_pos:
print(row)
if not isinstance(board_pos[0][0], int):
print(f"Current Board Length: {board_length(board_pos)}")
print(f"Current Reccursion Depth: {reccursion_depth}")
print(f"Current Number of Dead Ends: {dead_end_counter}")
print(f"Number of assumptions made: {assumption_counter}")
def is_solved(board_pos):
for row in board_pos:
for cell in row:
if len(cell) != 1:
return False
return True
def get_next_assume_candidate(board_pos):
assume_list = []
possibilities = 1
for i,row in enumerate(board_pos):
for j,cell in enumerate(row):
if len(cell) > 1:
assume_list.append([i,j,len(cell)])
possibilities = possibilities * len(cell)
sorted_assume = sorted(assume_list, key = lambda x: x[2])
if ASSUME_LOWEST_FIRST:
return (sorted_assume[0], possibilities)
else:
return (assume_list[0], possibilities)
def solve_sudoku(board_pos):
global reccursion_depth
global dead_end_counter
global assumption_counter
global solution_counter
reccursion_depth += 1
if PRINT_STEPS: print('reccursion depth :', reccursion_depth)
while not is_solved(board_pos):
if PRINT_STEPS: print('Trying to Solve by applying rules of Sudoku:')
if PRINT_STEP_BOARD: print_board(board_pos)
# Rule based Sudoku Solver.
is_valid, stuck, board_pos = remove_invalid(board_pos)
if not is_valid:
dead_end_counter += 1
assume_list, possibilities = get_next_assume_candidate(board_pos)
if PRINT_STEPS: print(f'Dead End Number: {dead_end_counter}!!')
if PRINT_STEPS: print_board(board_pos)
reccursion_depth -= 1
return False
# Unable to solve board with the rules of Sudoku, Need to assume a value.
if stuck:
if PRINT_STEPS: print('Unable to solve using rules of Sudoku, assuming a value:')
assume_list, possibilities = get_next_assume_candidate(board_pos)
org_board = copy.deepcopy(board_pos) # Create Snapshot of board before assuming.
for assumption in org_board[assume_list[0]][assume_list[1]]:
board_pos[assume_list[0]][assume_list[1]] = [assumption]
assumption_counter +=1
if PRINT_ASSUMPTION: print(f'Assuming {assumption} of {org_board[i_assume][j_assume]} at position ({i_assume}, {j_assume})')
solve_sudoku(board_pos)
board_pos = copy.deepcopy(org_board) #Reset board back to Original State.
reccursion_depth -= 1
return False
print('SOLVED!!!!!')
solution_counter +=1
print_board(board_pos)
if FIRST_SOLUTION_ONLY: sys.exit(0)
reccursion_depth -= 1
return True
def main():
problem1 = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
problem2 = [[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,3,0,8,5],
[0,0,1,0,2,0,0,0,0],
[0,0,0,5,0,7,0,0,0],
[0,0,4,0,0,0,1,0,0],
[0,9,0,0,0,0,0,0,0],
[5,0,0,0,0,0,0,7,3],
[0,0,2,0,1,0,0,0,0],
[0,0,0,0,4,0,0,0,9]] # Sudoku designed against brute force. Notice Line 1 of solution.
problem3 = [[1,0,0,0,6,8,0,0,9],
[0,8,4,9,0,0,0,0,0],
[0,3,0,0,4,2,0,0,0],
[0,0,0,5,0,0,0,7,0],
[7,9,0,0,3,0,4,0,0],
[0,5,0,0,0,4,9,0,0],
[0,4,0,0,0,3,0,0,0],
[0,0,6,0,0,7,0,0,4],
[0,0,2,0,8,6,0,3,0]]
problem4 = [[0,0,0,0,3,7,6,0,0],
[0,0,0,6,0,0,0,9,0],
[0,0,8,0,0,0,0,0,4],
[0,9,0,0,0,0,0,0,1],
[6,0,0,0,0,0,0,0,9],
[3,0,0,0,0,0,0,4,0],
[7,0,0,0,0,0,8,0,0],
[0,1,0,0,0,9,0,0,0],
[0,0,2,5,4,0,0,0,0]]
problem5 = [[9,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,7],
[5,0,0,0,0,3,0,0,4],
[0,0,7,0,0,0,2,0,0],
[0,0,3,6,0,8,0,0,0],
[0,0,0,4,0,0,6,1,0],
[0,8,5,0,4,0,0,0,0],
[0,0,0,3,2,0,0,6,0],
[0,4,0,0,1,0,0,9,0]]
problem6 = [[3,0,6,0,0,0,0,0,0],
[0,0,0,0,0,6,0,7,0],
[0,0,1,0,0,3,0,0,9],
[2,0,0,7,0,8,0,9,0],
[0,0,0,0,0,0,5,0,8],
[0,0,0,1,0,0,2,3,0],
[0,2,0,5,4,0,0,0,0],
[0,9,0,0,2,0,0,0,0],
[0,7,0,0,0,0,8,0,1]] #Use to understand Algorithm, with Print all steps.
problem7 = [[8,5,0,0,0,2,4,0,0],
[7,2,0,0,0,0,0,0,9],
[0,0,4,0,0,0,0,0,0],
[0,0,0,1,0,7,0,0,2],
[3,0,5,0,0,0,9,0,0],
[0,4,0,0,0,0,0,0,0],
[0,0,0,0,8,0,0,7,0],
[0,1,7,0,0,0,0,0,0],
[0,0,0,0,3,6,0,4,0]]
problem8 = [[0,0,5,3,0,0,0,0,0],
[8,0,0,0,0,0,0,2,0],
[0,7,0,0,1,0,5,0,0],
[4,0,0,0,0,5,3,0,0],
[0,1,0,0,7,0,0,0,6],
[0,0,3,2,0,0,0,8,0],
[0,6,0,5,0,0,0,0,9],
[0,0,4,0,0,0,0,3,0],
[0,0,0,0,0,9,7,0,0]]
problem9 = [[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],
[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]] # Blank Board.
problem10= [[8,0,0,0,0,0,0,0,0],
[0,0,3,6,0,0,0,0,0],
[0,7,0,0,9,0,2,0,0],
[0,5,0,0,0,7,0,0,0],
[0,0,0,0,4,5,7,0,0],
[0,0,0,1,0,0,0,3,0],
[0,0,1,0,0,0,0,6,8],
[0,0,8,5,0,0,0,1,0],
[0,9,0,0,0,0,4,0,0]]
problem11= [[8,0,0,6,0,0,9,0,5],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,2,0,3,1,0],
[0,0,7,3,1,8,0,6,0],
[2,4,0,0,0,0,0,7,3],
[0,0,0,0,0,0,0,0,0],
[0,0,2,7,9,0,1,0,0],
[5,0,0,0,8,0,0,3,6],
[0,0,3,0,0,0,0,0,0]] # Multiple Solutions
# Default starting board
#####################################################
puzzle = problem11 # Choose problem to solve here.
#####################################################
board_pos = initiate_board(puzzle)
print("Trying to Solve Board")
print_board(puzzle)
solved = solve_sudoku(board_pos)
if __name__== '__main__':
main()
</code></pre>
<p>OUTPUT</p>
<blockquote>
<pre><code>Trying to Solve Board
[8, 0, 0, 6, 0, 0, 9, 0, 5]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 2, 0, 3, 1, 0]
[0, 0, 7, 3, 1, 8, 0, 6, 0]
[2, 4, 0, 0, 0, 0, 0, 7, 3]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 2, 7, 9, 0, 1, 0, 0]
[5, 0, 0, 0, 8, 0, 0, 3, 6]
[0, 0, 3, 0, 0, 0, 0, 0, 0]
SOLVED!!!!!
####### SOLUTION NUMBER 1 #######
[[8], [1], [4], [6], [3], [7], [9], [2], [5]]
[[3], [2], [5], [1], [4], [9], [6], [8], [7]]
[[7], [9], [6], [8], [2], [5], [3], [1], [4]]
[[9], [5], [7], [3], [1], [8], [4], [6], [2]]
[[2], [4], [1], [9], [5], [6], [8], [7], [3]]
[[6], [3], [8], [2], [7], [4], [5], [9], [1]]
[[4], [6], [2], [7], [9], [3], [1], [5], [8]]
[[5], [7], [9], [4], [8], [1], [2], [3], [6]]
[[1], [8], [3], [5], [6], [2], [7], [4], [9]]
Current Board Length: 81
Current Reccursion Depth: 6
Current Number of Dead Ends: 1
Number of assumptions made: 6
SOLVED!!!!!
####### SOLUTION NUMBER 2 #######
[[8], [1], [4], [6], [3], [7], [9], [2], [5]]
[[3], [2], [5], [9], [4], [1], [6], [8], [7]]
[[7], [9], [6], [8], [2], [5], [3], [1], [4]]
[[9], [5], [7], [3], [1], [8], [4], [6], [2]]
[[2], [4], [1], [5], [6], [9], [8], [7], [3]]
[[6], [3], [8], [4], [7], [2], [5], [9], [1]]
[[4], [6], [2], [7], [9], [3], [1], [5], [8]]
[[5], [7], [9], [1], [8], [4], [2], [3], [6]]
[[1], [8], [3], [2], [5], [6], [7], [4], [9]]
Current Board Length: 81
Current Reccursion Depth: 6
Current Number of Dead Ends: 1
Number of assumptions made: 7
SOLVED!!!!!
####### SOLUTION NUMBER 3 #######
[[8], [3], [4], [6], [7], [1], [9], [2], [5]]
[[1], [2], [5], [8], [3], [9], [6], [4], [7]]
[[7], [9], [6], [4], [2], [5], [3], [1], [8]]
[[9], [5], [7], [3], [1], [8], [4], [6], [2]]
[[2], [4], [1], [9], [5], [6], [8], [7], [3]]
[[3], [6], [8], [2], [4], [7], [5], [9], [1]]
[[6], [8], [2], [7], [9], [3], [1], [5], [4]]
[[5], [7], [9], [1], [8], [4], [2], [3], [6]]
[[4], [1], [3], [5], [6], [2], [7], [8], [9]]
Current Board Length: 81
Current Reccursion Depth: 9
Current Number of Dead Ends: 8
Number of assumptions made: 23
SOLVED!!!!!
####### SOLUTION NUMBER 4 #######
[[8], [3], [4], [6], [7], [1], [9], [2], [5]]
[[1], [2], [5], [8], [3], [9], [6], [4], [7]]
[[7], [9], [6], [5], [2], [4], [3], [1], [8]]
[[9], [5], [7], [3], [1], [8], [4], [6], [2]]
[[2], [4], [1], [9], [5], [6], [8], [7], [3]]
[[3], [6], [8], [2], [4], [7], [5], [9], [1]]
[[6], [8], [2], [7], [9], [3], [1], [5], [4]]
[[5], [1], [9], [4], [8], [2], [7], [3], [6]]
[[4], [7], [3], [1], [6], [5], [2], [8], [9]]
Current Board Length: 81
Current Reccursion Depth: 10
Current Number of Dead Ends: 8
Number of assumptions made: 25
SOLVED!!!!!
####### SOLUTION NUMBER 5 #######
[[8], [3], [4], [6], [7], [1], [9], [2], [5]]
[[1], [2], [5], [8], [3], [9], [6], [4], [7]]
[[7], [9], [6], [5], [2], [4], [3], [1], [8]]
[[9], [5], [7], [3], [1], [8], [4], [6], [2]]
[[2], [4], [1], [9], [6], [5], [8], [7], [3]]
[[3], [6], [8], [2], [4], [7], [5], [9], [1]]
[[6], [8], [2], [7], [9], [3], [1], [5], [4]]
[[5], [1], [9], [4], [8], [2], [7], [3], [6]]
[[4], [7], [3], [1], [5], [6], [2], [8], [9]]
Current Board Length: 81
Current Reccursion Depth: 10
Current Number of Dead Ends: 8
Number of assumptions made: 26
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T05:53:05.507",
"Id": "488910",
"Score": "2",
"body": "the output looks weird. if my input was list of list of integers, I'd not expect the result to be yet another wrapping. https://i.stack.imgur.com/jxrPC.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:57:07.527",
"Id": "488986",
"Score": "0",
"body": "Thanks, that is a good observation. I'll fix it."
}
] |
[
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/questions/249194/sudoku-solver-using-rules-of-sudoku-and-backtracking?noredirect=1#comment488910_249194\">the comment</a>, a few more things you can work/focus/improve on:</p>\n<ol>\n<li><p>Avoid global variables like corona.</p>\n</li>\n<li><p>Since multiple functions are sharing states, or tracking changes using globals, perhaps use a class? For eg. you can have a <code>Board</code> class, consisting of attributes sectors (<span class=\"math-container\">\\$ 3 \\times 3 \\$</span> squares), rows (which iterates over 9 rows) and columns (iterator for columns).</p>\n</li>\n<li><p><code>[i for i in range(1,10)]</code> is same as <code>list(range(1, 10))</code>.</p>\n</li>\n<li><p>The following <strong><code>DEBUG</code></strong> flags(?):</p>\n<pre><code> PRINT_STEPS = False\n PRINT_STEP_BOARD = False\n PRINT_ASSUMPTION = False\n</code></pre>\n<p>can be removed to make use of python's <code>logging</code> utility. Depending on the depth of logs, you can set severity of log messages.</p>\n</li>\n<li><p>The enumeration doesn't make use of index values <code>i</code> and <code>j</code> anywhere. Remove those:</p>\n<pre><code> def board_length(board_pos):\n total_length = 0\n for row in board_pos:\n for cell in row:\n total_length += len(cell)\n return total_length\n</code></pre>\n<p>which can be further shortened to (untested):</p>\n<pre><code> def board_length(board_pos):\n return sum((sum(map(len, row)) for row in board_pos))\n</code></pre>\n</li>\n<li><p>I tried to enable debuggin, with <code>PRINT_ASSUMPTION</code> set to <code>True</code>, and the following error was raised:</p>\n<pre><code> Traceback (most recent call last):\n File ".code.tio", line 287, in <module>\n main()\n File ".code.tio", line 283, in main\n solved = solve_sudoku(board_pos)\n File ".code.tio", line 159, in solve_sudoku\n if PRINT_ASSUMPTION: print(f'Assuming {assumption} of {org_board[i_assume][j_assume]} at position ({i_assume}, {j_assume})')\n NameError: name 'i_assume' is not defined\n</code></pre>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T12:05:53.197",
"Id": "249493",
"ParentId": "249194",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T02:55:15.220",
"Id": "249194",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"sudoku",
"backtracking"
],
"Title": "Sudoku Solver using rules of Sudoku and backtracking"
}
|
249194
|
<p>I have the two following algorithms. My analysis says that both of them are <span class="math-container">\$\mathcal O(m^24^n)\$</span> i.e they are equivalent for big numbers (more than 32 bits). Is this right? Note that <code>m</code> and <code>n</code> are the bits numbers for <code>x</code> and <code>y</code></p>
<pre><code>def pow1(x, y):
if y == 0:
return 1
temp = x
while y > 1:
y -= 1
temp *= x
return temp
</code></pre>
<pre><code>def pow2(x, y):
if y == 0:
return 1
temp = pow2(x, y//2)
if y & 1: return temp * temp * x
return temp * temp
</code></pre>
<p><strong>The complexity of the first</strong></p>
<p>y-1 iterations and in each iteration, a subtraction taking <span class="math-container">\$\mathcal O (\lg (y-i))\$</span>, and a multiplication taking <span class="math-container">\$\mathcal O (im\cdot m)\$</span>, hence the total work takes</p>
<p><span class="math-container">\$T=\mathcal O(\sum\limits_{i=1}^ym^2i)=\mathcal O\left(m^2\frac{y(y+1)}2\right)=\mathcal O\left(m^24^n\right)\$</span></p>
<p><strong>Of the second</strong></p>
<p>We have <span class="math-container">\$n=\lg y\$</span> calls and for each, we have multiplications taking <span class="math-container">\$\mathcal O (2^im\cdot 2^im)\$</span>, hence the total work takes
<span class="math-container">\$ T=\mathcal O\left(\sum\limits_{i=1}^{n}\left(4^im^2\right)\right)=\mathcal O\left({4^n}{m^2}\right)\tag{for large $n$}\$</span></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T03:57:40.353",
"Id": "488382",
"Score": "0",
"body": "Big-O classification describes the change in behavior for ever larger numbers, absolute speed. The second one is typically much faster, but that has nothing to do with their big-O formula."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T04:52:28.503",
"Id": "488386",
"Score": "0",
"body": "@Aganju See update"
}
] |
[
{
"body": "<p>I think your analysis is correct if multiplication of k-digit and ℓ-digit numbers takes Θ(kℓ) time, but more efficient multiplication algorithms are known. The most efficient algorithm in wide use (implemented in <a href=\"https://en.wikipedia.org/wiki/GNU_Multiple_Precision_Arithmetic_Library\" rel=\"nofollow noreferrer\">GMP</a>) is <a href=\"https://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen_algorithm\" rel=\"nofollow noreferrer\">Schönhage-Strassen</a>, which is O(k log k log log k) for numbers of equal length. I don't know the complexity for unequal lengths, but I suspect it's O(ℓ log k log log k) for k < ℓ. Using that algorithm, or any sub-kℓ algorithm, you should find that the divide-and-conquer approach is faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T12:17:10.800",
"Id": "488416",
"Score": "0",
"body": "How do you know Schönhage-Strassen is implemented in GMP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T23:50:14.680",
"Id": "488477",
"Score": "1",
"body": "@superbrain It's mentioned in the documentation [here](https://gmplib.org/manual/FFT-Multiplication). Apparently they pad the inputs to the same length, so it's O(ℓ log ℓ log log ℓ)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T06:16:32.473",
"Id": "249199",
"ParentId": "249196",
"Score": "2"
}
},
{
"body": "<p>As benrg answered, it looks correct if multiplication of k-digit and ℓ-digit numbers takes Θ(kℓ) time. We can also somewhat verify it experimentally. Let's write a number class that keeps track of the bit operations:</p>\n<pre><code>class Int(int):\n def __mul__(self, other):\n global bitops\n bitops += self.bit_length() * other.bit_length()\n return Int(int(self) * other)\n</code></pre>\n<p>And now let's test that a bit, first increasing n by 1:</p>\n<pre><code>m n pow1 pow2 pow1 / pow2 pow1 / prev_pow1\n10 10 52272170 34951501 1.4955629516454816 None\n10 11 209388450 139788522 1.4978944408611745 4.005734791572648\n10 12 838148190 559136896 1.4990035463515539 4.002838695257546\n10 13 3353781770 2236448811 1.4996014008925151 4.001418615483737\n10 14 13417505370 8945532982 1.4999112291015417 4.0007091367784495\n</code></pre>\n<p>Here <code>pow1</code> is the number of bit operations with <code>pow1</code> and likewise for <code>pow2</code>. The <code>pow1 / pow2</code> column shows that <code>pow1</code> takes about a constant 1.5 times as many bit operations as <code>pow2</code>. And the last column shows that increasing n by 1 quadruples <code>pow1</code> as predicted by your analysis saying <span class=\"math-container\">\\$O(4^nm^2)\\$</span>.</p>\n<p>Now let's instead repeatedly double m:</p>\n<pre><code>m n pow1 pow2 pow1 / pow2 pow1 / prev_pow1\n10 10 52272170 34951501 1.4955629516454816 None\n20 10 209101200 139806021 1.495652322441821 4.000239515596923\n40 10 836404800 559224041 1.4956524374459073 4.0\n80 10 3345619200 2236896081 1.4956524929420716 4.0\n160 10 13382476800 8947584161 1.4956525201886839 4.0\n</code></pre>\n<p>We see that <code>pow1</code> and <code>pow2</code> again differ only by constant factor 1.5 and that doubling m quadruples the bit operations as expected from <span class=\"math-container\">\\$O(4^nm^2)\\$</span>.</p>\n<p>Whole code:</p>\n<pre><code>class Int(int):\n def __mul__(self, other):\n global bitops\n bitops += self.bit_length() * other.bit_length()\n return Int(int(self) * other)\n\ndef pow1(x, y):\n if y == 0:\n return Int(1)\n temp = x\n while y > 1:\n y -= 1\n temp *= x\n return temp\n\ndef pow2(x, y):\n if y == 0:\n return Int(1)\n temp = pow2(x, y//2)\n if y & 1: return temp * temp * x\n return temp * temp\n\nm = 10\nn = 10\nprev_bitops1 = None\nfor _ in range(5):\n x = Int(2**m - 1)\n y = 2**n - 1\n bitops = 0; pow1(x, y); bitops1 = bitops\n bitops = 0; pow2(x, y); bitops2 = bitops\n print(m, n,\n bitops1, bitops2,\n bitops1 / bitops2,\n prev_bitops1 and bitops1 / prev_bitops1)\n prev_bitops1 = bitops1\n # n += 1\n m *= 2\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T12:48:12.757",
"Id": "249214",
"ParentId": "249196",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249199",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T03:44:01.243",
"Id": "249196",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"comparative-review"
],
"Title": "Is the following divide and conquer recursive algorithm for the exponentiation more efficient than the iterative one for large numbers?"
}
|
249196
|
<p>I solve projecteuler.net Problem 2 deferent way</p>
<ol>
<li>Generate number from 1 to range ex 100 and get the even number</li>
<li>Get Fibonacci numbers from list</li>
<li>Reduce array</li>
</ol>
<p>I have one problem with a large set of numbers like 1000000 or 4000000.
can I ask how can I optimize the code? I am trying to solve the problem as a collection pipeline</p>
<p>swift code</p>
<pre><code>var evenArray = ((0..<100).filter({$0 % 2 == 0}))
print(evenArray)
var evenFibArray = evenArray.filter {(isPerfectSquare(5 * $0 * $0 + 4) || isPerfectSquare(5 * $0 * $0 - 4))}
print(evenFibArray)
var result = evenFibArray.reduce(into: 0){$0 += $1}
print(result)
func isPerfectSquare(_ x:Int ) -> Bool {
let i = Int(sqrt(Double(x)))
return (i * i == x)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:13:11.607",
"Id": "488392",
"Score": "1",
"body": "Is there really a problem with large numbers? Your code runs in less than 50 milliseconds for an upper bound of 4,000,000. Did you compile the code in “Release” mode so that it is optimized? – I am not saying that it cannot be improved and optimized further, but just want to be sure of your expectations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:21:57.687",
"Id": "488394",
"Score": "0",
"body": "I use playground"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:24:03.203",
"Id": "488396",
"Score": "0",
"body": "Should I use the lazy property to improve the computing ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:26:18.513",
"Id": "488398",
"Score": "0",
"body": "A Playground is suitable for interactive programming, but horribly slow. The code is not optimized, and values are displayed in the side bar for each computation step. If you care for performance, use a “real” Xcode Command Line Tool project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:32:43.820",
"Id": "488400",
"Score": "0",
"body": "I did not realize how bad the playground"
}
] |
[
{
"body": "<h1>General remarks</h1>\n<ul>\n<li>Your code is readable; it works and does use the collection pipeline pattern. This pattern makes your code easily maintainable and debuggable;</li>\n<li>Apart from the name chosen for the square root <code>i</code>, the naming was done correctly. After all, it's a small code snippet;</li>\n<li>You could have used fewer parentheses;</li>\n<li>You could have taken advantage of the trailing closure syntax after <code>reduce</code>;</li>\n<li>Your code would look a bit nicer if the use of spaces before or after special characters (e.g: <code>{</code>, <code>)</code>, <code>:</code>, <code>+</code> or <code>-</code>) was more consistent.</li>\n</ul>\n<h1>Lucky escape</h1>\n<p>Your <code>isPerfectSquare</code> function should only accept non-negative numbers (natural numbers):</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func isPerfectSquare(_ n: Int) -> Bool {\n guard n >= 0 else {\n return false\n }\n let root = Int(sqrt(Double(n)))\n return root * root == n\n}\n</code></pre>\n<p>You are lucky Swift uses short-circuit evaluation of juxtaposed conditions. In the expression of <code>evenFibArray</code> the first element that's passed to <code>filter</code> is <code>0</code>. So in this instance, <code>$0</code> is <code>0</code>. If <code>isPerfectSquare(5 * $0 * $0 - 4)</code> were to be evaluated, then you'd have got a <code>Fatal error</code> since the square root of a negative number in swift is not a number (<code>-nan</code>).</p>\n<p>Luckily, the former condition <code>isPerfectSquare(5 * $0 * $0 + 4)</code> with <code>$0 = 0</code> is <code>true</code>, and so, there is no need to evaluate the latter.</p>\n<h1>Conciseness</h1>\n<p>We don't really need the collection pipeline pattern since the initial numbers won't be transformed until the <code>reduce</code>. With the above remarks taken into consideration, here is what your code would look like:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let result = (0..<100)\n .filter { $0 % 2 == 0 }\n .filter { isPerfectSquare(5 * $0 * $0 + 4) || isPerfectSquare(5 * $0 * $0 - 4) }\n .reduce(0, +)\n</code></pre>\n<p>You could make it more concise: avoiding the first <code>filter</code> by using a stride instead:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let result = stride(from: 0, to: 100, by: 2)\n .filter { isPerfectSquare(5 * $0 * $0 + 4) || isPerfectSquare(5 * $0 * $0 - 4) }\n .reduce(0, +)\n</code></pre>\n<p>Or, if you like to use one <code>reduce</code> only, your code will become:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let result = stride(from: 2, to: 100, by: 2)\n .reduce(into: 0) { total, element in\n if isFibonacci(element) { total += element }\n }\n\nfunc isFibonacci(_ n: Int) -> Bool {\n let square = n * n\n return isPerfectSquare(5 * square + 4) || isPerfectSquare(5 * square - 4)\n}\n\nfunc isPerfectSquare(_ n: Int) -> Bool {\n guard n >= 0 else { return false }\n let root = Int(sqrt(Double(n)))\n return root * root == n\n}\n</code></pre>\n<p>There are <a href=\"https://www.baeldung.com/java-find-if-square-root-is-integer\" rel=\"nofollow noreferrer\">other ways to test whether an integer is a perfect square</a>.</p>\n<h1>Performance</h1>\n<p>Like you said, in your original code, you could avoid creating intermediate arrays in the pipeline by using the <code>lazy</code> keyword. The worst part about the original code is that you have to check for every number if it's even, and then check if it's a Fibonacci number. And there <a href=\"https://miniwebtool.com/list-of-fibonacci-numbers/?number=100\" rel=\"nofollow noreferrer\">not so many Fibonacci numbers up to 4,000,000</a>.</p>\n<p>You could notice that in the Fibonacci series, every third element, is even:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>fib(0)</th>\n<th>fib(1)</th>\n<th>fib(2)</th>\n<th>fib(3)</th>\n<th>fib(4)</th>\n<th>fib(5)</th>\n<th>fib(6)</th>\n<th>fib(7)</th>\n<th>...</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>0</strong></td>\n<td>1</td>\n<td>1</td>\n<td><strong>2</strong></td>\n<td>3</td>\n<td>5</td>\n<td><strong>8</strong></td>\n<td>13</td>\n<td>...</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Now, all we have to do is sum every third element in the Fibonacci series as long as it is less than the given limit (in your case 4,000,000). We could get the <a href=\"https://brilliant.org/wiki/fast-fibonacci-transform/\" rel=\"nofollow noreferrer\">Fibonacci numbers using recursion, or Dynamic Programming, or Matrix Exponentiation</a>, or more simply using <a href=\"https://brilliant.org/wiki/fibonacci-series/\" rel=\"nofollow noreferrer\">the formula</a>:</p>\n<p><span class=\"math-container\">$$Fib[n] = \\frac{A - B}{\\sqrt{5}}$$</span></p>\n<p>with:</p>\n<p><span class=\"math-container\">$$A = (\\frac{1 + \\sqrt{5}}{2})^{n}$$</span>\n<span class=\"math-container\">$$B = (\\frac{1 - \\sqrt{5}}{2})^{n}$$</span></p>\n<p>Here is code for the new approach:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let sqrt5 = sqrt(5)\nvar sum = 0\n\nstride(from: 3, through: 4_000_000, by: 3)\n .drop { n in\n let fn = fib(n)\n if fn <= 4_000_000 {\n sum += fn\n return true\n }\n return false\n }\n\nfunc fib(_ n: Int) -> Int {\n let numerator = pow((1 + sqrt5)/2, Double(n)) - pow((1.0 - sqrt5)/2.0, Double(n))\n return Int(numerator/sqrt5)\n}\n\nprint(sum) //4613732\n</code></pre>\n<p><a href=\"https://developer.apple.com/documentation/swift/sequence/3128801-drop\" rel=\"nofollow noreferrer\"><code>drop(while:)</code></a> makes sure we stop once the Fibonacci number exceeds 4,000,000.</p>\n<p>Let's calculate a better end for the <code>stride</code>:<br />\nSince <strong>B</strong> is negligible, we could approximate the upper limit to which we should be calculating Fibonacci numbers:</p>\n<p><span class=\"math-container\">$$Fib[n_{max}] \\simeq \\frac{(\\frac{1 + \\sqrt{5}}{2})^{n_{max}}}{\\sqrt{5}} \\leqslant 4\\cdot10^{6}$$</span>\n<span class=\"math-container\">$$\\Rightarrow (\\frac{1 + \\sqrt{5}}{2})^{n_{max}} \\leqslant 4\\cdot\\sqrt{5}\\cdot10^{6}$$</span>\n<span class=\"math-container\">$$\\Rightarrow n_{max}\\cdot\\ln(\\frac{1 + \\sqrt{5}}{2}) \\leqslant \\ln(4\\cdot\\sqrt{5}\\cdot10^{6})$$</span>\n<span class=\"math-container\">$$\\Rightarrow n_{max} \\leqslant \\frac{\\ln(4\\cdot\\sqrt{5}\\cdot10^{6})}{\\ln(\\frac{1 + \\sqrt{5}}{2})}$$</span>\n<span class=\"math-container\">$$\\Rightarrow n_{max} \\leqslant 33.26$$</span>\n<span class=\"math-container\">$$\\Rightarrow n_{max} = 33$$</span></p>\n<p>Lucky for us, 33 is a multiple of 3!</p>\n<p>Finally, here is the solution to the problem using the collection pipeline pattern:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let sqrt5 = sqrt(5)\n\nfunc fib(_ n: Int) -> Int {\n let numerator = pow((1 + sqrt5)/2, Double(n)) - pow((1.0 - sqrt5)/2.0, Double(n))\n return Int(numerator/sqrt5)\n}\n\nlet result = stride(from: 3, through: 33, by: 3)\n .lazy\n .map(fib)\n .reduce(0, +)\n\nprint(result) //4613732\n</code></pre>\n<h1>One more thing </h1>\n<p>There has to be a better way, and indeed, there is <a href=\"https://blog.dreamshire.com/solutions/project_euler/project-euler-problem-002-solution/\" rel=\"nofollow noreferrer\">an elegant solution to this problem</a>. Enjoy!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-20T17:11:55.010",
"Id": "269202",
"ParentId": "249197",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "269202",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T04:55:57.600",
"Id": "249197",
"Score": "2",
"Tags": [
"algorithm",
"functional-programming",
"swift"
],
"Title": "Projecteuler.net Problem 2 using collection pipeline Pattern"
}
|
249197
|
<p>For continuity, my last question was with adding numbers together with a function call: <a href="https://codereview.stackexchange.com/questions/248680/example-x86-64-program/248705#248705">Example x86-64 program</a>. In this one I've tried to apply the lessons pointed out in the previous answer (stack alignment, using <code>edx</code> instead of <code>rdx</code> where the results will fit). I've tried to comment inline with the code:</p>
<pre><code># We are going to calculate 7^2 + 2^4 = 49 + 16 = 65
# The exponent function supports whole numbers (long) >= 0
.section .data
base_1: .long 7
exp_1: .long 2
base_2: .long 2
exp_2: .long 4
.section .text
.globl _start
_start:
# We will do the first function call, 7^2
mov base_1(%rip), %edi
mov exp_1(%rip), %esi
call exp
# needs to be 16-byte aligned before the next function call so do two pushes
pushq $0
pushq %rax
# Now do the second function call
mov base_2(%rip), %edi
mov exp_2(%rip), %esi
call exp
# We have the return value in %eax so let's add this with our previous function's value
popq %rdi
add %eax, %edi
mov $60, %eax
syscall
exp:
# Initialize %eax to 1
mov $1, %eax
exp_op:
cmp $0, %esi
je exp_ret
imul %edi, %eax
dec %esi
jmp exp_op
exp_ret:
ret
</code></pre>
<p>I have a few specific questions about the code:</p>
<ul>
<li>Is doing a raw <code>push</code>/<code>pop</code> common? Or is the convention always to do <code>push rbp</code> <code>mov rsp rbp</code>...<code>pop rbp</code>. Why is one method preferred over the other?</li>
<li>What if I wanted to store the result of the first calculation in a register: are there any registers that are guaranteed to be preserved between function calls? Or is this why the <code>push...pop</code> method is used so much?</li>
<li>Finally, does my <code>exp</code> seem ok? It feels a bit odd having three labels in what amounts to one function. How could that be improved?</li>
</ul>
|
[] |
[
{
"body": "<p>I'm no expert, but what the heck, here's a review comment:</p>\n<pre><code># needs to be 16-byte aligned before the next function call so do two pushes\npushq $0\npushq %rax\n</code></pre>\n<p>This comment is good, but I would rephrase it. Two eight-byte pushes makes 16 bytes and doesn't change the stack alignment. Therefore I infer that <em>one</em> of these pushes is <em>significant</em> and the other one is <em>insignificant</em> — but your comment doesn't tell me which is which! So you might say instead</p>\n<pre><code># one extra push to preserve 16-byte stack alignment\npushq $0\n\n# push the result of `exp`\npushq %rax\n</code></pre>\n<p>You could make the generated code smaller by eliminating the insignificant constant <code>$0</code>:</p>\n<pre><code># push the result of `exp`, plus one extra push to preserve 16-byte stack alignment\npushq %rax\npushq %rax\n</code></pre>\n<p>Now the reader doesn't even need to figure out which push is the significant one, because both pushes do the same thing!</p>\n<hr />\n<p>But why is preserving 16-byte alignment on calls important? That's not a requirement of the <em>machine</em>. You seem to be trying to follow some specific <em>ABI</em>, like maybe for interoperability with C or C++. Your external documentation should be clearer about what ABI you're trying to follow.</p>\n<p>And then, if you <em>are</em> trying to interoperate with C code, you could improve your code by indicating which of its labels are meant as external entrypoints and which ones are just internal local labels. It seems like you intend <code>exp</code> to be called from other code — it's an entrypoint — but e.g. <code>exp_op</code> is not callable, and <code>exp_ret</code> is technically callable but just acts as a no-op. You might mark them somehow as "local implementation details, not for external consumption."</p>\n<p>Yeah, you technically already do this by exporting <code>.globl _start</code> and not <code>.globl exp</code> — but there's still a big difference between the callable function <code>exp</code> and the local label <code>exp_op</code> which is not reflected in your naming scheme. If I were doing this, I'd add <code>.globl exp</code> and I'd rename <code>exp_op, exp_ret</code> to something like <code>Lexp1, Lexp2</code> or <code>L1_looptop, L2_loopend</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T13:45:08.813",
"Id": "249216",
"ParentId": "249198",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249216",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T05:23:53.840",
"Id": "249198",
"Score": "2",
"Tags": [
"assembly",
"x86"
],
"Title": "x86 program to do an exponent"
}
|
249198
|
<p>Id like feedback on my code. Specifically the parts where i use graphemes. I use cloned strings because the grapheme functions eat my strings. But feel free to comment about anything else that looks like it could be improved.</p>
<p><a href="https://github.com/MonkeyToiletLadder/Hangman" rel="nofollow noreferrer">https://github.com/MonkeyToiletLadder/Hangman</a></p>
<p>Dictionary</p>
<pre><code>pub mod prelude {
use std::io::prelude::*;
use std::fs::File;
use rand::prelude::*;
pub struct Dictionary {
pub data: Vec<String>,
}
impl Dictionary {
pub fn load(&mut self, filename: &str) -> std::io::Result<()> {
if self.data.len() > 0 {
self.data.clear()
}
let mut file = File::open(filename)?;
let mut string = String::new();
file.read_to_string(&mut string)?;
let split = string.split("\n");
let vector: Vec<&str> = split.collect();
//Only add if the first line is not empty string
if vector[0] != "" {
for item in vector {
self.data.push(item.to_string());
}
}
Ok(())
}
pub fn get_random_word(&self) -> String {
let mut rng = rand::thread_rng();
let index = rng.gen_range(0,self.data.len());
self.data.get(index).unwrap().to_string()
}
pub fn new() -> Dictionary {
Dictionary { data: vec![] }
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
}
}
</code></pre>
<p>Main</p>
<pre><code>use std::io;
//TODO: Make a drawing guessing game!
mod dictionary;
use dictionary::prelude::*;
use unicode_segmentation::UnicodeSegmentation as US;
const ENGLISH_DIR: &str = "res/dictionaries/english/";
const JAPANESE_DIR: &str = "res/dictionaries/japanese/";
const SPANISH_DIR: &str = "res/dictionaries/spanish/";
const FRENCH_DIR: &str = "res/dictionaries/french/";
#[derive(PartialEq)]
enum GameState {
Running,
Stopped,
}
fn main() {
let dictionary = match std::env::args().nth(1) {
Some(arg) => arg,
None => "default.txt".to_string(),
};
let language = match std::env::args().nth(2) {
Some(arg) => arg,
None => "english".to_string(),
};
let directory = match language.as_str() {
"english" => ENGLISH_DIR.to_string(),
"japanese" => JAPANESE_DIR.to_string(),
"spanish" => SPANISH_DIR.to_string(),
"french" => FRENCH_DIR.to_string(),
_ => {
//Interpret language as a directory!
language
}
};
let mut d = Dictionary::new();
d.load(&format!("{}{}", directory, dictionary))
.expect("Could not find file!");
if d.is_empty() {
panic!("File {} is empty!", dictionary);
}
let mut word_to_guess = d.get_random_word();
let mut guess = String::new();
//Fill the guess with underscores to start.
{
let __word_to_guess = word_to_guess.clone();
let graphemes =
US::graphemes(__word_to_guess.as_str(), true)
.collect::<Vec<&str>>();
for _ in &graphemes {
guess.push('_');
}
}
println!("Enter \"quit\" to exit the progam.");
let mut guesses = 12;
let mut state = GameState::Running;
while state != GameState::Stopped {
println!("{}", guess);
println!("Enter a character to guess. Guesses left {}.", guesses);
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("Failed to read input!");
input = input.trim().to_string();
if input.len() > 1 {
match input.as_str() {
"quit" => state = GameState::Stopped,
_ => continue,
}
}
//Converting a string into graphemes takes ownership of the string.
//So to circumvent this I cloned the strings into seperate variables.
//Im not sure if this is going againt rust guidlines at what is best,
//but it works.
//This blocks only purpose is to mark the code as questionable, nothing else.
{
let __word_to_guess = word_to_guess.clone();
let __guess = guess.clone();
let mut graphemes_i =
US::graphemes(__word_to_guess.as_str(), true)
.collect::<Vec<&str>>();
let mut graphemes_j =
US::graphemes(__guess.as_str(), true)
.collect::<Vec<&str>>();
let mut index = graphemes_i.iter().position(|&x| x == input);
if index.is_none() {
guesses -= 1;
}
while let Some(i) = index {
graphemes_j[i] = &input;
graphemes_i[i] = "_";
index = graphemes_i.iter().position(|&x| x == input);
}
guess.clear();
for string in &graphemes_j {
guess.push_str(*string);
}
}
if guesses <= 0 {
println!("The word was {}.", word_to_guess);
state = GameState::Stopped;
}
if guess == word_to_guess {
println!("You guessed the word!");
state = GameState::Stopped;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T08:10:34.013",
"Id": "488403",
"Score": "0",
"body": "Most hangman games assume input is only `[A-Z]`. In languages with accents, it would be pretty difficult if you treated accented letters as different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T08:14:23.097",
"Id": "488404",
"Score": "0",
"body": "So i should just drop the graphemes entirely?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T11:29:54.360",
"Id": "488414",
"Score": "0",
"body": "@dylan that depends on what you are trying to get out of this. I'm assuming this is a learning exercise, so you might want to explore that even though it wouldn't necessarily be how you'd do it it if you were making a commercial product!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T05:04:44.590",
"Id": "488803",
"Score": "0",
"body": "The grapheme function doesn't take ownership of your strings, so the cloning is unnecessary. Perhaps it might help to show us the code that didn't work that you solved by introducing the cloned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T09:43:45.057",
"Id": "490387",
"Score": "0",
"body": "FYI: I updated my answer with some more comments about `main.rs`."
}
] |
[
{
"body": "<h1>Program design</h1>\n<h2>Handling of grapheme clusters</h2>\n<p>The program operates on Unicode grapheme clusters, presumably to\nhandle different languages.</p>\n<p>However, Hangman only really works on languages with an alphabet small\nenough. Japanese, as a counterexample, is written with a wide range\nof individual characters — around 50 <em>hiragana</em>, 50 <em>katakana</em>,\n2,136 commonly used <em>kanji</em>, and at least thousands more of uncommon\nones. Languages that require grapheme clusters probably have an even\nlarger alphabet.</p>\n<p>Therefore, I suggest dropping support for grapheme clusters, and\noperate on characters instead, to simplify the code.</p>\n<h2>Dictionary interface</h2>\n<p>It is easier to let the user enter the path to the dictionary file\ndirectly, defaulting to, say, <code>./resource/default_dictionary</code>. This\nsimplifies the argument handling.</p>\n<hr />\n<h1>Code</h1>\n<h2>Formatting</h2>\n<p><code>cargo fmt</code> automatically formats your code according to the standard\nRust style. I would also suggest adding blank lines between items.</p>\n<h2><code>cargo clippy</code></h2>\n<p>Running <code>clippy</code> shows several self-explanatory warnings:</p>\n<pre><code>warning: variable does not need to be mutable\n --> src\\main.rs:48:9\n |\n48 | let mut word_to_guess = d.get_random_word();\n | ----^^^^^^^^^^^^^\n | |\n | help: remove this `mut`\n |\n = note: `#[warn(unused_mut)]` on by default\n\nwarning: length comparison to zero\n --> src\\dictionary.rs:11:16\n |\n11 | if self.data.len() > 0 {\n | ^^^^^^^^^^^^^^^^^^^ help: using `!is_empty` is clearer and more explicit: `!self.data.is_empty()`\n |\n = note: `#[warn(clippy::len_zero)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#len_zero\n\nwarning: single-character string constant used as pattern\n --> src\\dictionary.rs:17:38\n |\n17 | let split = string.split("\\n");\n | ^^^^ help: try using a `char` instead: `'\\n'`\n |\n = note: `#[warn(clippy::single_char_pattern)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_char_pattern\n\nwarning: crate `HangMan2` should have a snake case name\n |\n = note: `#[warn(non_snake_case)]` on by default\n = help: convert the identifier to snake case: `hang_man2`\n\nwarning: 4 warnings emitted\n</code></pre>\n<h2>Naming</h2>\n<p>Names starting with underscores are conventionally reserved for\nintentionally unused variables, as the compiler does not warn about\nthem. Using such names for normal variables hides potential bugs that\ncan be found by the compiler.</p>\n<p>Note that Rust allows you to reuse names via shadowing:</p>\n<pre><code>let word_to_guess = word_to_guess.clone();\n</code></pre>\n<p>This is useful when the new variable cannot be meaningfully given a\ndistinct name.</p>\n<p><code>graphemes_i</code> and <code>graphemes_j</code> can be named better.</p>\n<h2><code>dictionary::prelude</code></h2>\n<p>There is no point in wrapping the entirety of a module in a\n<code>prelude</code>. Simply remove it and use</p>\n<pre><code>use dictionary::Dictionary;\n</code></pre>\n<p>in <code>main.rs</code>.</p>\n<h2>Error handling</h2>\n<p>I suggest using the <a href=\"https://docs.rs/anyhow/1.0\" rel=\"nofollow noreferrer\"><code>anyhow</code></a> crate to construct nice stack traces\nand remove the error handling boilerplate. Just add</p>\n<pre><code>anyhow = "1.0"\n</code></pre>\n<p>to <code>Cargo.toml</code>.</p>\n<h2><code>Dictionary</code></h2>\n<p><code>data</code> needn't be public.</p>\n<p>Instead of first constructing an empty dictionary and then load a file\ninto it, it is more idiomatic to directly construct one:</p>\n<pre><code>pub fn new<P: AsRef<Path>>(filename: P) -> Result<Self> {\n let mut file = BufReader::new(File::open(filename)?);\n\n Ok(Dictionary {\n data: file.lines().collect::<Result<_, _>>()?,\n })\n}\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li><p>paths are generally passed as an <code>impl AsRef<Path></code> by value;</p>\n</li>\n<li><p><a href=\"https://doc.rust-lang.org/std/io/trait.BufRead.html#method.lines\" rel=\"nofollow noreferrer\"><code>std::io::BufRead::lines</code></a> is probably what you are looking for.</p>\n</li>\n</ul>\n<p>Don't reimplement <a href=\"https://docs.rs/rand/0.7.3/rand/seq/trait.SliceRandom.html#tymethod.choose\" rel=\"nofollow noreferrer\"><code>rand::SliceRandom::choose</code></a>:</p>\n<pre><code>pub fn get_random_word(&self) -> Result<&str> {\n self.data\n .choose(&mut rand::thread_rng())\n .map(|word| word.as_str())\n .ok_or_else(|| anyhow!("empty dictionary"))\n}\n</code></pre>\n<h2><code>derive</code> traits</h2>\n<p>For simple <code>enum</code>s like <code>GameState</code>, many useful traits can be\nautomatically implemented using <code>derive</code>:</p>\n<pre><code>#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\nenum GameState {\n Running,\n Stopped,\n}\n</code></pre>\n<h2><code>unwrap_or_else</code></h2>\n<p>This pattern:</p>\n<pre><code>let dictionary = match std::env::args().nth(1) {\n Some(arg) => arg,\n None => "default.txt".to_string(),\n};\n</code></pre>\n<p>can be simplified by using <a href=\"https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or_else\" rel=\"nofollow noreferrer\"><code>Option::unwrap_or_else</code></a>:</p>\n<pre><code>let dictionary = std::env::args()\n .nth(1)\n .unwrap_or_else(|| "default.txt".to_owned());\n</code></pre>\n<h2><code>GameState</code></h2>\n<p>You do not really need <code>GameState</code> here — simply <code>break</code> out of\nthe <code>while</code> loop.</p>\n<h2><code>retain</code></h2>\n<p>This part:</p>\n<pre><code>let mut index = graphemes_i.iter().position(|&x| x == input);\n\nif index.is_none() {\n guesses -= 1;\n}\n\nwhile let Some(i) = index {\n graphemes_j[i] = &input;\n graphemes_i[i] = "_";\n index = graphemes_i.iter().position(|&x| x == input);\n}\n</code></pre>\n<p>can be simplified by first using <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain\" rel=\"nofollow noreferrer\"><code>Vec::retain</code></a> and then checking\nthe length.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:09:39.943",
"Id": "249885",
"ParentId": "249202",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249885",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T07:01:52.627",
"Id": "249202",
"Score": "4",
"Tags": [
"game",
"rust"
],
"Title": "Would anyone like to view my command line hangman game?"
}
|
249202
|
<p>I am working on a text normalizer. It works just fine with small text files but takes a very long time with large text files such as 5 MB or more.</p>
<p>Is there anything to change in the code to make it run faster on large text files? My guess would be something in the <code>__preprocess(tmp)</code> and <code>__prenormalise(text)</code>?</p>
<pre><code># -*- coding: utf-8 -*-
import re
import sys
import json
import os
import codecs
import copy
from num2words import num2words
from text_unidecode import unidecode
import argparse
class TextNormaliser:
def __init__(self, debug=False):
"""
Args:
debug (bool, optional): Debug mode
"""
self.debug = debug
self.abbreviations = {}
self.acronyms = {}
self.currencies = {}
self.months = [
'january', 'february', 'march', 'april', 'may', 'june', 'july',
'august', 'september', 'october', 'november', 'december']
self.number_scale = [
'thousand', 'thousands', 'million', 'millions',
'billion', 'billions', 'trillion', 'trillions']
path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(path, 'resources', 'abbreviations.json')) as jf:
self.abbreviations = json.load(jf)
with open(os.path.join(path, 'resources', 'acronyms.json')) as jf:
self.acronyms = json.load(jf)
with open(os.path.join(path, 'resources', 'currencies.json')) as jf:
self.currencies = json.load(jf)
with open(os.path.join(path, 'resources', 'domains.json')) as jf:
self.domains = json.load(jf)
def normalise(self, text):
"""Normalise text.
The function covers numbers, email addresses, ascii characters, etc.
Args:
text (str): Input string
Returns:
textn (srt): Normalised text
tokens ([tuples]): List of tuples to track back normalisation
Examples:
>>> textn, tokens = tn.normalise("My email is, a@b.com.")
tokens: (Original, Normalised, Display)
my email is a at b dot com
[('My', ['my'], 'My'), ('email', ['email'], 'email'),
('is,', ['is'], 'is'),
('a@b.com.', ['a', 'at', 'b', 'dot', 'com'], 'a@b.com')]
"""
return self.__normalise(text)
def normalise_file(self, path):
"""Normalise text from a file.
The function covers numbers, email addresses, ascii characters, etc.
Args:
path (str): Path to a file
Returns:
textn (srt): Normalised text, or None if file does not exists
tokens ([tuples]): List of tuples to track back normalisation,
or None if file doesnot exists
Raises:
Exception: If file cannot be read
Examples:
>>> textn = tn.normalise_file('./trans.txt')
"""
try:
if os.path.isfile(path):
with codecs.open(path, encoding='utf-8') as f:
return self.__normalise(f.readline())
else:
return None, None
except Exception as e:
raise Exception('ERR Normalise_file: {}'.format(e))
def __normalise(self, text):
text = self.__prenormalise(text)
tmp = []
for idx, t in enumerate(text.split()):
tmp.append((t, idx))
original = copy.deepcopy(tmp)
# Preprocessing
tokens = self.__preprocess(tmp)
# Convert to result format
ret_text, ret_tokens = self.__generate_results(original, tokens)
return ret_text, ret_tokens
def __prenormalise(self, text):
text = text.replace('\n', '').replace('\r', '')
text = re.sub(r'\b\?\b', ' ', text)
text = re.sub(r'\b\!\b', ' ', text)
text = re.sub(r'\b\"\b', ' ', text)
text = re.sub(r'\b\--\b', ' ', text)
chars = list(text)
for i, c in enumerate(chars):
if i < 1 or i > len(chars)-1:
continue
if c == ',':
if not(chars[i-1].isnumeric() and
chars[i-1].isnumeric()):
chars[i] = ', '
text = ''.join(chars)
return text
def __preprocess(self, tokens):
# Remove spaces and some special encoding
for idx, t in enumerate(tokens):
i = t[1]
t = t[0]
t = t.replace('&amp;', '&')
hints = ['[Music]', '[Laughter]', '[Applause]']
for hint in hints:
t = t.replace(hint, '')
del tokens[idx]
tokens.insert(idx, (t.strip(), i))
# Remove last dot
if len(tokens):
if tokens[-1][0].endswith('.'):
i = tokens[-1][1]
t = tokens[-1][0]
del tokens[-1]
tokens.append((t[:-1], i))
return tokens
def __rstrip(self, token):
for i in range(5):
if len(token):
if token[-1] in [',', '.', ';', '!', '?', ':', '"']:
token = token[:-1]
else:
break
return token
def __lstrip(self, token):
for i in range(5):
if len(token):
if token[0] in [',', '.', ';', '!', '?', ':', '"', '\'']:
token = token[1:]
else:
break
return token
def __generate_results(self, original, normalised):
words = []
for t in normalised:
if len(t[0]):
words.append(t[0])
text = ' '.join(words)
tokens = []
if len(original):
for t in original:
idx = t[1]
words = []
for t2 in normalised:
if idx == t2[1]:
words.append(t2[0])
display_text = self.__rstrip(t[0])
display_text = self.__lstrip(display_text)
tokens.append((t[0], words, display_text))
else:
tokens.append(('', '', ''))
return text, tokens
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--textfile', type=str, required=True, help='input directory or file')
args = parser.parse_args()
tn = TextNormaliser(False)
with open(args.textfile) as fd:
lines = fd.readlines()
for line in lines:
line = line.strip()
normalised, tokens = tn.normalise(line)
print(normalised)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T16:12:36.563",
"Id": "488435",
"Score": "1",
"body": "To reinforce a suggestion you've already received, when your code is too slow, don't waste a lot of time deeply studying code to determine what needs optimization. Instead, just measure it -- for example, with `timeit`. It will usually save you a lot of effort, because you'll focus more quickly on the trouble spots. Of course, sometimes once you find the trouble, you'll realize there's no way to fix it without a bigger rewrite of your strategy and code -- but that's only a potential concern, after you have some hard evidence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:36:49.997",
"Id": "489105",
"Score": "1",
"body": "Please do not change the code in your question after receiving answers. Doing so goes against the Question + Answer style of Code Review. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>I'd suggest to do some profiling, or simply using <code>timeit</code> for measuring which part of code takes the long time, and then focus on that:</p>\n<pre><code>from timeit import default_timer as timer\n\nstart = timer()\ntext = self.__prenormalise(text) # for example\nend = timer()\nprint('__prenormalise took', end - start) # time in seconds\n</code></pre>\n<p>I'm suspicious about the <code>__prenormalise</code> method. You're doing there several simple replacements, which can be merged into a single one instead:</p>\n<pre><code>text = re.sub(r"\\b(\\?|\\!|\\"|--|\\n)\\b", " ", text)\n</code></pre>\n<p>even better you should use <a href=\"https://docs.python.org/3/library/re.html#re.compile\" rel=\"nofollow noreferrer\">re.compile</a> to compile the pattern once anywhere outside the function, so it is complied only once. If you would put this into a function, it would get compiled every time the function is executed:</p>\n<pre><code># replace all diacritics in a single go\nRE_DIACRITICS = re.compile(r"\\b(\\?|\\!|\\"|--|\\n)\\b")\n</code></pre>\n<p>then in the function you can use that compiled regex:</p>\n<pre><code># use inside your methods like this\ntext = RE_DIACRITICS.sub(" ", text)\n</code></pre>\n<p>however the slowest part is probably the loop, where you iterate through the whole text one character at a time:</p>\n<pre><code>for i, c in enumerate(chars):\n if i < 1 or i > len(chars)-1:\n continue\n if c == ',':\n if not(chars[i-1].isnumeric() and\n chars[i-1].isnumeric()):\n chars[i] = ', '\n text = ''.join(chars)\n</code></pre>\n<p>The condition <code>if i < 1 or i > len(chars)-1</code> is executed every time but it matters only during the first and last iteration. So you can throw it away and iterate only through a slice starting at the 2nd character and ending at the last-but-one:</p>\n<pre><code>for i, c in enumerate(chars[1:-1]):\n</code></pre>\n<p>However that is still slow. The thing what you want to do is to replace a comma between two non-numbers with the same thing except putting a space there, right? That could be done with a straightforward regex substitution instead of going one character after another manually. So the whole loop <code>for i, c in enumerate(chars):</code> can be replaced with this regex:</p>\n<pre><code> # replace comma between non-numbers with comma + space\n text = re.sub("(?<!\\d)(,)(?!\\d)", "\\g<1> ", text)\n</code></pre>\n<p>This regex is using negative lookahead and negative lookbehind, which you can find in the <a href=\"https://docs.python.org/3/library/re.html#regular-expression-syntax\" rel=\"nofollow noreferrer\">re module documenation</a>. It looks for a comma which is not following nor followed by a number, and then it replaces the comma with first matched group (which is the comma itself) plus space. For working with regexes I recommend using regex101.com, which can visualise results in real time. Here's the regex from above <a href=\"https://regex101.com/r/tccMoA/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/tccMoA/1</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T13:48:02.527",
"Id": "488421",
"Score": "0",
"body": "thanks for you answer i did everything you said but im having trouble understanding where to put the re.compile and the re.finditer. Is there a way to contact you privately? Much appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T14:42:37.513",
"Id": "488422",
"Score": "1",
"body": "I updated my answer further"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:16:35.137",
"Id": "488443",
"Score": "0",
"body": "@ yedpodtrzitko I tried the timeit you told me about its very usefull and i discovered that the __generate_results and the __preprocess are also taking alot of time im not sure why. I hope you can help with that? The changes you did to the __prenormalize were excellent now its much faster!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T11:35:46.447",
"Id": "249211",
"ParentId": "249208",
"Score": "4"
}
},
{
"body": "<h3><code>__preprocess()</code></h3>\n<p><code>token</code> is a list of (test, index) tuples. So, it looks like <code>idx</code> and <code>i</code> will always be the same value. <code>enumerate</code> is not needed, just use <code>i</code>.</p>\n<pre><code> # Remove spaces and some special encoding\n for t, i in tokens:\n t = t.replace('&amp;', '&')\n\n hints = ['[Music]', '[Laughter]', '[Applause]']\n for hint in hints:\n t = t.replace(hint, '')\n</code></pre>\n<p><code>tokens</code> is a list. Don't delete and then insert a new value, just replace the value. Also, <code>i</code> and <code>t</code> aren't used when removing the last dot.</p>\n<pre><code> tokens[idx] = (t.strip(), i)\n\n if len(tokens) and tokens[-1][0].endswith('.'):\n tokens[-1] = (t[:-1], i)\n\n return tokens\n</code></pre>\n<h3><code>__rstrip()</code> and <code>__lstrip()</code></h3>\n<p>The Python str type has methods for <code>__rstrip()</code> and <code>__lstrip()</code>. Triple quotes can be used to enclose a string containing both kinds of single quotes.</p>\n<pre><code>def __rstrip(self, token):\n return token.rstrip(''',.;!?:'"''')\n\ndef __lstrip(self, token):\n return token.lstrip(''',.;!?:'"''')\n</code></pre>\n<h3><code>__generate_results()</code></h3>\n<p>The <code>for t in normalised:</code> loop can be a generator expression:</p>\n<pre><code>text = ' '.join(w for w, _ in normalised if w)\n</code></pre>\n<p>It looks like the <code>for t in original</code> loop could be replaced by <code>itertools.groupby()</code> and grouping by the index in <code>normalized</code>.</p>\n<p>The way you are using <code>__rstrip()</code> and <code>__lstrip()</code>, just use the <code>strip()</code> method; it strips from both ends of the string.</p>\n<pre><code>from itertools import groupby\n\ntokens = []\nfor idx, group in groupby(normalized, key=lambda t:t[1]):\n words = [w for w, _ in group]\n display_text = original[idx][0].strip(''',.;!?:'"''')\n\n tokens.append((original[idx], words, display_text))\n</code></pre>\n<h3>main code</h3>\n<p>An open file is already an iterable, so you don't need to read it all in and then iterate over it.</p>\n<pre><code>with open(args.textfile) as fd:\n for line in fd:\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:58:21.880",
"Id": "249246",
"ParentId": "249208",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T10:30:45.783",
"Id": "249208",
"Score": "2",
"Tags": [
"python",
"performance",
"natural-language-processing"
],
"Title": "Text Normalizer"
}
|
249208
|
<p>I built an auction site with a dynamic caching layer after I seeing how expensive a dbaas is. The site is now done, but like any site that grows, my caching solution grew too. The cache currently caches every page on the site so I made sure everything gets invalidated appropriately, but the amount of stuff I'm invalidating has grown. More specifically when I'm creating a new auction. I know I'm using Azure so I can scale things from the portal to handle load, but I wanted to make sure my design will work. When someone creates an auction listing, I have to invalidate a bunch of stuff like in code below. Does anyone see a problem with what I'm doing or should I be good?</p>
<p>I'm using <a href="https://www.npmjs.com/package/redis-delete-wildcard" rel="nofollow noreferrer">redis-delete-wildcard</a> for the <code>delwild</code> keyword</p>
<pre><code>var Post = require('../models/post');
let emails;
var startTime;
const redis = require('redis');
var redisConnection = require("../connections/server");
require('redis-delete-wildcard')(redis); //pass in redis so prototype can be extended
const checkAuth = require('../middleware/check-auth');
module.exports = function (context, req) {
checkAuth(context, req);
const tempAuctionKey = `temp-auction-data-${req.body.creator}`;
redisConnection.client.get(tempAuctionKey, function (err, result) {
let blacklistGroup;
let email;
if (err) {
console.log(err);
}
let output = JSON.parse(result);
email = output.documents.email;
emails = output.emails;
if (err) {
context.res = {
status: 500,
body: {
message: "FAILED TO GET TEMP AUCTION DATA FROM CACHE!",
error: err
},
headers: {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
"Access-Control-Max-Age": "86400",
"Vary": "Accept-Encoding, Origin",
"Content-Type": "application/json"
}
};
context.done();
}
var fiveDaysAfterAuction = new Date(req.body.auctionEndDateTime * 1000);
startTime = new Date(req.body.startTime);
startTime.setSeconds(0);
fiveDaysAfterAuction.setHours(120);
console.log("req.body.auctionImages");
console.log(req.body.images);
let images = req.body.images;
console.log("req.body.auctionImagesTimeStamp");
console.log(req.body.auctionImagesTimeStamp);
const post = new Post({
title: req.body.title,
creator: req.body.creator
//and more...
});
post.save().then(result => {
const totalListingsKey = `dashboardTotal-${req.body.creator}`;
const sellerDashboardKey = `dashboard-${req.body.creator}-*`;
const bioKey = `my-bio-${req.body.sellerName}-*`;
const mainListingsCountKey = `main-listing-count`;
const buyNowTotalKey = `buy-total`;
//clears seller bio page which has active auctions listed
redisConnection.client.delwild(bioKey, function (error, numberDeletedKeys) {
console.log("Deleted Seller Bio Page for Seller");
console.log(numberDeletedKeys);
});
if (req.body.auctionType === "publicAuction") {
//clears all the auction pages
redisConnection.client.delwild('main-listings-no-filter-page=*', function (error, numberDeletedKeys) {
console.log("Deletes all auction pages");
console.log(numberDeletedKeys);
});
//clears the buy it now page if new auction is a buy it now listing
if (req.body.buyItNow) {
const buyNowKey = `buy-now-page-*`;
redisConnection.client.delwild(buyNowKey, function (error, numberDeletedKeys) {
console.log("deleted buynowkeys");
console.log(numberDeletedKeys);
});
//clears buy it now page total count for pagination
redisConnection.client.del(buyNowTotalKey, function (err, response) {
if (response == 1) {
console.log("Deleted Buy Now total count")
} else {
console.log("Cannot delete buy now total")
}
})
}
//clears main page total count for pagination
redisConnection.client.del(mainListingsCountKey, function (err, response) {
if (response == 1) {
console.log("Deleted Listings Count Successfully!")
} else {
console.log("Cannot delete")
}
})
}
//clears seller dashboard listings
redisConnection.client.delwild(sellerDashboardKey, function (error, numberDeletedKeys) {
console.log("numberDeletedKeys");
console.log(numberDeletedKeys);
});
//clears seller dashboard page count for pagination
redisConnection.client.del(totalListingsKey, function (err, response) {
if (response == 1) {
console.log("Deleted SellerDashboard Listings Count Successfully!")
} else {
console.log("Cannot delete")
}
})
redisConnection.client.expire(tempAuctionKey, 5);
context.res = {
status: 201,
body: {
message: "Auction listing created successfully!",
postId: result._id
},
headers: {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
"Access-Control-Max-Age": "86400",
"Vary": "Accept-Encoding, Origin",
"Content-Type": "application/json"
}
};
context.done();
}).catch((err) => {
context.res = {
status: 500,
body: {
message: "Auction Creation Failed",
error: err
},
headers: {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
"Access-Control-Max-Age": "86400",
"Vary": "Accept-Encoding, Origin",
"Content-Type": "application/json"
}
};
context.done();
});
});
};
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T14:14:54.647",
"Id": "249218",
"Score": "2",
"Tags": [
"node.js",
"redis",
"azure"
],
"Title": "Scalability of azure redis example"
}
|
249218
|
<p>I'm looking into fixing some obvious performance-related issues in my code but I tend to employ bug-introducing tricks as I do so.</p>
<p>My code uses a library which defines <code>Field<scalar></code> and <code>uniformField<scalar></code>:</p>
<pre class="lang-cpp prettyprint-override"><code>template<class T>
class Field
{
List<T> v_;
public:
explicit Field(const Mesh&); // There are more args, but that's the important one
// v_ gets initialized based on mesh size.
// operator[](int) is a proxy to List<T>::operator[](int)
};
template<class T>
class uniformField
{
T v_;
public:
uniformField(const Mesh&, const T&); // There are more args, but that's the important one
// v_ gets initialized to passed value.
// operator[](int) is defined to always return v_
};
</code></pre>
<p>But I'm in a situation where, at run time, a specific variable can be either a single scalar
or a collection of scalars (collection size = mesh size).</p>
<blockquote>
<p>Currently, I'm replicating the single scalar to a full field, making use only of <code>Field</code> in both cases (The variable will always have mesh.nCells() elements which is a waste of memory and cpu; I expect 10000s to milions of these elements).</p>
</blockquote>
<p>I thought of two options:</p>
<ol>
<li>Make a new field class inheriting from both <code>Field</code> and <code>uniformField</code>. But this approach has obvious drawbacks:</li>
</ol>
<ul>
<li>These classes are closely related and have no default constructors. Their constructors will probably be implicitly deleted in the derived one (if attempting to inherit them).</li>
<li>The hope of using <code>operator[]</code> seamlessly perishes as I'll have to resolve the ambiguity of such operators manually.</li>
</ul>
<ol start="2">
<li>Give up on using <code>uniformField</code> and use a single-element field for the scalar case.
Now, that's easy, I just define:</li>
</ol>
<pre><code>class OneCellMesh : public Mesh; // Which will always have size = 1
// and can be constructed from a Full Mesh object
// Initialize a scalar to erronous value (eg. if s is supposed to be positive:)
scalar s = -1;
// Consider user input
s = readScalar(); // If the user didn't specify this, "s" won't be touched.
// If didn't touch s, construct as a field
// else, construct as scalar
Field<scalar> sF( s == -1 ? fullMesh ! OneCellMesh(fullMesh));
</code></pre>
<p>The problem with this "volatile" construction is that it forces me to check the size
of <code>sF</code> every time if I want to write safe code. Particularly, <code>Field<T></code> will generate UB code all over the place (Field::operator[] has no bound handling) and it's difficult to control the effects of such construction. Eg. what happens if one calls pow(Field&, Field&) where the parameters have different sizes?</p>
<p>Is there a better way to do this (in addition to building up my own class from scratch!)?</p>
<h2>For those of who want to see actual code</h2>
<p>Consider <code>uniformField</code> to be <a href="https://github.com/FoamScience/OpenFOAM-dev/blob/master/src/OpenFOAM/fields/UniformDimensionedFields/UniformDimensionedField.H#L54" rel="nofollow noreferrer">UniformDimensionedField from OpenFOAM</a>
Consider <code>Field</code> to be <a href="https://github.com/FoamScience/OpenFOAM-dev/blob/master/src/OpenFOAM/fields/DimensionedFields/DimensionedField/DimensionedField.H#L71" rel="nofollow noreferrer">DimensionedField from OpenFOAM</a></p>
<p>NB: In no way I'm suggesting review for those classes.</p>
<h3>Working code (Current implementation):</h3>
<pre><code> DimensionedField<scalar,volMesh> ss
(
IOobject
(
"ss",
mesh.time().timeName(),
mesh,
IOobject::READ_IF_PRESENT,
IOobject::AUTO_WRITE
),
mesh, // Has many cells
dimensionedScalar("ss", 0)
);
DimensionedField<scalar,volMesh> sv
(
IOobject
(
"ss",
mesh.time().timeName(),
mesh,
IOobject::READ_IF_PRESENT,
IOobject::AUTO_WRITE
),
mesh, // Has many cells
dimensionedScalar("sv", readScalar(dict))
);
// both sv and ss are of equal size, but as you can see,
// sv is initialized from a user-provided scalar and won't be
// changed any further.
// Works but wasteful
Info << sv + ss << endl;
// Notice READ_IF_PRESENT
// The user can write a file which is read into sv
// Then, sv has many elements and the previous operation is not wasteful
</code></pre>
<p>I'm looking into optimizing <code>sv</code> so not to store many values but store a single scalar one and still benefit from a shared interface for both <code>sv</code> and <code>ss</code> types.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T14:54:35.083",
"Id": "488424",
"Score": "0",
"body": "Welcome to Code Review! I've voted to close your question as [off-topic](https://codereview.stackexchange.com/help/on-topic). We only review complete, functional code, that has sufficient review context for meaningful review. Right now the code does not seem to be fully written (and thus functional), and I don't feel like there is quite enough context to understand what problem you're trying to solve. Please feel free to [edit](https://codereview.stackexchange.com/posts/249219/edit) your question to include complete working code & more detailed explanation and we will happily review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:00:10.450",
"Id": "488426",
"Score": "1",
"body": "@Dannnno I explicitly mentioned how I'm doing things now \"Currently, I'm replicating the single scalar to a full field, making use only of Field in both cases (The variable will always have mesh.nCells() elements which is a waste of memory and cpu; I expect 10000s to milions of these elements).\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:02:52.407",
"Id": "488427",
"Score": "0",
"body": "Including complete code is not an option because of the huge dependency tree of the classes! I believe I included the relevant parts. I'm happy to clarify any issues of anyone has any!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:03:19.147",
"Id": "488428",
"Score": "1",
"body": "@Dannnno I was the one who sent this user here, before he posted their question they confirmed their code **is** already working as intended, and they're looking for potential performance improvements. I agree, that the question could be improved by showing larger part of the code to see more context, but in no way there's a MCVE required at CR. So give them a chance, before close voting please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:23:33.527",
"Id": "488431",
"Score": "1",
"body": "@Dannnno I edited the question as you suggested. Hope it's in an acceptable state now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:24:06.010",
"Id": "488632",
"Score": "0",
"body": "I do *not* find enough code presented in the [2nd revision](https://codereview.stackexchange.com/revisions/249219/2) to even guess where performance issues may arise, let alone be mended. (I'm not fond of having to search in the first place.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:25:31.890",
"Id": "488633",
"Score": "1",
"body": "(One idea coming to mind is to introduce `FieldExpression`s as 1st class citizen and build on lazy evaluation.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:02:17.290",
"Id": "488834",
"Score": "0",
"body": "@greybeard Already planning on Lazy Evaluation for next phase: Just need to absolutely make sure that the current code is bug-free :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T15:11:33.090",
"Id": "488838",
"Score": "0",
"body": "@greybeard the expression \"ss+sv\" may be wastefull if either vector is represented by a single scalar value. These vectors are expected to be big, so duplicating the scalar value to match the size of the vector is not \"optimal\" (Memory-wise and cpu-time-wise)"
}
] |
[
{
"body": "<h1>Consider using <code>std::variant</code></h1>\n<p>So what you want is something that can either hold a single value or a <code>std::vector</code> of values, with the idea that you don't want to pay for the memory and/or CPU overhead of a <code>std::vector</code> for a uniform field. Consider using <a href=\"https://en.cppreference.com/w/cpp/utility/variant\" rel=\"noreferrer\"><code>std::variant</code></a>:</p>\n<pre><code>template<typename T>\nclass Field {\n std::variant<T, std::vector<T>> v_;\npublic:\n explicit Field(const Mesh&); // initializes the vector\n uniformField(const Mesh&, const T&); // initializes the single value\n};\n</code></pre>\n<p>And then all the member functions should check which variant is used. Of course, that will complicate all the member functions, and they do need to perform a runtime check. But you probably would have to pay that price somewhere anyway, if whether you want a regular field or uniform field depends on user input.</p>\n<p>Alternatively:</p>\n<h1>Make out-of-bounds handling fast</h1>\n<p>An advantage of your problem is that either you have a vector of arbitrary size, and code already is written such that they don't go out of bounds, or you want it to act like a vector but always return the same element. Consider storing a mask that is either all ones or all zeroes, depending on if it's a regular field or uniform field,\nand use that to mask the index inside <code>operator[]</code>:</p>\n<pre><code>template<typename T>\nclass Field {\n std::vector<T> v_;\n size_t mask;\npublic:\n explicit Field(const Mesh&): mask{-1} {v_.reserve(/* mesh size */); ...}\n uniformField(const Mesh&, const T& value): mask{0}, v_{value} {...}\n\n T &operator[](size_t index) {\n return v_[index & mask];\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:55:34.323",
"Id": "488433",
"Score": "1",
"body": "+1 for the mask idea: already employing this for other things :) so It'll be consistent . I'm aware of \"variant\" but prefer not to use c++14. So, you say I'll have to check the mask (or the size) in operator+ .... and similar functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:32:23.497",
"Id": "488454",
"Score": "1",
"body": "Yes, you can do that. Check both masks in the operator overloads, and if they are different, then you know if you have the situation where you add a uniform field to a regular field or the other way around, and the result should then be a regular field."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:38:51.813",
"Id": "488525",
"Score": "0",
"body": "Verified with experiment; The correct definition of operator[] is most enough as (most) other operators will use it. I think this is the way to go. Considering no further answers have been submitted in ~24 hours"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:30:51.710",
"Id": "249221",
"ParentId": "249219",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "249221",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T14:14:55.253",
"Id": "249219",
"Score": "5",
"Tags": [
"c++",
"performance",
"vectors"
],
"Title": "Handle (“potentially” occuring) scalar-Vector and Vector-Vector operations"
}
|
249219
|
<p>I want to get exactly <code>n</code> unique randomly sampled rows per category in a Dataframe. This proved to be involve more steps than the description would lead you to believe.</p>
<pre class="lang-py prettyprint-override"><code>n = 4
df = pd.DataFrame({'category': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 1],
'value' : range(12)})
category_counts = df['category'].value_counts()
categories_with_count_above_threshold = category_counts[category_counts >= n].index
# rows with infrequent categories are filtered out
df = df[df['category'].isin(categories_with_count_above_threshold)]
# sample exactly x rows per category
df = df.groupby('category').sample(n)
</code></pre>
<p>This goes through the whole DataFrame quite a few times. With a bigger DataFrame this can become quite time consuming. Is there a way to simplify this expression?</p>
<p>PS: requires <code>pandas</code> >= 1.1 for the <code>DataFrameGroupBy.sample</code></p>
|
[] |
[
{
"body": "<p>Have you tried using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html?highlight=filter#pandas.core.groupby.DataFrameGroupBy.filter\" rel=\"nofollow noreferrer\"><code>DataFrameGroupBy.filter()</code></a> (I don't have recent pandas on this machine so I can't test it).</p>\n<pre><code>n = 4\ndf = pd.DataFrame({'category': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 1],\n 'value' : range(12)})\n\n# sample exactly x rows per category\ndf = df.groupby('category').filter(lambda x:x.size >= n).sample(n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T11:28:00.243",
"Id": "488705",
"Score": "0",
"body": "Filter sadly does not return groups, so sample works on the whole DataFrame and I get n rows back instead of n rows _per group_. As it stands, I would just have to do another `groupby('category')` between `filter` and `sample`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T07:47:48.793",
"Id": "488804",
"Score": "0",
"body": "Also, `filter` passes the groups as DFs to the lambda function and size returns <n_rows * n_columns> for DFs, so you would have to call `len` instead.\nIn the end the multiple groupby could not be avoided and the query has to look like this afaict:\n`df = df.groupby('category').filter(lambda x: len(x) >= n).groupby('category').sample(n)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T20:26:58.390",
"Id": "249242",
"ParentId": "249222",
"Score": "0"
}
},
{
"body": "<p>Here's code using <code>.apply()</code>, that makes a single pass through the dataframe.</p>\n<pre><code>df = pd.DataFrame({'category': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 1],\n 'value': range(12),\n 'other': list('abcdefghijkl')})\n\ndef pick(group, n):\n """Return n random rows from groups that have at least n rows"""\n\n if len(group) >= n:\n return group.sample(n)\n\n# sample exactly x rows per category, iff there are at least x in the catgory\nx = 4\ndf1 = df.groupby('category').apply(pick, x).reset_index(drop=True)\n\ndf1\n</code></pre>\n<p>output:</p>\n<pre><code> category value other\n0 1 3 d\n1 1 11 l\n2 1 6 g\n3 1 9 j\n4 2 10 k\n5 2 1 b\n6 2 4 e\n7 2 7 h\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:37:56.690",
"Id": "250557",
"ParentId": "249222",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T15:41:27.373",
"Id": "249222",
"Score": "5",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Get exactly `n` unique randomly sampled rows per category in a Dataframe"
}
|
249222
|
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps" rel="nofollow noreferrer">"Ransom Note" problem on hackerank</a>.
Why isn't my code getting submitted?
What can I do differently?
is my total time complexity, in this case, it is O(n^2)?</p>
<pre><code>#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the checkMagazine function below.
def checkMagazine(magazine, note):
for word in note: # O(n)
if word not in magazine: # O(n)
return 'No'
else:
magazine.remove(word) # O(n)
return 'Yes'
if __name__ == '__main__':
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
print(checkMagazine(magazine, note))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:24:59.493",
"Id": "488445",
"Score": "1",
"body": "\"Why isn't my code getting submitted?\" - I guess because you're not submitting it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:33:59.547",
"Id": "488447",
"Score": "0",
"body": "And if you do submit it, it doesn't get accepted. Probably that's what you meant? Then you know that it's not correct, making this off-topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:27:31.190",
"Id": "488634",
"Score": "0",
"body": "In your assessment of asymptotic bounds of complexity, you need more variables to model problem size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:29:36.907",
"Id": "488635",
"Score": "0",
"body": "(You may try and find an approach minimising memory required.)"
}
] |
[
{
"body": "<p>You can find some ideas in the discussions tab of the original question:\n<a href=\"https://www.hackerrank.com/challenges/ctci-ransom-note/forum?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps\" rel=\"nofollow noreferrer\">https://www.hackerrank.com/challenges/ctci-ransom-note/forum?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps</a>.</p>\n<p>To answer your quesitons: yes, your solution has time complexity of O(n^2).</p>\n<p>The optinal solution should have time complexity of O(n):</p>\n<ol>\n<li>Go through magazine in O(n), get a map from words to counts.</li>\n<li>Go through note in O(n), also get a map from words to counts.</li>\n<li>Go through the map in step 2 in O(n), check for each word, whether the count of the map in step 1 is larger or not. Return True only when all the counts are no larger.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T16:28:53.580",
"Id": "249225",
"ParentId": "249224",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249225",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T16:08:12.217",
"Id": "249224",
"Score": "-4",
"Tags": [
"python",
"performance",
"python-3.x",
"complexity"
],
"Title": "What is the time complexity problem I need to manage on a Hackerank \"Ransom Note\" - my code runs perfectly"
}
|
249224
|
<p>I am new to writing java code and I would like to improve my skills. I would like someone to review and critic me on where I can improve on. Here is a small program I wrote in java about matrices and a few arithmetic methods applied on it.</p>
<pre><code>import java.util.*;
public class MatrixArithmetic{
private static Scanner in = new Scanner(System.in);
public static void main(String[] args){
menu();
}
public static void menu(){
showOptions();
int choice = getValue();
System.out.println();
while (choice != -1){
switch (choice){
case 1:{ // add two matrices
int size = getSize();
int[][] firstMatrix = getMatrix(size);
int[][] secondMatrix = getMatrix(size);
System.out.println();
System.out.println("First matrix is:");
printMatrix(firstMatrix);
System.out.println("Second matrix is:");
printMatrix(secondMatrix);
int[][] result = addMatrix(firstMatrix, secondMatrix, size);
System.out.println("The resulting matrix is:");
printMatrix(result);
System.out.println();
System.out.println("Command number 1 completed.");
System.out.println();
showOptions();
choice = getValue();
System.out.println();
break;
}
case 2:{ // subtract two matrices
int size = getSize();
int[][] firstMatrix = getMatrix(size);
int[][] secondMatrix = getMatrix(size);
System.out.println();
System.out.println("First matrix is:");
printMatrix(firstMatrix);
System.out.println("Second matrix is:");
printMatrix(secondMatrix);
int[][] result = subMatrix(firstMatrix, secondMatrix, size);
System.out.println("The resulting matrix is:");
printMatrix(result);
System.out.println();
System.out.println("Command number 2 completed.");
System.out.println();
showOptions();
choice = getValue();
System.out.println();
break;
}
case 3:{ // multiply two matrices
int size = getSize();
int[][] firstMatrix = getMatrix(size);
int[][] secondMatrix = getMatrix(size);
System.out.println();
System.out.println("First matrix is:");
printMatrix(firstMatrix);
System.out.println("Second matrix is:");
printMatrix(secondMatrix);
int[][] result = prodTwoMatrix(firstMatrix, secondMatrix, size);
System.out.println("The resulting matrix is:");
printMatrix(result);
System.out.println();
System.out.println("Command number 3 completed.");
System.out.println();
showOptions();
choice = getValue();
System.out.println();
break;
}
case 4:{ // multiply matrix to a constant
int size = getSize();
System.out.print("Enter the multiplication constant: ");
int constant = getValue();
int[][] matrix = getMatrix(size);
System.out.println();
System.out.println("The matrix is:");
printMatrix(matrix);
int[][] result = prodMatrixConstant(matrix, size, constant);
System.out.println("The resulting matrix is:");
printMatrix(result);
System.out.println();
System.out.println("Command number 4 completed.");
System.out.println();
showOptions();
choice = getValue();
System.out.println();
break;
}
case 5:{ // transpose matrix
int size = getSize();
int[][] matrix = getMatrix(size);
System.out.println();
System.out.println("The matrix is:");
printMatrix(matrix);
int[][] result = transposeMatrix(matrix, size);
System.out.println("The resulting matrix is:");
printMatrix(result);
System.out.println();
System.out.println("Command number 5 completed.");
System.out.println();
showOptions();
choice = getValue();
System.out.println();
break;
}
case 6:{ // trace matrix
int size = getSize();
int[][] matrix = getMatrix(size);
System.out.println();
System.out.println("The matrix is:");
printMatrix(matrix);
int result = traceMatrix(matrix, size);
System.out.println();
System.out.print("The trace for this matrix is: " + result);
System.out.println("\n");
System.out.println("Command number 6 completed.");
System.out.println();
showOptions();
choice = getValue();
System.out.println();
break;
}
default:{
System.out.println("Testing completed.");
choice = -1;
break;
}
}
}
}
public static void showOptions(){
System.out.print("Your options are: \n" +
"----------------- \n" +
"1) Add two matrices \n" +
"2) Subtract 2 matrices \n" +
"3) Multiply 2 matrices \n" +
"4) Multiply matrix by a constant \n" +
"5) Transpose matrix \n" +
"6) Matrix trace \n" +
"0) EXIT \n" +
"----------------- \n" +
"Please enter your option: ");
}
public static int getValue(){
return in.nextInt();
}
public static int getSize(){
System.out.print("Enter the size of square matrices: ");
int size = getValue();
return size;
}
public static int[][] getMatrix(int size){
int[][] matrix = new int[size][size];
randMatrix(matrix, size);
return matrix;
}
public static void randMatrix(int[][] matrix, int size){
Random rand = new Random();
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
matrix[i][j] = rand.nextInt(10);
}
}
}
public static void printMatrix(int[][] matrix){
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
System.out.printf("%4s\t", matrix[i][j]);
}
System.out.print("\n");
}
}
public static int[][] addMatrix(int[][] firstMatrix, int[][] secondMatrix, int size){
int[][] add = new int[size][size];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
add[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
return add;
}
public static int[][] subMatrix(int[][] firstMatrix, int[][] secondMatrix, int size){
int[][] sub = new int[size][size];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
sub[i][j] = firstMatrix[i][j] - secondMatrix[i][j];
}
}
return sub;
}
public static int[][] prodTwoMatrix(int[][] firstMatrix, int[][] secondMatrix, int size){
int[][] product = new int[size][size];
for(int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
return product;
}
public static int[][] prodMatrixConstant(int[][] matrix, int size, int constant){
int[][] product = new int[size][size];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
product[i][j] = matrix[i][j] * constant;
}
}
return product;
}
public static int[][] transposeMatrix(int[][] matrix, int size){
int[][] newMatrix = new int[size][size];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
newMatrix[i][j] = 0;
for(int k = 0; k < size; k++){
newMatrix[i][j] = matrix[j][i];
}
}
}
return newMatrix;
}
public static int traceMatrix(int[][] matrix, int size){
int trace = 0;
for (int i = 0; i < size; i++){
trace += matrix[i][i];
}
return trace;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:42:23.150",
"Id": "488456",
"Score": "2",
"body": "Welcome to Code Review! Can you describe the code more than just \"_Here is a small program I wrote in java about matrices and a few arithmetic methods applied on it._\"? The more you tell us about [what your code is for](https://meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title applies to too many posts on this site (since many users want their programs to be written better) and needs an [edit] to simply [state the task](https://meta.codereview.stackexchange.com/q/2436) per site convention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T19:52:39.067",
"Id": "488458",
"Score": "0",
"body": "The task was to design a Java program to implement matrix arithmetic for square matrices (same number of rows and columns) and to make sure that the program is calling methods to perform (at least) the following operations:\n1) Generate: Generate a matrix with values 1 - 10\n2) Addition\n3) Subtraction\n4) Multiplication\n5) Multiply two matrices\n6) Multiply a matrix by a constant\n7) Transposition\n8) Matrix Trace"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T06:08:59.257",
"Id": "488486",
"Score": "0",
"body": "Please [edit] this information into your question, don't hide it away in comments, especially since you are using a numbered list in your comment and comments don't support numbered list formatting."
}
] |
[
{
"body": "<p>In my humble opinion, there are three possible improvements:</p>\n<ol>\n<li>Inside the switch clause, there are a lot of repeated statements. You can move all the common parts (read matrix, print matrix) outside the switch clause, and only leave the real matrix computation part inside the switch.</li>\n<li>I would suggest make all the computation methods <code>private</code> other than <code>public</code>.</li>\n<li>Actually another method can be abstracted, where the input is two matrix and one option, the output is the matrix result.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T03:56:09.760",
"Id": "249252",
"ParentId": "249228",
"Score": "2"
}
},
{
"body": "<p>The single biggest, most obvious problem in your code is that <em>everything</em> is about doing stuff with matrices, yet there is not a single <code>Matrix</code> object to be found anywhere.</p>\n<p>Your <em>central</em> object that everything revolves around is the matrix, and that should be represented by an <em>actual</em> object in your program. So, your central class (or record in Java 14+) should be a <code>Matrix</code> class with methods like <code>plus</code>, <code>minus</code>, <code>mult</code>, etc. Notice that almost every method in your class has <code>Matrix</code> in its name and takes a <code>matrix</code> parameter? That is a sure sign that this parameter should actually be an object that you call the method on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T11:08:17.663",
"Id": "249270",
"ParentId": "249228",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249252",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:00:01.947",
"Id": "249228",
"Score": "0",
"Tags": [
"java",
"matrix"
],
"Title": "Better way to write this program in java?"
}
|
249228
|
<p>So I recently applied to <a href="https://boards.greenhouse.io/fetchrewards/jobs/4011315003" rel="nofollow noreferrer">this</a> job for iOS Developer and was invited to complete the following code challenge:</p>
<blockquote>
<p>As a next step, please complete this coding exercise in order to proceed with our interview process. If you do well & pass, you will be connected to a Software Engineer to discuss your exercise for an hour zoom video call. Take as much time as needed.</p>
<p>Problem statement:</p>
<p>Please write an (Android/iOS) app that retrieves the data from <a href="https://fetch-hiring.s3.amazonaws.com/hiring.json" rel="nofollow noreferrer">https://fetch-hiring.s3.amazonaws.com/hiring.json</a>. This will return a json array of items. Using this list of items, display all the items grouped by "listId" to the UI. Sort the results first by "listId" then by "name" when displaying. Filter out any items where "name" is blank or null. The final result should be displayed to the user in an easy-to-read list."</p>
</blockquote>
<p>My solution is <a href="https://github.com/rjowell/FetchTestApp" rel="nofollow noreferrer">here</a>.</p>
<p>View Controller is as follows:</p>
<pre><code>import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData[section].count
}
@IBOutlet weak var dataTableView: UITableView!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataViewCell", for: indexPath) as? DataCell
cell?.textSpace.text=tableData[indexPath.section][tableIndices[indexPath.section][indexPath.row]]
return cell!
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "List ID: "+String(section+1)
}
func numberOfSections(in tableView: UITableView) -> Int {
return tableData.count
}
var tableData: [[Int:String]]=[[:]]
var tableIndices: [[Int]]=[[]]
override func viewDidLoad() {
super.viewDidLoad()
URLSession.shared.dataTask(with: URL(string: "https://fetch-hiring.s3.amazonaws.com/hiring.json")!)
{
data,response,error in
let json=try? JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]
for items in json!
{
if(type(of: items["name"]!) != NSNull.self && items["name"]! as! String != "")
{
let listID=Int(String(describing: items["listId"]!))!
while(self.tableData.count < listID)
{
self.tableData.append([:])
self.tableIndices.append([])
}
self.tableIndices[listID-1].append(Int(String(describing: items["id"]!))!)
self.tableData[listID-1][Int(String(describing: items["id"]!))! ]=items["name"]! as! String
self.tableIndices[listID-1].sort()
}
}
DispatchQueue.main.async {
self.dataTableView.delegate=self
self.dataTableView.dataSource=self
self.dataTableView.reloadData()
}
}.resume()
}
}
</code></pre>
<p>Two days after submitting, I got the following feedback:</p>
<blockquote>
<p>The exercise featured a lot of Swift code that forced unwrapping instead of using nil safe paradigms such as let or guard, and the items displayed in the list would have benefited from a struct or class defining the object to better separate the business logic from the view controller.</p>
</blockquote>
<p>Are they being too nit picky here, or is my code really that screwed up?</p>
|
[] |
[
{
"body": "<p>They're not being too nit-picky. DataTask's completion handler will return nil for data when it couldn't get the data, like when the network is offline. Force unwrapping 'data' means you deliberately crash the application when that happens. That would be bad.</p>\n<p>"separate the business logic from the view controller": They expect you to make a data type to parse the JSON into, perhaps like this:</p>\n<pre><code>struct Item: Decodable {\n let id: Int\n let listId: Int\n let name: String?\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:27:03.170",
"Id": "249536",
"ParentId": "249229",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:05:20.067",
"Id": "249229",
"Score": "5",
"Tags": [
"interview-questions",
"swift",
"ios"
],
"Title": "Sorting JSON items from a site"
}
|
249229
|
<p>I'm a hobbyist programmer(just having fun) created a small script that takes a photo and
resizes it, then cuts it up into 24 pieces. The chunks are transposed and made into buttons. Your task is to get it back to it's original state without out going negative on points. My questions are: was it fun? Could you play it on windows or iso platforms?</p>
<pre><code>from PIL.ImageTk import Image, PhotoImage
from PIL import ImageChops
from tkinter import (Canvas,Tk,Frame,Button,YES,BOTH,filedialog,
Toplevel,IntVar,Label)
from tkinter.messagebox import showinfo, showerror
import logging
from random import choice
from functools import partial
#logging.basicConfig(level= logging.DEBUG)
logging.disable(logging.CRITICAL)
class Puzzle_One(Frame):
"""Grab a picture, then cuts it up into 24 pieces and transpose,
make them into buttons. Repeatedly pressing the buttons to it's
origional state before getting a negative score."""
def __init__(self, parent=None):
self.parent= parent
Frame.__init__(self, self.parent)
self.pack(expand=YES, fill=BOTH)
self.canvas= Canvas(self)
self.canvas.config(width= 800, height= 700, bg='gray90')
self.canvas.pack(expand=YES, fill=BOTH)
self.puzzle_points= IntVar()
self.lbl_1= Label(self.canvas, textvariable=self.puzzle_points,
font=('arial',50,'bold'))
self.lbl_1.place(x=500,y=30)
self.puzzle_points.set(2500)
self.btn= Button(self.canvas, text='find image',
command= self.get_image)
self.btn.place(x=400,y=600)
self.buttons= []
self.image_ref= []
self.transitions= [ Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM,
Image.ROTATE_180, Image.ROTATE_270,
Image.ROTATE_90]
self.t_count=0
self.t_pics=[]
self.buttons= []
self.image_compare= []
self.mydict= {}
def get_image(self):
"""Find your photo, it will be displayed on the canvas as a reference.
A new button will be made to create the puzzle"""
self.btn.config(state='disabled')
self.file= filedialog.askopenfilename(filetypes=[('PNG','.png'),
('JPG','.jpg'),
('GIF','.gif'),
]
)
self.image= Image.open(self.file)
self.im= self.image.resize((600,400))
image= PhotoImage(self.im)
self.canvas.create_image(360,320,image=image,tag='my_image')
self.t_pics.append(image)
self.btn2= Button(self.canvas,text='make puzzle',
command=self.make_puzzle)
self.btn2.place(x=200,y=600)
def rotate_btn(self,pic_name, index):
"""Reapeatedly pressing the image buttons scrolls through a list of
image transitions. Find the correct position"""
if self.t_count >4:
self.t_count =0
img= pic_name.transpose(self.transitions[self.t_count])
self.mydict[index]= img
image= PhotoImage(image=img)
self.buttons[index].config(image=image)
self.t_pics.append(image)
self.t_count +=1
def compare(self):
"""Compares the puzzle button with the original. Numbering starts
in the upper left corner with 0, lower right corner is 23.
Need a better way to indicate which buttons image is incorrect.
Updating the score
"""
points= self.puzzle_points.get()
res= []
for num in range(0,24):
image_1= self.image_compare[num]
image_2= self.mydict.get(num, '')
diff= ImageChops.difference(image_1,image_2)
if diff.getbbox():
pts= points- 500
if pts < 0:
self.puzzle_points.set(pts)
self.buttons[num].config(borderwidth=10)
txt= 'Your total points is {}'.format(pts)
showinfo('Loss',txt)
self.buttons[num].config(borderwidth=2)
self.btn3.config(state='disabled')
break
else:
self.puzzle_points.set(pts)
self.buttons[num].config(borderwidth=10)
text_= "There's an error {}".format(num)
showerror('No bueno', text_)
self.buttons[num].config(borderwidth=2)
break
else:
res.append(num)
if len(res) == 24:
total= self.puzzle_points.get()
text='Winner your total points are {}'.format(total)
showinfo('Win', text)
self.btn3.config(state='disabled')
def make_puzzle(self):
"""A popup window containing 24 buttons. x1,y1,x2,y2 are the position of the cut pieces
of the image. A reference of each region is transposed and converted to a Tk image,
then saved to a list to prevent being garbage collected. Passing the region of each
image and the index as an argument for each button. The buttons are in a list so they
can be accessed by the index."""
self.btn3= Button(self.canvas, text='I solved it!',
command=self.compare)
self.btn3.place(x=600,y=600)
self.btn2.config(state='disabled')
self.top= Toplevel()
x1=0
y1=0
x2=100
y2=100
count=0
b_count=0
for r in range(1,5):
for c in range(1,7):
box= x1,y1,x2,y2
reg= self.im.crop(box)
self.image_compare.append(reg)
tran= choice(self.transitions)
reg= reg.transpose(tran)
self.mydict[b_count]= reg
image= PhotoImage(reg)
self.buttons.append(Button(self.top,image=image,
command=partial(self.rotate_btn,reg,b_count))
)
self.buttons[-1].grid(row=r,column=c,padx=0.5,pady=0.5)
self.image_ref.append(image)
if count == 5:
count= 0
b_count +=1
x1 = 0
y1 += 100
x2= 100
y2 += 100
else:
x1 +=100
x2 +=100
count +=1
b_count +=1
if __name__ == '__main__':
root= Tk()
Puzzle_One(root)
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>Nice game and great work, my daughter likes it!</p>\n<p>It worked running on Windows. On completing the puzzle I was unable to select another picture and play again. I think this can be easily implemented by adding a method <code>play_game(self)</code> that takes the overall control of the game and will have a quit button.</p>\n<p>A follow up puzzle would be to hustle the picture elements where you have to put them in the right order.</p>\n<p>Then a suggestion, you can try to implement the same game in PyQt5. Personally I like this GUI better than tkinter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T05:56:17.290",
"Id": "249475",
"ParentId": "249230",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:22:06.903",
"Id": "249230",
"Score": "5",
"Tags": [
"python",
"tkinter"
],
"Title": "Image puzzle PIL tkinter"
}
|
249230
|
<p>I need to calculate the value for the following function:</p>
<p><span class="math-container">$$f(n) = -1 + 2 - 3 + ... + -1^n$$</span></p>
<p>The time limit to calculate a given value of <span class="math-container">\$n\$</span> is less than 1 second. My approach does not meet that requirement at large sizes, for example <span class="math-container">\$f(1000000000)\$</span>.</p>
<p>My code:</p>
<pre><code>program A486;
uses wincrt, sysutils;
var
n: LongInt;
function f(n : LongInt): LongInt;
var
i : LongInt;
//Result : LongInt;
begin
Result:= 0;
for i:= 1 to n do
if i mod 2 = 0 then
Result += i
else
Result -= i;
//f:= Result;
end;
begin
readln(n);
writeln(f(n));
//readkey()
end.
</code></pre>
<p>Is there a better way I can do this?</p>
|
[] |
[
{
"body": "<p>Seems trivial. Pair them, each pair is worth -1.</p>\n<pre><code>f(1000) = 1 - 2 + 3 - 4 + ... + 999 - 1000\n = (1 - 2) + (3 - 4) + ... + (999 - 1000)\n = -1 -1 + ... + -1\n = -500\n</code></pre>\n<p>Odd n left as exercise for the reader.</p>\n<p>(I wrote this when the question title still said "1 − 2 + 3 − 4 + · · ·", can't be bothered to switch all signs now.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:37:43.387",
"Id": "488455",
"Score": "0",
"body": "Thank you very much for your idea."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:58:53.667",
"Id": "249235",
"ParentId": "249231",
"Score": "1"
}
},
{
"body": "<p>According to the help of Mr Andreas, i have come up with this code, which was helpful, but it gave a runtime error, in this test : <code>1000000000000000</code>, I have to disapprove the answer as it wasn't the best performance. But i still greatly thank you for your attention.</p>\n<p>code :</p>\n<pre><code>program A486;\nuses wincrt, sysutils;\n\nvar\n n: LongInt;\n\nfunction f(n : LongInt): LongInt;\nvar\n {Result,} SumOdd, SumEven : LongInt;\nbegin\n Result:=0; SumOdd:=0; SumEven:=0; \n if n mod 2 = 0 then\n begin \n SumOdd:=( n*(n div 2) ) div 2;\n SumEven:=((2+n)*(n div 2) ) div 2;\n Result:= SumOdd - SumEven;\n end else \n begin\n SumOdd:=( (n+1)*(n div 2 + 1) ) div 2;\n SumEven:=((n+1)*(n div 2) ) div 2;\n Result:= SumOdd - SumEven; \n end; \n //f:= Result; \nend;\n\nbegin\n readln(n);\n writeln(f(n));\n //readkey()\nend.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:18:45.190",
"Id": "249236",
"ParentId": "249231",
"Score": "0"
}
},
{
"body": "<p>As far as we discussed it, this is the most efficient answer found:</p>\n<pre><code>program A486;\nuses wincrt, sysutils;\n\nvar\n n: LongInt;\n\nfunction f(n : LongInt): LongInt;\n//var\n //Result : LongInt;\nbegin\n Result:=0; \n if n mod 2 = 0 then\n Result:= n div 2\n else \n Result:= (n div 2) - n;\n\n //f:= Result; \nend;\n\nbegin\n readln(n);\n writeln(f(n));\n //readkey()\nend. \n</code></pre>\n<p>thanks for everyone helped!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T22:31:01.710",
"Id": "488473",
"Score": "1",
"body": "It might not speed up your code but you could rewrite that whole if statement as -1^(n % 2) * ceiling(n / 2)\n\nThe pattern to your problem is that results go -1, 1, -2, 2, -3, 3, ... -roundUp(n / 2), roudUp(n / 2). Odd numbers mod 2 are always 1 and even numbers mod 2 are 0 so -1^(n mod 2) will keep alternating the negative sign for you and roundUp(n / 2) gives you the int value at each step"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T17:41:19.383",
"Id": "489590",
"Score": "1",
"body": "how about `Result := (n shr 1) - n * (n and 1);`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:36:49.977",
"Id": "249238",
"ParentId": "249231",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249235",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:27:09.710",
"Id": "249231",
"Score": "2",
"Tags": [
"algorithm",
"time-limit-exceeded",
"mathematics",
"delphi",
"object-pascal"
],
"Title": "Efficiently calculate the value of an arithmetic sequence"
}
|
249231
|
<p>While I know that Shaders are often made with glsl or hlsl because that is want those languages were made for I wanted to see if there was another way to accomplish Shaders while also using the GPU. as a result I decided to use CUDA for the Shaders and win32 for the actual window. also most of the Shaders were ported from shader-toy so that is why they look different compared to the rest of the code.</p>
<p><code>main.cu</code></p>
<pre><code>/* standard headers */
#include <cstdint>
#include <cstddef>
/* windows headers */
#include <windows.h>
/* cuda headers */
#include <cuda_runtime.h>
/* glm headers */
#define GLM_FORCE_SWIZZLE
#include <glm/glm.hpp>
/* project headers */
#include "shaders.cuh"
/* global variables */
namespace
{
constexpr std::uint32_t width = 1920 / 2;
constexpr std::uint32_t height = 1080 / 2;
constexpr std::int64_t milliseconds_in_a_second = 1000;
bool running = true;
std::uint32_t *image = nullptr;
std::uint32_t *device_image = nullptr;
HBITMAP bitmap = nullptr;
HBITMAP old_bitmap = nullptr;
HDC bitmap_device_context = nullptr;
std::uint32_t window_width;
std::uint32_t window_height;
dim3 const threadsPerBlock{ 32, 32 };
dim3 numBlocks = { 0 };
}
void initialize_globals(HWND window_handle)
{
/* get window rect */
RECT rect;
GetClientRect(window_handle, &rect);
/* get the window width and height */
window_width = rect.right - rect.left;
window_height = rect.bottom - rect.top;
/* calculate the number of blocks and also use ceil rounding */
numBlocks = dim3{ (window_width + threadsPerBlock.x - 1) / threadsPerBlock.x, (window_height + threadsPerBlock.x - 1) / threadsPerBlock.y };
/* create a DIB */
HDC const temp_hdc = CreateCompatibleDC(nullptr);
BITMAPINFO bitmap_info = { 0 };
bitmap_info.bmiHeader.biSize = sizeof(bitmap_info);
bitmap_info.bmiHeader.biWidth = window_width;
bitmap_info.bmiHeader.biHeight = window_height;
bitmap_info.bmiHeader.biPlanes = 1;
bitmap_info.bmiHeader.biBitCount = 32;
bitmap_info.bmiHeader.biCompression = BI_RGB;
bitmap_info.bmiHeader.biSizeImage = 0;
bitmap = CreateDIBSection(temp_hdc, &bitmap_info, DIB_RGB_COLORS, reinterpret_cast<void **>(&image), nullptr, 0);
bitmap_device_context = CreateCompatibleDC(nullptr);
old_bitmap = static_cast<HBITMAP>(SelectObject(bitmap_device_context, bitmap));
/* allocate memory for the image on the device */
cudaMalloc(&device_image, sizeof(std::uint32_t) * window_width * window_height);
/* cleanup */
DeleteDC(temp_hdc);
}
void cleanup_globals()
{
SelectObject(bitmap_device_context, old_bitmap);
DeleteDC(bitmap_device_context);
DeleteObject(bitmap);
}
void blt_bitmap(HWND const window_handle, HDC const device_context)
{
BitBlt(device_context, 0, 0, window_width,
window_height, bitmap_device_context, 0, 0, SRCCOPY);
}
std::int64_t milliseconds_now()
{
static LARGE_INTEGER frequency;
static bool use_qpc = QueryPerformanceFrequency(&frequency);
if (use_qpc)
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (milliseconds_in_a_second * now.QuadPart) / frequency.QuadPart;
}
else
{
return GetTickCount();
}
}
LRESULT CALLBACK WinProc(HWND window_handle, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_PAINT:
{
/* redraw the screen */
PAINTSTRUCT ps;
HDC hdc = BeginPaint(window_handle, &ps);
blt_bitmap(window_handle, hdc);
EndPaint(window_handle, &ps);
} break;
case WM_CREATE:
{
initialize_globals(window_handle);
} break;
case WM_QUIT:
case WM_CLOSE:
case WM_DESTROY:
{
running = false;
PostQuitMessage(0);
} break;
default:
{
return DefWindowProcA(window_handle, message, wParam, lParam);
} break;
}
return 0;
}
template<typename T>
__global__
void generate_image_kernel(std::uint32_t *const image, std::uint32_t const image_width, std::uint32_t const image_height, float time, T pixel_function)
{
std::uint32_t x = threadIdx.x + blockIdx.x * blockDim.x;
std::uint32_t y = threadIdx.y + blockIdx.y * blockDim.y;
/* check if y or x is out of bounds */
if (x >= image_width || y >= image_height) return;
glm::u8vec3 const pixel_color{ glm::round(glm::clamp(pixel_function(glm::vec2{x, y}, glm::vec2{image_width, image_height}, time), 0.0f, 1.0f) * 255.0f) };
image[y * image_width + x] = pixel_color.r << 16 | pixel_color.g << 8 | pixel_color.b;
}
template<typename T>
void generate_image(float time, T &&pixel_function)
{
generate_image_kernel <<< numBlocks, threadsPerBlock >>>(device_image, window_width, window_height, time, std::forward<T>(pixel_function));
}
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
/* create a window class */
WNDCLASSEXA wndclassex = { };
wndclassex.cbSize = sizeof(wndclassex),
wndclassex.style = CS_HREDRAW | CS_VREDRAW,
wndclassex.lpfnWndProc = &WinProc,
wndclassex.cbClsExtra = 0,
wndclassex.cbWndExtra = 0,
wndclassex.hInstance = hInstance,
wndclassex.hIcon = LoadIconA(hInstance, IDI_APPLICATION),
wndclassex.hCursor = LoadCursorA(nullptr, IDC_ARROW),
wndclassex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND),
wndclassex.lpszMenuName = nullptr,
wndclassex.lpszClassName = "Class Name",
wndclassex.hIconSm = LoadIconA(hInstance, IDI_APPLICATION);
if (RegisterClassExA(&wndclassex) == 0)
{
ExitProcess(GetLastError());
}
else
{
/* create a window */
HWND window_handle = CreateWindowA(wndclassex.lpszClassName,
"This is the title of the window",
WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME ^ WS_MAXIMIZEBOX, /* we don't want resizing */
CW_USEDEFAULT, CW_USEDEFAULT,
width, height,
nullptr, nullptr,
hInstance, nullptr);
if (window_handle == nullptr)
{
ExitProcess(GetLastError());
}
else
{
/* start timers */
std::uint64_t start_time = milliseconds_now();
/* get device context */
HDC device_context = GetDC(window_handle);
/* show the window */
ShowWindow(window_handle, SW_SHOWDEFAULT);
/* setup */
UpdateWindow(window_handle);
MSG msg;
for (;;)
{
if (PeekMessageA(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageA(&msg);
if (msg.message == WM_QUIT) running = false;
}
/* exit the loop if we are no longer running */
if (running == false) break;
{
std::uint64_t elapsed_time = milliseconds_now() - start_time;
float time = elapsed_time/(float)milliseconds_in_a_second;
/* generate the image */
generate_image(time, [=] __device__(auto const &coords, auto const &res, auto const &time) {
return + shader::one_way_trip(coords, res, time);
});
/* copy the memory from the device to the host */
cudaMemcpy(image, device_image,
sizeof(std::uint32_t) * window_width * window_height, cudaMemcpyDeviceToHost);
blt_bitmap(window_handle, device_context);
}
}
/* cleanup and exit */
ReleaseDC(window_handle, device_context);
cleanup_globals();
DestroyWindow(window_handle);
UnregisterClassA(wndclassex.lpszClassName, hInstance);
ExitProcess(msg.message);
}
}
}
</code></pre>
<p><code>shaders.cuh</code></p>
<pre><code>#pragma once
/* note: most of these are from shader toy */
namespace shader
{
/* while glm already has glm::pow for vec3 it does not seem to work for nvcc with -std=c++17 enabled */
namespace detail
{
__device__ glm::vec3 pow(glm::vec3 const &base, glm::vec3 const &exponent)
{
return { ::pow(base.x, exponent.x), ::pow(base.y, exponent.y), ::pow(base.z, exponent.z) };
}
}
__device__ glm::vec3 one_way_trip(glm::vec2 const &coords, glm::vec2 res, float iTime)
{
using namespace glm;
// -------------------------------------------------------------------------------------------
// "ONE WAY TRIP" by PVM
// Shadertoy version of our 4k intro entry for Evoke 2019
// Code: Kali
// Music: Uctumi
// NOTE: Rewind the shader after it starts to correct audio sync
// -------------------------------------------------------------------------------------------
// Original code without optimizations for the 4k intro and including PVM logo
// global variables
float det = .005f, fin = 0.f, time; // raymarching threshold, aux variable
const float maxdist = 60.f; // max distance for raymarching
vec3 ldir = vec3(0.f, 1.f, 4.f); // light direction (without normalization)
vec3 fcol; // global for coloring
vec3 suncol = vec3(2.f, 1.f, .6f); // sun color
// 2D rotation functions
auto rot2D = [](float a) {
float s = sin(a);
float c = cos(a);
return mat2(c, s, -s, c);
};
// A version with degrees used when designing the logo
auto rot2Ddeg = [](float a) {
a = radians(a);
float s = sin(a);
float c = cos(a);
return mat2(c, s, -s, c);
};
// -------------------------------------------------------------------------------------------
// PVM LOGO
// 2D rectangle with a tilt distortion value
auto rect = [](vec2 p, vec2 b, float inc) {
p.x += p.y * inc;
vec2 d = abs(p) - b;
return length(max(d, vec2(0))) + min(max(d.x, d.y), 0.0f);
};
// 2D triangle function by iq (I think)
auto tri = [&](vec2 p, vec2 q, float ang) {
p = p * rot2Ddeg(ang);
p.x = abs(p.x);
vec2 a = p - q * clamp(dot(p, q) / dot(q, q), 0.0f, 1.0f);
vec2 b = p - q * vec2(clamp(p.x / q.x, 0.0f, 1.0f), 1.0f);
float s = -sign(q.y);
vec2 d = min(vec2(dot(a, a), s * (p.x * q.y - p.y * q.x)),
vec2(dot(b, b), s * (p.y - q.y)));
return -sqrt(d.x) * sign(d.y);
};
// Here the logo is constructed from distoted rectangles and triangles
auto logo = [&](vec2 uv) {
uv *= 1.2f;
uv.x *= 1.15f;
uv.y -= .6f;
uv.x -= 1.3f;
float d = rect(uv, vec2(.045, .25), -.5f);
uv.x += .25f;
uv.y += .01f;
d = min(d, rect(uv, vec2(.045, .24), .5f));
uv.x += .265f;
uv.y -= .04f;
d = min(d, rect(uv, vec2(.045, .2), -.55f));
uv.x -= .73f;
uv.y -= .06f;
d = min(d, rect(uv, vec2(.045, .16), .4f));
uv.x -= .105f;
uv.y += .074f;
d = min(d, rect(uv, vec2(.045, .085), -.45f));
uv.x -= .105f;
uv.y += .045f;
d = min(d, rect(uv, vec2(.045, .13), .45f));
uv.x -= .25f;
uv.y += .1f;
d = min(d, rect(uv, vec2(.18, .03), .0f));
uv.x += 1.32f;
uv.y -= .18f;
d = min(d, rect(uv + vec2(0.0f, .03f), vec2(.35f, .03f), .0f));
uv.x -= .5165f;
uv.y += .4f;
d = min(d, tri(uv, vec2(.09, .185), 0.f));
uv.x -= .492f;
uv.y -= .56f;
d = min(d, tri(uv, vec2(.063, .14), 180.f));
uv.x += .225f;
uv.y -= .17f;
d = min(d, tri(uv, vec2(.063, .145), 180.f));
uv.x -= .142f;
uv.y += .555f;
d = min(d, tri(uv, vec2(.063, .145), 0.f));
uv.x += .985f;
uv.y += .075f;
vec2 uvd = uv - vec2(uv.y, 0.f);
d = min(d, tri(uvd - vec2(0.003, 0.022), vec2(.04, .05), 0.f));
uv.x -= .16f;
uv.y -= .63f;
uvd = uv + vec2(uv.y * .4f, 0.f);
d = min(d, tri(uvd + vec2(.03f, 0.f), vec2(.07, .23), -145.f));
uvd = uv + vec2(.465f, .33f);
uvd = uvd * rot2Ddeg(27.f);
uvd -= vec2(uvd.y * .5f * sign(uvd.x), 0.);
d = min(d, rect(uvd, vec2(.08f, .03f), .0f));
uvd = uv + vec2(-1.43f, .534f);
uvd = uvd * rot2Ddeg(206.f);
uvd -= vec2(uvd.y * .5f * sign(uvd.x), 0.f);
d = min(d, rect(uvd, vec2(.08f, .03f), .0f));
float s = pow(abs(d) + .9f, 10.f);
uvd = uv + vec2(-.28f, .36f);
uvd = uvd * rot2Ddeg(50.f);
d = max(d, -rect(uvd, vec2(.1f, .025f), .0f));
// logo coloring, RGBA
float o = 1.f - smoothstep(0.f, .01f, d);
float l = 1.f - smoothstep(0.f, .05f, d);
vec3 col = mix(vec3(2.f, .15f, .1f), vec3(1.f, 2.f, .5f), min(1.f, abs(uv.y + .4f)));
return vec4(col * o + .1f, l);
};
// -------------------------------------------------------------------------------------------
// FRACTAL
// A bunch of sin and cos that defines the curves of the fractal path
// it returns the displacement at a given point. freq was used to explore diferent scales
auto pitpath = [](float ti) {
float freq = .5f;
ti *= freq;
float x = cos(cos(ti * .35682f) + ti * .2823f) * cos(ti * .1322f) * 1.5f;
float y = sin(ti * .166453f) * 4.f + cos(cos(ti * .125465f) + ti * .17354f) * cos(ti * .05123f) * 2.f;
vec3 p = vec3(x, y, ti / freq);
return p;
};
// Distance Estimation function
auto de = [&](vec3 pos) {
float x = 1.f - smoothstep(5.f, 8.f, abs(pos.x)); // aux variable used for washing the colors away from the path in the fractal
pos.y += .9f; // offset y position for the fractal object
pos.xy -= pitpath(pos.z).xy(); // distortion of coordinates based on the path function
mat2 rot = rot2D(.5f); // rotation matrix used in the fractal iteration loop
float organic = smoothstep(.5f, 1.f, -sin(pos.z * .005f)); // used for the "organic" part of the fractal
mat2 rot2 = rot2D(organic * .4f); // rotation matrix used in the fractal iteration loop, it mutates the fractal to kinda "organic" shapes
float fold = 2.6f + sin(pos.z * .01f) + organic * 1.5f; // fold is a parameter for one of the operations inside the fractal loop
pos.x += pow(organic, .2f) * fold * .75f; // x offset for the organic part
pos.y += organic * .3f; // y offset for the organic part
pos.z = abs(5.f - mod(pos.z, 10.f)); // tiling for repeating the fractal along the z axis
pos.x = abs(10.f - mod(pos.x + 10.f, 20.f)); // tiling for reapeating along x axis
pos.x -= fold; // x offset to center the fractal
vec4 p = vec4(pos, 1.f); // w value will be used for calculating the derivative
vec3 m = vec3(1000.f); // for orbit trap coloring
int it = int(8.f + fin * 2.f); // gives more iterations to the fractal at the end
// Amazing Surface fractal formula by Kali
// Derived from Mandelbox by tglad
for (int i = 0; i < it; i++)
{
p.xz = clamp(p.xz(), -vec2(fold, 2.f), vec2(fold, 2.f)) * 2.0f - p.xz; // fold transform on xz plane
p.xyz -= vec3(.5f, .8, 1.); // translation transform
p = p * (2.f - organic * .2f) / clamp(dot(p.xyz(), p.xyz()), .25f, 1.f) - vec4(2.f, .5f, -1.f, 0.f) * x; // scale + spheric fold + translation transform
// rotation transforms
p.xy = p.xy() * rot;
p.xz = p.xz() * rot2; // rotations on xz and yz give the "organic" feel for the "alien reefs" part
p.yz = p.yz() * rot2;
m = min(m, abs(p.xyz())); // saves the minimum value of the position during the iteration, used for "orbit traps" coloring
}
// fractal coloring (fcol global variable)
fcol = vec3(1.f, .3f, .0f) * m * x;
fcol = max(fcol, length(p) * .0015f * vec3(1.f, .9f, .8f) * (1.f - fin)) * (1.f + organic * .5f);
return (max(p.x, p.y) / p.w - .025f * (1.f - fin)) * .85f; // returns the distance estimation to the fractal's surface, with some adjustment towards the end
};
// -------------------------------------------------------------------------------------------
// RAYMARCHING
// Returns the perpendicular vector to the surface at a given point
auto normal = [&](vec3 p) {
vec3 d = vec3(0.f, det * 2.f, 0.f);
return normalize(vec3(de(p - d.yxx()), de(p - d.xyx()), de(p - d.xxy())) - de(p));
};
// Ambient occlusion and soft shadows, classic iq's methods
auto ao = [&](vec3 p, vec3 n) {
float td = 0.f, ao = 0.f;
for (int i = 0; i < 6; i++)
{
td += .05f;
float d = de(p - n * td);
ao += max(0.f, (td - d) / td);
}
return clamp(1.f - ao * .1f, 0.f, 1.f);
};
auto shadow = [&](vec3 p) {
float sh = 1.f, td = .1f;
for (int i = 0; i < 50; i++)
{
p += ldir * td;
float d = de(p);
td += d;
sh = min(sh, 10.f * d / td);
if (sh < .05f) break;
}
return clamp(sh, 0.f, 1.f);
};
// Lighting
auto shade = [&](vec3 p, vec3 dir, vec3 n, vec3 col) {
float sha = shadow(p);
float aoc = ao(p, n);
float amb = .25f * aoc; // ambient light with ambient occlusion
float dif = max(0.f, dot(ldir, -n)) * sha; // diffuse light with shadow
vec3 ref = reflect(dir, n); // reflection vector
float spe = pow(max(0.f, dot(ldir, ref)), 10.f) * .7f * sha; // specular lights
return col * (amb + dif) + spe * suncol; // lighting applied to the surface color
};
// Raymarching
auto march = [&](vec3 from, vec3 dir, vec3 camdir) {
// variable declarations
vec3 p = from, col = vec3(0.1f), backcol = col;
float totdist = 0.f, d = 0.f, sdet, glow = 0.f, lhit = 1.f;
// the detail value is smaller towards the end as we are closer to the fractal boundary
det *= 1.f - fin * .7f;
// raymarching loop to obtain an occlusion value of the sun at the camera direction
// used for the lens flare
for (int i = 0; i < 70; i++)
{
p += d * ldir; // advance ray from camera pos to light dir
d = de(p) * 2.f; // distance estimation, doubled to gain performance as we don't need too much accuracy for this
lhit = min(lhit, d); // occlusion value based on how close the ray pass from the surfaces and very small if it hits
if (d < det)
{ // ray hits the surface, bye
break;
}
}
// main raymarching loop
for (int i = 0; i < 150; i++)
{
p = from + totdist * dir; // advance ray
d = de(p); // distance estimation to fractal surface
sdet = det * (1.f + totdist * .1f); // makes the detail level lower for far hits
if (d<sdet || totdist>maxdist) break; // ray hits the surface or it reached the max distance defined
totdist += d; // distance accumulator
glow++; // step counting used for glow
}
float sun = max(0.f, dot(dir, ldir)); // the dot product of the cam direction and the light direction using for drawing the sun
if (d < .2f)
{ // ray most likely hit a surface
p -= (sdet - d) * dir; // backstep to correct the ray position
vec3 c = fcol; // saves the color set by the de function to not get altered by the normal calculation
vec3 n = normal(p); // calculates the normal at the ray hit point
col = shade(p, dir, n, c); // sets the color and lighting
}
else
{ // ray missed any surface, this is the background
totdist = maxdist;
p = from + dir * maxdist; // moves the ray to the max distance defined
// Kaliset fractal for stars and cosmic dust near the sun.
vec3 st = (dir * 3.f + vec3(1.3f, 2.5f, 1.25f)) * .3f;
for (int i = 0; i < 10; i++) st = abs(st) / dot(st, st) - .8f;
backcol += length(st) * .015f * (1.f - pow(sun, 3.f)) * (.5f + abs(st.grb()) * .5f);
sun -= length(st) * .0017f;
sun = max(0.f, sun);
backcol += pow(sun, 100.f) * .5f; // adds sun light to the background
}
backcol += pow(sun, 20.f) * suncol * .8f; // sun light
float normdist = totdist / maxdist; // distance of the ray normalized from 0 to 1
col = mix(col, backcol, pow(normdist, 1.5f)); // mix the surface with the background in the far distance (fog)
col = max(col, col * vec3(sqrt(glow)) * .13f); // adds a little bit of glow
// lens flare
vec2 pflare = dir.xy - ldir.xy;
float flare = max(0.f, 1.0f - length(pflare)) - pow(abs(1.f - mod(camdir.x - atan(pflare.y, pflare.x) * 5.f / 3.14f, 2.f)), .6f);
float cflare = pow(max(0.f, dot(camdir, ldir)), 20.f) * lhit;
col += pow(max(0.f, flare), 3.f) * cflare * suncol;
col += pow(sun, 30.f) * cflare;
// "only glow" part (at sec. 10)
col.rgb() = mix(col.rgb(), glow * suncol * .01f + backcol, 1.f - smoothstep(0.f, .8f, abs(time - 10.5f)));
return vec4(col, normdist); // returns the resulting color and a normalized depth in alpha
}; //(depth was going to be used for a postprocessing shader)
// -------------------------------------------------------------------------------------------
// Camera and main function
// I learnt this function from eiffie,
// it takes a direction, a reference up vec3
// and returns the rotation matrix to orient a vector
auto lookat = [&](vec3 dir, vec3 up) {
dir = normalize(dir); vec3 rt = normalize(cross(dir, normalize(up)));
return mat3(rt, cross(rt, dir), dir);
};
// the path of the camera at a given point of time
auto campath = [&](float ti) {
float start = pow(max(0.f, 1.f - ti * .02f), 3.f); // interpolation curve for the starting camera
vec3 p = pitpath(ti); // path displacement of the fractal
p *= 1.f - start; // the camera gradually ends following the fractal when, that happens when start=0
p += vec3(start * 30.f, start * 25.f, 0.f); // position offset for starting camera curve
return p;
};
vec2 uv = coords / res.xy - .5f;
uv.x *= res.x / res.y;
vec3 dir = normalize(vec3(uv, 1.)); // ray direction
time = mod(iTime, 162.f); // time loop
fin = smoothstep(145.f, 147.5f, time); // aux variable used for the end sequence
// camera accelerations and slow downs
float acel1 = smoothstep(11.f, 12.f, time) * 7.31;
float acel2 = smoothstep(99.f, 100.f, time) * 4.;
float desacel1 = smoothstep(77.f, 78.f, time) * 5.;
float desacel2 = fin * 9.5f;
float tt = time;
// freeze BW frame
if (abs(tt - 25.5f) < .5f) tt = 25.f;
float acel = acel1 + acel2 - desacel1 - desacel2;
// time variable
float t = tt * (3.6f + acel) - acel1 * 11.f - acel2 * 99.f + desacel1 * 77.f + desacel2 * 147.5f;
t += smoothstep(125.f, 145.f, time) * 243.f;
vec3 from = campath(t); // camera position
from.y -= desacel2 * .035f; // camera offset on 2nd slow down
vec3 fw = normalize(campath(t + 3.f) - from); // camera forward direction
from.x -= fw.x * .1f; // camera x offset based on the forward direction
dir = dir * lookat(fw * vec3(1.f, -1.f, 1.f), vec3(fw.x * .2f, 1.f, 0.f)); // re-orientation of the ray dir with the camera fwd dir
ldir = normalize(ldir); // light dir normalization
vec4 col = march(from, dir, fw); // get color from raymarching and background
col.rgb() = mix(vec3(length(col.rgb()) * .6f), col.rgb(), .85f - step(abs(tt - 25.f), .1f)); // BW freeze frame sequence coloring
col.rgb() *= 1.f - smoothstep(25.f, 26.f, time) + step(25.1f, tt); // BW freeze frame sequence fading
col.rgb() *= 1.f + step(abs(tt - 25.f), .1f);
// PVM Logo color mixing
vec4 pvm = logo(uv * 1.5f + vec2(.9f, .5f)) * smoothstep(1.f, 3.f, time + uv.x * 2.f) * (1.f - smoothstep(7.5f, 8.f, time + uv.x * 2.f));
col.rgb() = mix(col.rgb(), pvm.rgb(), pvm.a);
// fade in from black
col.rgb() *= smoothstep(0.f, 4.f, time);
// fade out to black
col.rgb() *= 1.f - smoothstep(160.f, 162.f, time);
return col;
}
__device__ glm::vec3 sea_scape(glm::vec2 const &coords, glm::vec2 res, float iTime)
{
using namespace glm;
/*
* "Seascape" by Alexander Alekseev aka TDM - 2014
* License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
* Contact: tdmaav@gmail.com
*/
const int NUM_STEPS = 8;
const float PI = 3.141592f;
const float EPSILON = 1e-4f;
#define EPSILON_NRM (0.1f / res.x)
#define AA
// sea
const int ITER_GEOMETRY = 3;
const int ITER_FRAGMENT = 5;
const float SEA_HEIGHT = 0.6f;
const float SEA_CHOPPY = 4.0f;
const float SEA_SPEED = 0.8f;
const float SEA_FREQ = 0.16f;
const vec3 SEA_BASE = vec3(0.0f, 0.09f, 0.18f);
const vec3 SEA_WATER_COLOR = vec3(0.8f, 0.9f, 0.6f) * 0.6f;
#define SEA_TIME (1.0f + iTime * SEA_SPEED)
const mat2 octave_m = mat2(1.6f, 1.2f, -1.2f, 1.6f);
// math
auto fromEuler = [](vec3 ang) {
vec2 a1 = vec2(sin(ang.x), cos(ang.x));
vec2 a2 = vec2(sin(ang.y), cos(ang.y));
vec2 a3 = vec2(sin(ang.z), cos(ang.z));
mat3 m;
m[0] = vec3(a1.y * a3.y + a1.x * a2.x * a3.x, a1.y * a2.x * a3.x + a3.y * a1.x, -a2.y * a3.x);
m[1] = vec3(-a2.y * a1.x, a1.y * a2.y, a2.x);
m[2] = vec3(a3.y * a1.x * a2.x + a1.y * a3.x, a1.x * a3.x - a1.y * a3.y * a2.x, a2.y * a3.y);
return m;
};
auto hash = [](vec2 p) {
float h = dot(p, vec2(127.1f, 311.7f));
return fract(sin(h) * 43758.5453123f);
};
auto noise = [&](vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0f - 2.0f * f);
return -1.0f + 2.0f * mix(mix(hash(i + vec2(0.0f, 0.0f)),
hash(i + vec2(1.0f, 0.0f)), u.x),
mix(hash(i + vec2(0.0f, 1.0f)),
hash(i + vec2(1.0f, 1.0f)), u.x), u.y);
};
// lighting
auto diffuse = [](vec3 n, vec3 l, float p) {
return pow(dot(n, l) * 0.4f + 0.6f, p);
};
auto specular = [&] (vec3 n, vec3 l, vec3 e, float s) {
float nrm = (s + 8.0f) / (PI * 8.0f);
return pow(max(dot(reflect(e, n), l), 0.0f), s) * nrm;
};
// sky
auto getSkyColor = [](vec3 e) {
e.y = (max(e.y, 0.0f) * 0.8f + 0.2f) * 0.8f;
return vec3(pow(1.0f - e.y, 2.0f), 1.0f - e.y, 0.6f + (1.0f - e.y) * 0.4f) * 1.1f;
};
// sea
auto sea_octave = [&](vec2 uv, float choppy) {
uv += noise(uv);
vec2 wv = 1.0f - abs(sin(uv));
vec2 swv = abs(cos(uv));
wv = mix(wv, swv, wv);
return pow(1.0f - pow(wv.x * wv.y, 0.65f), choppy);
};
auto map = [&](vec3 p) {
float freq = SEA_FREQ;
float amp = SEA_HEIGHT;
float choppy = SEA_CHOPPY;
vec2 uv = p.xz; uv.x *= 0.75f;
float d, h = 0.0f;
for (int i = 0; i < ITER_GEOMETRY; i++)
{
d = sea_octave((uv + SEA_TIME) * freq, choppy);
d += sea_octave((uv - SEA_TIME) * freq, choppy);
h += d * amp;
uv = uv * octave_m; freq *= 1.9f; amp *= 0.22f;
choppy = mix(choppy, 1.0f, 0.2f);
}
return p.y - h;
};
auto map_detailed = [&](vec3 p) {
float freq = SEA_FREQ;
float amp = SEA_HEIGHT;
float choppy = SEA_CHOPPY;
vec2 uv = p.xz; uv.x *= 0.75f;
float d, h = 0.0f;
for (int i = 0; i < ITER_FRAGMENT; i++)
{
d = sea_octave((uv + SEA_TIME) * freq, choppy);
d += sea_octave((uv - SEA_TIME) * freq, choppy);
h += d * amp;
uv = uv * octave_m; freq *= 1.9f; amp *= 0.22f;
choppy = mix(choppy, 1.0f, 0.2f);
}
return p.y - h;
};
auto getSeaColor = [&](vec3 p, vec3 n, vec3 l, vec3 eye, vec3 dist) {
float fresnel = clamp(1.0f - dot(n, -eye), 0.0f, 1.0f);
fresnel = pow(fresnel, 3.0f) * 0.5f;
vec3 reflected = getSkyColor(reflect(eye, n));
vec3 refracted = SEA_BASE + diffuse(n, l, 80.0f) * SEA_WATER_COLOR * 0.12f;
vec3 color = mix(refracted, reflected, fresnel);
float atten = max(1.0f - dot(dist, dist) * 0.001f, 0.0f);
color += SEA_WATER_COLOR * (p.y - SEA_HEIGHT) * 0.18f * atten;
color += vec3(specular(n, l, eye, 60.0f));
return color;
};
// tracing
auto getNormal = [&](vec3 p, float eps) {
vec3 n;
n.y = map_detailed(p);
n.x = map_detailed(vec3(p.x + eps, p.y, p.z)) - n.y;
n.z = map_detailed(vec3(p.x, p.y, p.z + eps)) - n.y;
n.y = eps;
return normalize(n);
};
auto heightMapTracing = [&](vec3 ori, vec3 dir, vec3& p) {
float tm = 0.0f;
float tx = 1000.0f;
float hx = map(ori + dir * tx);
if (hx > 0.0f) return tx;
float hm = map(ori + dir * tm);
float tmid = 0.0f;
for (int i = 0; i < NUM_STEPS; i++)
{
tmid = mix(tm, tx, hm / (hm - hx));
p = ori + dir * tmid;
float hmid = map(p);
if (hmid < 0.0f)
{
tx = tmid;
hx = hmid;
}
else
{
tm = tmid;
hm = hmid;
}
}
return tmid;
};
auto getPixel = [&](vec2 coord, float time) {
vec2 uv = coord / res.xy;
uv = uv * 2.0f - 1.0f;
uv.x *= res.x / res.y;
// ray
vec3 ang = vec3(sin(time * 3.0f) * 0.1f, sin(time) * 0.2f + 0.3f, time);
vec3 ori = vec3(0.0f, 3.5f, time * 5.0f);
vec3 dir = normalize(vec3(uv.xy(), -2.0f)); dir.z += length(uv) * 0.14f;
dir = normalize(dir) * fromEuler(ang);
// tracing
vec3 p;
heightMapTracing(ori, dir, p);
vec3 dist = p - ori;
vec3 n = getNormal(p, dot(dist, dist) * EPSILON_NRM);
vec3 light = normalize(vec3(0.0f, 1.0f, 0.8f));
// color
return mix(
getSkyColor(dir),
getSeaColor(p, n, light, dir, dist),
pow(smoothstep(0.0f, -0.02f, dir.y), 0.2f));
};
// main
float time = iTime * 0.3f;
#ifdef AA
vec3 color = vec3(0.0f);
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
vec2 uv = coords + vec2(i, j) / 3.0f;
color += getPixel(uv, time);
}
}
color /= 9.0f;
#else
vec3 color = getPixel(fragCoord, time);
#endif
// post
return vec3(detail::pow(color, vec3(0.65f)));
}
__device__ glm::vec3 clouds(glm::vec2 const &coords, glm::vec2 res, float time)
{
// Volumetric screamer - Result of an improvised live coding session on Twitch
// LIVE SHADER CODING, SHADER SHOWDOWN STYLE, EVERY TUESDAYS 20:00 Uk time:
// https://www.twitch.tv/evvvvil_
using namespace glm;
float iTime = time;
vec2 z; float tt, b, g = 0., gg = 0., cr; vec3 faceP, cp; vec4 su = vec4(0);
auto smin = [](float d1, float d2, float k) { float h = max(k - abs(d1 - d2), 0.f); return min(d1, d2) - h * h * .25f / k; };
auto smax = [](float d1, float d2, float k) { float h = max(k - abs(-d1 - d2), 0.f); return max(-d1, d2) + h * h * .25f / k; };
auto r2 = [](float r) { return mat2(cos(r), sin(r), -sin(r), cos(r)); };
auto noi = [](vec3 p) {
vec3 f = floor(p), s = vec3(7, 157, 113);
p -= f;
vec4 h = vec4(0, s.yz, s.y + s.z) + dot(f, s);
p = p * p * (3.f - 2.f * p);
h = mix(fract(sin(h) * 43758.5f), fract(sin(h + s.x) * 43758.5f), p.x);
h.xy = mix(h.xz(), h.yw(), p.y);
return mix(h.x, h.y, p.z);
};
auto ferlin = [&](vec3 p) {
float f = 0.f, A = .5f, I;
p.zy() += tt * 2.f;
for (int i = 0; i < 3; i++) I = float(i), f += A / (I + 1.f) * noi(p + I), p = (2.1f + .1f * I) * p;
return f;
};
auto face = [&](vec3 p) {
p -= vec3(0, -12.f + b * 20.f, 0) + sin(p.y * 2.f) * .1f;
p.yz() = r2(1.65f * (1.f - b)) * p.yz();
faceP = p * vec3(1, .7f, 1);
float t = length(faceP) - 4.f - sin(p.y) * .66f;
t = smin(t, length(abs(faceP + vec3(0, -2.5f, -1)) - vec3(2, 0, 0)) - 4.f, 1.f);
vec3 spikeP = p + vec3(0, -3.9f, 2);
spikeP.x = abs(spikeP.x) - 2.f;
spikeP.xy() = r2(-.785f) * spikeP.xy();
spikeP.yz() = r2(-.1785f) * spikeP.yz();
t = smin(t, length(spikeP.xz()) - 2.f + abs(p.x) * .2f, 1.5f);
vec3 eyeP = abs(p - vec3(0, 2, 0));
eyeP.xy() = r2(.6f) * eyeP.xy();
float eyes = max(eyeP.y, (length(abs(faceP + vec3(0, -1.5f, 3.f)) - vec3(1.f, 0, 0)) - 3.f));
t = smax(eyes, t, 1.f);
t = min(t, max(eyeP.y + 4.f, eyes));
t = smax(length(faceP + vec3(0, 2, -2.f + 5.f * b)) - 2.5f, t, .5f);
spikeP.xy() = r2(-.1485f) * spikeP.xy();
spikeP -= vec3(8.f * b, -3, -1);
t = smin(t, length(spikeP.xz()) - 1.f + abs(spikeP.y + 3.f) * .25f, 1.5f);
return t;
};
auto terrain = [&](vec3 p) {
float t = p.y + 5.f + cos(length(p * (.5f)) - b * 15.f - tt * 4.f) * b + noi(p * .07f + 1.f) * 5.f; //WOBBLE: cos(length(p*(.5f))-b*15.-tt*4.)
t = smax(length(p.xz()) - 2.f - b * 6.f, t, 3.f);
t = smin(t, length(p.xz()) - 1.f + (p.y + 15.f - b * 17.f) * .5f, 1.5f);
return t;
};
auto cmp = [&](vec3 p)
{
float t = face(p);
t = smin(t, terrain(p), 2.5f);
vec3 boltP = p;
boltP = abs(boltP - vec3(0, 0, 2)) - 11.f + sin(p.y * 5.f * p.x * .1f + tt * 25.5f) * .05f + 4.f * sin(p.y * .3f - 3.f) + p.y * .2f;//ORIGINAL SHADER IN BONZOMATIC HAD NOISE TEXTURE CALL FOR BETTER LIGHTNING BOLT EFFECT BUT, THIS SHADER BEING GREEDY ENOUGH, I THOUGHT BEST REPLACE WITH BUNCH OF SINS ON SHADERTOY
float bolt = length(boltP.xz()) - .1f; //~Above line on bonzo end should be: abs(boltP-vec3(0,0,2))-11.+texture(texNoise,p.xy*.1+tt*.5f).r*2.+4.*sin(p.y*.3-3)+p.y*.2;
bolt = max(bolt, p.y + 10.f - b * 25.f);
float mouthFlash = max(p.z, length(faceP.xy() - vec2(0, -2)) + 2.f + p.z * .2f * b);
g += 0.1f / (0.1f + bolt * bolt * (1.02f - b) * (40.f - 39.5f * sin(p.y * .2f - b * 8.f)));
gg += 0.1f / (0.1f + mouthFlash * mouthFlash * (1.05f - b) * (40.f - 39.5f * sin(p.z * .3f + tt * 5.f)));
return t;
};
vec2 uv = (coords.xy / res.xy - 0.5f) / vec2(res.y / res.x, 1);
tt = mod(iTime, 62.82f);
b = smoothstep(0.f, 1.f, sin(tt) * .5f + .5f);
vec3 ro = vec3(sin(tt * .5f) * 10.f, mix(15.f, -3.f, b), -20.f + sin(tt * .5f) * 5.f) * mix(vec3(1), vec3(2, 1, cos(tt * .5f) * 1.5f), cos(-tt * .5f + .5f) * .5f + .5f),
cw = normalize(vec3(0, b * 10.f, 0) - ro), cu = normalize(cross(cw, vec3(0, 1, 0))),
cv = normalize(cross(cu, cw)), rd = mat3(cu, cv, cw) * normalize(vec3(uv, .5f)), co, fo;
co = fo = vec3(.1f, .12f, 0.17f) - length(uv) * .1f - rd.y * .2f;
cr = cmp(ro - 3.f) + fract(dot(sin(uv * 476.567f + uv.yx() * 785.951f + tt), vec2(984.156f)));
for (int i = 0; i < 128; i++)
{
cp = ro + rd * (cr += 1.f / 2.5f);
if (su.a > .99f) break; //NOTE TO SELF: cr>t NOT NEEDED AS ONLY VOLUMETRIC GEOM ARE PRESENT
float de = clamp((-cmp(cp) * 9.f + 8.f * ferlin(cp)) / 8.f, 0.f, 1.f);
su += vec4(vec3(mix(1.f, 0.f, de) * de), mix(.07f, de, exp(-.00001f * cr * cr * cr))) * (1.f - su.a);//FOG ON CLOUDS! mix(.07,de,exp(-.00001*cr*cr*cr))
}
co = mix(co, su.xyz(), su.a);
return glm::vec3(detail::pow(co + g * .4f * vec3(.5f, .2f, .1f) + gg * .4f * vec3(.1f, .2f, .5f), vec3(.55f)));
}
__device__ glm::vec3 mandelbrot(glm::vec2 const &coords, glm::vec2 const &res, float time)
{
constexpr std::uint32_t max_iterations = 200;
constexpr float bailout = 200000.0f;
/* get uv coords */
glm::vec2 uv = (coords - 0.5f * res) / res.y * 4.0f * sin(time) - glm::vec2{cos(time) * 1.35f, 0.0f};
glm::vec2 z = {};
/* iterate z = z ^ 2 +c until abs(z) > bailout */
std::uint32_t i;
for (i = 0; i < max_iterations; ++i)
{
/* exit the loop if z has escaped */
if (glm::dot(z, z) >= bailout) break;
z = glm::vec2{ z.x * z.x - z.y * z.y, z.x * z.y * 2.0f } + uv;
}
float smooth_color = sqrtf(((float)i - log2f(logf(glm::dot(z, z)) / logf(bailout))) / (float)max_iterations);
return glm::sin(20.0f * smooth_color * glm::vec3{ 1.5f, 1.8f, 2.1f } + time) * 0.5f + 0.5f;
}
__device__ glm::vec3 paper_pattern(glm::vec2 const &coords, glm::vec2 const &res, float iTime)
{
/*
Geometric Paper Pattern
-----------------------
A geometric pattern rendered onto some animated hanging paper, which for some
inexplicable and physics defying reason is also animated. :D
I put this together out of sheer boredom, and I didn't spend a lot of time on
it, so I wouldn't look too much into the inner workings, especially not the
physics aspects... I honestly couldn't tell you why the paper is waving around
like that. :)
The pattern is about as basic as it gets. I've used some equally basic post
processing to give it a slightly hand drawn look. The pencil algorithm I've
used is just a few lines, and is based on one of Flockaroo's more sophisticated
examples. The link is below, for anyone interested. At some stage, I'd like
to put a sketch algorithm out that is more hatch-like.
On a side note, for anyone who likes small functions, feel free to take a look
at the "n2D" value noise function. I wrote it ages ago (also when I was bored)
and have taken it as far as I can take it. However, I've often wondered whether
some clever soul out there could write a more compact one.
Related examples:
// A more sophisticated pencil sketch algorithm.
When Voxels Wed Pixels - Flockaroo
// https://www.shadertoy.com/view/MsKfRw
*/
using namespace glm;
// For those who find the default pattern just a little too abstract and minimal,
// here's another slighly less abstract minimal pattern. :D
//#define LINE_TRUCHET
// I felt the pattern wasn't artistic enough, so I added some tiny holes. :)
#define HOLES
#define LINE_TRUCHET
// Standard 2D rotation formula.
auto rot2 = [](float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); };
// IQ's vec2 to float hash.
auto hash21 = [](vec2 p) { return fract(sin(dot(p, vec2(27.619f, 57.583f))) * 43758.5453f); };
// IQ's box formula -- modified for smoothing.
auto sBoxS = [](vec2 p, vec2 b, float rf) {
vec2 d = abs(p) - b + rf;
return min(max(d.x, d.y), 0.f) + length(max(d, 0.f)) - rf;
};
// IQ's box formula.
auto sBox = [](vec2 p, vec2 b) {
vec2 d = abs(p) - b;
return min(max(d.x, d.y), 0.f) + length(max(d, 0.f));
};
// This will draw a box (no caps) of width "ew" from point "a "to "b". I hacked
// it together pretty quickly. It seems to work, but I'm pretty sure it could be
// improved on. In fact, if anyone would like to do that, I'd be grateful. :)
auto lBox = [&](vec2 p, vec2 a, vec2 b, float ew) {
float ang = atan(b.y - a.y, b.x - a.x);
p = rot2(ang) * (p - mix(a, b, .5f));
vec2 l = vec2(length(b - a), ew);
return sBox(p, (l + ew) / 2.f);
};
auto distField = [&](vec2 p) {
// Cell ID and local cell coordinates.
vec2 ip = floor(p) + .5f;
p -= ip;
// Some random numbers.
float rnd = hash21(ip + .37f);
float rnd2 = hash21(ip + .23f);
float rnd3 = hash21(ip + .72f);
// Cell boundary.
float bound = sBox(p, vec2(.5f));
float d = 1e5; // Distance field.
// Random 90 degree cell rotation.
p = p * rot2(floor(rnd * 64.f) * 3.14159f / 2.f);
// Just adding a tiny hole to draw the eye to the... No idea why artists do
// this kind of thing, but it enables them to double the price, so it's
// definitely worth the two second effort. :)
float hole = 1e5;
#ifdef LINE_TRUCHET
// Three tiled Truchet pattern consisting of arc, straight line
// and dotted tiles.
// Four corner circles.
vec2 q = abs(p);
float cir = min(length(q - vec2(0, .5f)), length(q - vec2(.5f, 0)));
if (rnd3 < .75f)
{
if (rnd2 < .65)
{
d = abs(min(length(p - .5f), length(p + .5f)) - .5f) - .5f / 3.f;
}
else
{
p = abs(p) - .5f / 3.f;
d = min(max(p.x, -(p.y - .5f / 8.f)), p.y);
}
}
else
{
// Four dots in the empty squares to complete the pattern.
d = cir - .5f / 3.f;
}
// Corner holes.
hole = cir - .05f;
#else
// Very common quarter arc and triangle Truchet pattern, which is a
// favorite amongst the abstract art crowd.
if (rnd3 < .75f)
{
;
// Corner holes.
hole = length(p - .325f) - .05f;
if (rnd2 < .5f)
{
// Corner quarter circle... Well, it's a full one,
// but it gets cut off at the grid boundaries.
d = length(p - .5f) - 1.f;
}
else
{
// A corner diamond, but we'll only see the triangular part.
p = abs(p - .5f);
d = abs(p.x + p.y) / sqrt(2.f) - .7071f;
}
}
#endif
#ifdef HOLES
d = max(d, -hole);
#endif
// Cap to the cell boundaries. Sometimes, you have to do this
// to stop rendering out of bounds, or if you wish to include
// boundary lines in the rendering.
//
return max(d, bound);
};
// Cell grid borders.
auto gridField = [](vec2 p) {
vec2 ip = floor(p) + .5f;
p -= ip;
p = abs(p);
float grid = abs(max(p.x, p.y) - .5f) - .005f;
return grid;
};
// Cheap and nasty 2D smooth noise function with inbuilt hash function -- based on IQ's
// original. Very trimmed down. In fact, I probably went a little overboard. I think it
// might also degrade with large time values.
auto n2D = [](vec2 p) {
vec2 i = floor(p);
p -= i;
p *= p * (3.f - p * 2.f);
vec4 temp_vec4 = fract(sin(vec4(0, 1, 113, 114) + dot(i, vec2(1, 113))) * 43758.5453f);
return dot(mat2(temp_vec4.xy(), temp_vec4.zw()) * vec2(1.f - p.y, p.y), vec2(1.f - p.x, p.x));
};
// FBM -- 4 accumulated noise layers of modulated amplitudes and frequencies.
auto fbm = [&](vec2 p) { return n2D(p) * .533f + n2D(p * 2.f) * .267f + n2D(p * 4.f) * .133f + n2D(p * 8.f) * .067f; };
auto pencil = [&](vec3 col, vec2 p) {
// Rough pencil color overlay... The calculations are rough... Very rough, in fact,
// since I'm only using a small overlayed portion of it. Flockaroo does a much, much
// better pencil sketch algorithm here:
//
// When Voxels Wed Pixels - Flockaroo
// https://www.shadertoy.com/view/MsKfRw
//
// Anyway, the idea is very simple: Render a layer of noise, stretched out along one
// of the directions, then mix a similar, but rotated, layer on top. Whilst doing this,
// compare each layer to it's underlying greyscale value, and take the difference...
// I probably could have described it better, but hopefully, the code will make it
// more clear. :)
//
// Tweaked to suit the brush stroke size.
vec2 q = p * 4.f;
const vec2 sc = vec2(1, 12);
q += (vec2(n2D(q * 4.f), n2D(q * 4.f + 7.3f)) - .5f) * .03f;
q = q * rot2(-3.14159f / 2.5f);
// I always forget this bit. Without it, the grey scale value will be above one,
// resulting in the extra bright spots not having any hatching over the top.
col = min(col, 1.f);
// Underlying grey scale pixel value -- Tweaked for contrast and brightness.
float gr = (dot(col, vec3(.299f, .587f, .114f)));
// Stretched fBm noise layer.
float ns = (n2D(q * sc) * .64f + n2D(q * 2.f * sc) * .34f);
// Compare it to the underlying grey scale value.
ns = gr - ns;
//
// Repeat the process with a couple of extra rotated layers.
q = q * rot2(3.14159f / 2.f);
float ns2 = (n2D(q * sc) * .64f + n2D(q * 2.f * sc) * .34f);
ns2 = gr - ns2;
q = q * rot2(-3.14159f / 5.f);
float ns3 = (n2D(q * sc) * .64f + n2D(q * 2.f * sc) * .34f);
ns3 = gr - ns3;
//
// Mix the two layers in some way to suit your needs. Flockaroo applied common sense,
// and used a smooth threshold, which works better than the dumb things I was trying. :)
ns = min(min(ns, ns2), ns3) + .5f; // Rough pencil sketch layer.
//ns = smoothstep(0., 1., min(min(ns, ns2), ns3) + .5f); // Same, but with contrast.
//
// Return the pencil sketch value.
return vec3(ns);
};
// Aspect correct screen coordinates.
vec2 uv = (coords - res.xy() * .5f) / res.y;
// Scaling factor.
float gSc = 8.f;
// Smoothing factor.
float sf = 1.f / res.y * gSc;
// Unperturbed coordinates.
vec2 pBg = uv * gSc;
vec2 offs = vec2(fbm(uv / 1.f + iTime / 4.f), fbm(uv / 1.f + iTime / 4.f + .35f));
const float oFct = .04f;
uv -= (offs - .5f) * oFct;
// Scaled perturbed coordinates..
vec2 p = uv * gSc;
// The paper distance field.
vec2 fw = vec2(6, 3);
float bw = 1. / 3.;
float paper = sBoxS(p, fw + bw, .05);
// Mixing the static background coordinates with the wavy offset ones to
// save calculating two functions for various things.
vec2 pMix = mix(p, pBg, smoothstep(0.f, sf, paper));
// Failed experiment with a moving pattern.
//vec2 rnd22 = vec2(hash21(ip + 1.6), hash21(ip + 2.6));
//rnd22 = smoothstep(.9, .97, sin(6.2831*rnd22 + iTime/2.));
//float d = distField(p + rnd22);
// The geometric pattern field.
float d = distField(pMix);
// Canvas pattern square ID.
vec2 ip = floor(p) + .5f;
// Background. Nothing exciting, but theres' a subtle vertical gradient
// to mimic an overhead light, or something to that effect.
vec3 bg = vec3(.9, .82, .74) * .85f;
bg = mix(bg, bg * .9f, -uv.y * .5f + .5f);
// Initialize the scene color to the background.
vec3 col = bg;
// Using the pattern distance field for a subtle background wall overlay.
// Back in the old days (the 90s), you'd reuse whatever you could.
col = mix(col, bg * .92f, 1.f - smoothstep(0.f, sf, d));
col = mix(col, bg * .96f, 1.f - smoothstep(0.f, sf, d + .03f));
// The paper shadow distance field and application.
vec2 shOff = normalize(vec2(1, -3)) * .1f;
float dSh = sBoxS(p - shOff, fw + bw, .05f);
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf * 4.f, dSh)) * .5f);
// Paper rendering.
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf, paper)) * .1f);
col = mix(col, vec3(1), (1.f - smoothstep(0.f, sf, paper + .02f)));
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf, paper + bw)));
/*
// Distance field-based lines on the canvas. I tried a few quick things
// for this example, and unfortunately, not a lot worked, but I've left
// the workings in for anyone who wants to play around with this.
const float lnN = 8.; // Number of concentric pattern lines.
float pat = abs(fract(d*lnN*1. - .5f) - .5f)*2. - .05;
pat = smoothstep(0., sf*lnN*2., pat)*.65 + .35;
*/
// Random animated background color for each square.
float rndC = hash21(ip + .23f);
rndC = sin(6.2831f * rndC + iTime / 2.f);
vec3 sqCol = .55f + .45f * cos(6.2831f * rndC + vec3(0, 1, 2)); // IQ's palette.
col = mix(col, sqCol, (1.f - smoothstep(0.f, sf, paper + bw + .0f)));
// Render a colored Truchet pattern in one of two styles.
// Restrict pattern rendering to the canvas.
d = max(d, (paper + bw));
// IQ's really cool, and simple, palette.
vec3 shCol = .55f + .45f * cos(6.2831f * rndC + vec3(0, 1, 2) + 1.f);
// Subtle drop shadow, edge and coloring.
col = mix(col, bg * .03f, (1.f - smoothstep(0.f, sf * 4.f, d)) * .5f);
col = mix(col, bg * .03f, (1.f - smoothstep(0.f, sf, d)));
col = mix(col, shCol, (1.f - smoothstep(0.f, sf, d + .02f)));
// Adding in some blinking offset color, just to mix things up a little.
rndC = hash21(ip + .87f);
rndC = smoothstep(.8f, .9f, sin(6.2831f * rndC + iTime * 2.f) * .5f + .5f);
vec3 colB = mix(col, col.xzy(), rndC / 2.f);
col = mix(col, colB, 1.f - smoothstep(0.f, sf, paper + bw));
// Putting some subtle layerd noise onto the wall and paper.
col *= fbm(pMix * 48.f) * .2f + .9f;
// Grid lines on the canvas.
float grid = gridField(p);
grid = max(grid, paper + bw);
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf * 2.f, grid)) * .5f);
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf, grid)));
/*
// Circles on the pattern... Too busy looking.
vec3 svC = col/2.;
float cir = length(p - ip) - .1;
cir = max(cir, bord + bw);
col = mix(col, bg*.07, (1. - smoothstep(0., sf, cir)));
//col = mix(col, svC, (1. - smoothstep(0., sf, cir + .02)));
*/
// Recalculating UV with no offset to use with postprocessing effects.
uv = (coords - res.xy * .5f) / res.y;
float canv = smoothstep(0.f, sf * 2.f, (paper + bw));
float canvBord = smoothstep(0.f, sf * 2.f, (paper));
/*
// Corduroy lines... Interesting texture, but I'm leaving it out.
vec2 q3 = mix(uv, p/gSc, 1. - (canvBord));
float lnPat = abs(fract((q3.x - q3.y)*80.) - .5f)*2. - .01;
float frM = smoothstep(0., sf, max(paper, -(paper + bw)));
lnPat = smoothstep(0., sf*80./2., lnPat);
col = mix(col, col*(lnPat*.25 + .75), frM);
*/
// Boring, and admittedly, inefficient hanger and string calculations, etc.
// A lot of it is made up on the spot. However, at the end of the day, this
// is a pretty cheap example, so it'll do.
vec2 q2 = uv;
q2.x = mod(q2.x, 1.f) - .5f;
q2 -= (offs - .5f) * oFct + vec2(0, (3.f + bw * .9f) / gSc);
// String, and string shadow.
float strg = lBox(q2, vec2(0), vec2(0, .5f) - (offs - .5f) * oFct, .002f);
float strgSh = lBox(q2 - shOff * .5f, vec2(0, .04f), vec2(0, .5f) - (offs - .5f) * oFct, .002f);
// Rendering the strings and shadows.
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf / gSc, strgSh)) * .25f);
col = mix(col, vec3(.5f, .4, .3), (1.f - smoothstep(0.f, sf / gSc / 2.f, strg)));
// The little black hangers and corresponding shadow.
float hang = sBoxS(q2, vec2(1, .5f) * bw / gSc, .0);
float hangBk = sBoxS(q2, vec2(1.f + .05f, .5f) * bw / gSc, .0);
float hangBkSh = sBoxS(q2 - vec2(.008, -.004), vec2(1. + .06, .5f) * bw / gSc, .0);
hangBk = max(hangBk, -paper);
hangBkSh = max(hangBkSh, -paper);
float hangSh = sBoxS(q2 - shOff * .1f, vec2(1, .5f) * bw / gSc, .0f);
// Rendering the hangers and shadows.
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf / gSc * 2.f, hangBkSh)) * .5f);
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf / gSc * 2.f, hangSh)) * .35f);
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf / gSc, hangBk)));
col = mix(col, vec3(0), (1.f - smoothstep(0.f, sf / gSc, hang)));
col = mix(col, bg * oFct, 1.f - smoothstep(0.f, sf / gSc, hang + .004f));
// Adding very subtle lighting to the wavy pattern... So subtle that it's
// barely worth the effort, but it's done now. :)
float eps = .01f;
vec2 offs2 = vec2(fbm(uv / 1.f + iTime / 4.f - eps), fbm(uv / 1.f + iTime / 4.f + .35f - eps));
float z = max(dot(vec3(0, 1, -.5f), vec3(offs2 - offs, eps)), 0.f) / eps;
col *= mix(1.f, .9f + z * .1f, 1.f - canvBord);
// Subtle pencel overlay... It's cheap and definitely not production worthy,
// but it works well enough for the purpose of the example. The idea is based
// off of one of Flockaroo's examples.
vec2 q = mix(uv * gSc * 2.f, p, 1.f - (canvBord));
vec3 colP = pencil(col, q * res.y / 450.f);
//col *= colP*.8 + .5f;
col *= mix(vec3(1), colP * .8f + .5f, .8f);
//col = colP;
// Cheap paper grain... Also barely worth the effort. :)
vec2 oP = floor(p / gSc * 1024.f);
vec3 rn3 = vec3(hash21(p), hash21(p + 2.37f), hash21(oP + 4.83f));
vec3 pg = .9f + .1f * rn3.xyz + .1f * rn3.xxx;
col *= mix(vec3(1), pg, 1.f - canv);
// Rough gamma correction.
return glm::vec3(sqrt(max(col, 0.f)));
#undef HOLES
#undef LINE_TRUCHET
}
}
</code></pre>
<p>here is an example of the program:
<a href="https://i.stack.imgur.com/BWrs2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BWrs2.jpg" alt="" /></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T17:30:11.313",
"Id": "249232",
"Score": "2",
"Tags": [
"c++",
"cuda"
],
"Title": "Shaders made with CUDA"
}
|
249232
|
<p>Any one can help me optimise those three functions? I did profiling and timing of my original python file and found that most calls and time duration was because of those three functions.</p>
<p>The three functions are from a text normaliser for text processing. The full python file is available if anyone wants to have a look at the whole script. Thank you</p>
<pre><code> def __rstrip(self, token):
for i in range(5):
if len(token):
if token[-1] in [',', '.', ';', '!', '?', ':', '"']:
token = token[:-1]
else:
break
return token
def __lstrip(self, token):
for i in range(5):
if len(token):
if token[0] in [',', '.', ';', '!', '?', ':', '"', '\'']:
token = token[1:]
else:
break
return token
def __generate_results(self, original, normalised):
words = []
for t in normalised:
if len(t[0]):
words.append(t[0])
text = ' '.join(words)
tokens = []
if len(original):
for t in original:
idx = t[1]
words = []
for t2 in normalised:
if idx == t2[1]:
words.append(t2[0])
display_text = self.__rstrip(t[0])
display_text = self.__lstrip(display_text)
tokens.append((t[0], words, display_text))
else:
tokens.append(('', '', ''))
return text, tokens
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:53:30.087",
"Id": "488457",
"Score": "1",
"body": "Would you mind giving a little more detail concerning the `__lstrip` and `__rstrip` functions? Is the goal of these function to remove the first/last 5 symbols of a token? Because it seems like a weird use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T19:55:26.797",
"Id": "488459",
"Score": "1",
"body": "You need to provide more information about the data structures. For example, how many elements are typically in a `token`? If these sequences are large, your current stripping methods could be quite inefficient (you create a new list with each iteration); but if they are tiny, that might not be a major issue. Or, how large is `normalised` and what type of collection is it? If it's a large list/tuple, repeated `in` checks might be costly, but if it's small or if it's a dict/set, then perhaps that's not the source of trouble. Currently, your question is too abstract."
}
] |
[
{
"body": "<p>Here are some suggestions for general code cleanup. I can't guarantee that any of these changes will improve performance.</p>\n<hr />\n<blockquote>\n<pre><code>if len(xxx):\n</code></pre>\n</blockquote>\n<p>Almost certainly you can replace these with <code>if xxx:</code>. It's not guaranteed to be the same, but almost all types that support <code>len</code> will test false if their length is 0. This includes strings, lists, dicts, and other standard Python types.</p>\n<hr />\n<p>I would turn <code>__rstrip</code> and <code>__lstrip</code> into top-level functions, or at least make them <code>@staticmethod</code>s since they don't use <code>self</code>. <code>__generate_results</code> could be a static method as well.</p>\n<hr />\n<p><code>__rstrip</code> and <code>__lstrip</code> seem to reimplement the functionality of the built-in <code>str.rstrip</code> and <code>str.lstrip</code>. Possibly, you could replace them with</p>\n<pre><code>display_text = t[0].rstrip(',.;!?:"')\ndisplay_text = display_text.lstrip(',.;!?:"\\'')\n</code></pre>\n<p>If it's really important that at most 5 characters be stripped, you can do that like this:</p>\n<pre><code>def _rstrip(token):\n return token[:-5] + token[-5:].rstrip(',.;!?:"')\n\ndef _lstrip(token):\n return token[:5].lstrip(',.;!?:"\\'') + token[5:]\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>token[-1] in [',', '.', ';', '!', '?', ':', '"']\n</code></pre>\n</blockquote>\n<p>Either <code>token[-1] in {',', '.', ';', '!', '?', ':', '"'}</code> or <code>token[-1] in ',.;!?:"'</code> would be faster. The latter is riskier since it's not exactly the same: it will do a substring test if <code>token[-1]</code> isn't a single character. But if <code>token</code> is a string then <code>token[-1]</code> is guaranteed to be a single character.</p>\n<hr />\n<blockquote>\n<pre><code>words = []\nfor t in normalised:\n if len(t[0]):\n words.append(t[0])\n</code></pre>\n</blockquote>\n<p>You can replace this with <code>words = [t[0] for t in normalised if t[0]]</code>.</p>\n<hr />\n<blockquote>\n<pre><code> words = []\n for t2 in normalised:\n if idx == t2[1]:\n words.append(t2[0])\n</code></pre>\n</blockquote>\n<p>This <em>could</em> be a significant source of inefficiency. You could try making a lookup table outside the loop:</p>\n<pre><code>normalized_lookup = collections.defaultdict(list)\nfor t in normalized:\n normalized_lookup[t[1]].append(t[0])\n</code></pre>\n<p>and then replace the quoted code with <code>words = normalized_lookup[idx]</code>. This could end up being slower, though. Also, it has the side effect that lists for the same value of <code>idx</code> will be shared, which could cause subtle, hard-to-catch aliasing bugs down the line. If that's an issue, write <code>words = list(normalized_lookup[idx])</code> (or <code>tuple</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T23:39:08.003",
"Id": "249251",
"ParentId": "249237",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:25:14.097",
"Id": "249237",
"Score": "-1",
"Tags": [
"python",
"performance",
"python-3.x",
"memory-optimization"
],
"Title": "Optimise python functions for speed"
}
|
249237
|
<p>This is my first modeling exercise on the particle flow. Recently, I read a paper <a href="https://acp.copernicus.org/articles/20/3181/2020/" rel="nofollow noreferrer">https://acp.copernicus.org/articles/20/3181/2020/</a>. After reading the paper, thought of modeling it in Python. It seems like that the model came out well but I am not entirely sure.
Since I don't know how to fit the parameters alpha and beta to the experimental curve. I directly used those values. I am uncertain of the way I used the <strong>call</strong> function. Is there a better way to apply it?</p>
<pre><code>"""
Created on Wed Sep 9 20:08:25 2020
@author: vishal
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class ParticleFlow:
def __init__(self, d, ec, el, rp, rf, g, na):
self.d = d
self.ec = ec
self.el = el
self.rp = rp
self.rf = rf
self.g = g
self.na = na
def __call__(self, v0, t):
def cd():
re = (self.rf*np.linalg.norm(v0, axis = 1)*self.d)/self.na
t = np.zeros(nop)
for i, j in enumerate(re):
t[i] = (24/j)*(1 + 0.15*pow(j,0.681)) + 0.407/(1+(8710/j))
return t
def fg():
fgc = np.zeros(v0.shape)
fgc[:,1] = (np.pi*pow(self.d,3)*self.rp*self.g)/6
return fgc
def fe():
fec = np.zeros(v0.shape)
fec[:,1] = np.pi*pow(self.d,2)*self.ec*self.el
return fec
def fd():
fdc = np.zeros(v0.shape)
fdc [:,0] = -(1/8)*(cd()*self.rf*np.pi*pow(self.d,2)*pow(v0[:,0],2))*np.reciprocal(np.linalg.norm(v0, axis = 1))
fdc [:,1] = -(1/8)*(cd()*self.rf*np.pi*pow(self.d,2)*pow(v0[:,1],2))*np.reciprocal(np.linalg.norm(v0, axis = 1))
return (fdc*v0)
a = np.zeros(v0.shape)
a[:,0] = (6/(np.pi*pow(self.d,3)*rp))*(fg()[:,0] + fe()[:,0] + fd()[:,0])
a[:,1] = (6/(np.pi*pow(self.d,3)*rp))*(fg()[:,1] + fe()[:,1] + fd()[:,1])
return a
class ExplicitEuler:
"""
Euler scheme for the numerical resolution of
a differentiel equation.
"""
def __init__(self,f):
self.f = f
def iterate(self,v0,t,dt):
return v0+dt*self.f(v0,t)
class Integrator:
"""
Integration of a differential equation between tMin and tMax
with N discretization steps and x0 as an initial condition
"""
def __init__(self,method,v0,tMin,tMax,N):
self.v0 = v0
self.tMin = tMin
self.tMax = tMax
self.dt = (tMax - tMin)/(N-1)
self.f = method
def getIntegrationTime(self):
return np.arange(self.tMin,self.tMax+self.dt,self.dt)
def integrate(self):
v = np.array(self.v0)
for t in np.arange(self.tMin,self.tMax,self.dt):
v = np.append( v, self.f.iterate(v[-nop:],t,self.dt),axis=0)
return v
'''
rp: density of particle (quartz)
rf: density of fluid (air)
da: average diameter of particle
sd: SD for the particle size distribution
g: acceleration due to gravity
ec: electric charge
alpha: SD in electric charge
el: electric field
nop: # of particles
'''
rp = 2600
rf = 1.18
da = 132*1e-06
sd = 45*1e-06
g = 9.8
beta = 11000*1e-12
alpha = 1.4*1e-06
vh = 4.95
dim = 2
na = 1.5*1e-05
tmin = 1e-06
tmax = 18e-03
nop = 100
d0 = np.random.normal(da, sd, nop*10)
d0 = np.random.choice(d0[d0 > 0], nop) #to avoid any negative value of diameter
ec0 = np.random.normal(0, alpha, nop)
# a0 = np.zeros((n, dim))
v0 = np.ones(nop)*vh
#v1 = np.array([norm(0, beta/pow(i,2), i) for i in d0])
v1 = np.array([np.random.normal(0, beta/(i**2), 1) for i in d0])[:,0]
#v1 = np.random.normal(0, beta/(d0**2), nop)
vint = np.dstack((v0, v1))[0]
eul = Integrator(ExplicitEuler(ParticleFlow(d0, ec0, 1e05, rp, rf, g, na)),vint,tmin,tmax,2000)
temp = eul.integrate()
'''
Intial positions of particles set to zero
and subsequent positions were calculated by multiplying with velocity.
'''
ri = np.zeros(vint.shape)
r = ri
k = 0
dt = (tmax - tmin)/(2000-1)
lv = len(np.arange(tmin, tmax, dt))
for i in range(lv):
ri = ri + temp[i*nop:(i+1)*nop]*dt
r = np.append(r, ri, axis =0)
#plt.scatter(r[-100:,0], r[-100:,1], c=np.sign(ec0), cmap="bwr", s = np.abs(ec0)*4e07)
#plt.scatter(d0, v1, c = np.sign(ec0), cmap = 'bwr', s = np.abs(ec0)*4e07)
#plt.xlim(d0.min()-1e-05, d0.max()+1e-05)
#plt.ylim(v1.min()-1, v1.max()+1)
#plt.xlabel('y', fontsize = 20)
#plt.ylabel('x', fontsize = 20)
##plt.savefig('position_1.png', dpi = 600, bbox_inches = 'tight')
# animate
fig = plt.figure()
ax = plt.axes(xlim=(r[:,0].min(), r[:,0].max()), ylim=(r[:,1].min(), r[:,1].max()))
particles, = ax.plot([], [], 'o', ms = 2)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.rc('xtick', labelsize=20)
plt.rc('ytick', labelsize=20)
#plt.xlabel(r'x',fontsize=20)
#plt.ylabel(r'$y$', fontsize=20)
def init(): # initialize animation
particles.set_data([], [])
return particles,
def animate(i): # define animation Euler
particles.set_data(r[i*nop:(i+1)*nop,0], r[i*nop:(i+1)*nop,1])
return particles,
anim=animation.FuncAnimation(fig, animate, init_func=init, frames = 2000, interval=2,blit=True,repeat=False)
#anim.save('Particle_flow_1000.mp4',fps=200,dpi=400)
'''
scatter plot to give different colors
based on the polarity of the charge
'''
# scatter
def PlotScatter(i, r):
plt.figure()
plt.ioff()
plt.axes(xlim=(r[:,0].min(), r[:,0].max()), ylim=(r[:,1].min(), r[:,1].max()))
plt.scatter(r[i*nop:(i+1)*nop, 0], r[i*nop:(i+1)*nop,1], c=np.sign(ec0),
cmap="bwr", s = np.abs(ec0)*4e07)
plt.savefig('{}'.format(i), dpi = 200, bbox_inches = 'tight')
plt.clf()
plt.cla()
plt.close()
i = 0
while i <= lv:
PlotScatter(i, r)
i = i + 50
</code></pre>
|
[] |
[
{
"body": "<p><strong>TLDR: Vectorize and eliminate redundant calculations. Rewriting most of your code gave a 400-500x speed up</strong></p>\n<p>Also, use functions and name your variables in ways that people can read</p>\n<p><strong>Long version:</strong></p>\n<ol>\n<li>Legibility</li>\n</ol>\n<p>The code in <code>ParticleFlow</code>, <code>ExplicitEuler</code>, and <code>Integrate</code> was well organize but slow and hard to follow. The variable names were cryptic. They get repeated in different functions with different meanings. Method parameters and global variables are intermixed randomly. And one case a variable is created, explicitly passed through 4 functions, and then thrown away without ever being using.</p>\n<p>If there hadn't been an academic paper for reference I don't think I could have figured out what was happening beyond something is getting integrated.</p>\n<p>Then the second half of the code was hard to follow because organizing functions and comments suddenly vanish. For example:</p>\n<pre><code>for i in range(lv):\n ri = ri + temp[i*nop:(i+1)*nop]*dt\n r = np.append(r, ri, axis =0)\n</code></pre>\n<p>Is there without any explanation of what it does or why. What is <code>temp</code> and why is it getting sliced between <code>i*nop</code> and <code>(i+1)*nop</code>? In the rewrite I tried to give examples of better naming and structure so I'll stop harping on legibility now and move on the the interesting stuff of</p>\n<ol start=\"2\">\n<li>Performance</li>\n</ol>\n<p>Once I read through the paper the code was based on on I could follow the gist of what it calculates and it found it does so pretty inefficiently. Running on my laptop it takes about 3.4 seconds to use Euler's Method to approximate the solution for 100 particles. The rewrite below does the exact same thing in 0.007 seconds.</p>\n<p>The major performance issues are that you repeat calculations based on static variables hundreds/thousands of times and you repeat them in the slowest way possible so your method has to slog through the same number crunching again and again and again.</p>\n<p>Look at <code>cd()</code>:</p>\n<pre><code> def cd():\n re = (self.rf*np.linalg.norm(v0, axis = 1)*self.d)/self.na\n t = np.zeros(nop)\n for i, j in enumerate(re):\n t[i] = (24/j)*(1 + 0.15*pow(j,0.681)) + 0.407/(1+(8710/j))\n return t\n</code></pre>\n<p>The beauty of numpy is that it lets you performed vectorized calculations entire arrays at once. That for loop isn't doing anything that couldn't be written in one line. And once you start using vectorized results you can strip out the overhead of creating empty <code>N</code>-length vectors (or rather <code>nop</code>-length, an ambiguously named global variable defined halfway down) and filling it element-by-element every iteration. Vectorize whatever you can. It'll give roughly an order of magnitude speedup for free.</p>\n<pre><code>def fe():\n fec = np.zeros(v0.shape)\n fec[:,1] = np.pi*pow(self.d,2)*self.ec*self.el\n return fec\n</code></pre>\n<p>Is better but you're still creating things inefficiently. <code>np.zeros(v0.shape)</code> could be <code>np.zeros_like(v0)</code>. You're only using values in <code>fec[:,1]</code> but are creating a 2D array to hold them.\nBut, the thing that really kills efficiency: You go through the whole process of creating an unnecessarily large array, putting some values in it, and then returning it <em>4,000 separate times for the same result</em>.</p>\n<p>The differential equation you're approximating a solution to only depends on the variable <code>V</code>. Everything in <code>fg</code> is a constant defined at run time. That whole function can be rewritten as a single line that gets run once on initialization and saved:</p>\n<pre><code>self.fe = np.pi*pow(self.p.d, 2)*self.p.ec*self.env.el\n</code></pre>\n<p>Cutting out out almost a million operations (2D array x 100 elements x 4000 calls = 800,000 allocations) just for the empty array. If you increase the number of particles it saves even more. I can see how you copied the equations from the article but pay attention to what changes and what does to see what you can calculate once and save.</p>\n<p>This next example I'm not sure sped anything up much but highlights a way of thinking that can help save time in the long run. You wrote <code>ExplicitEuler</code> as a class:</p>\n<pre><code>class ExplicitEuler:\n """\n Euler scheme for the numerical resolution of \n a differentiel equation.\n """\n def __init__(self,f):\n self.f = f\n\n def iterate(self,v0,t,dt):\n return v0+dt*self.f(v0,t)\n</code></pre>\n<p>When you look at the code that runs it though it becomes apparent that again, nothing it does ever changes. There's no actual state being used. When you start looking for bits and pieces like that you can realize that all you actually want from it is an interface to define a specific function composition (a function using a function). You don't need a class with initialization and methods to do that. You can use a simple function:</p>\n<pre><code>def ExplicitEuler(func):\n def f(v, dt):\n return v+dt*func(v)\n return f\n</code></pre>\n<p>Same thing with <code>Integrator</code>. It gets passed some variables once and returns a single result. You don't need a class for it. You can even change them both to functions still keep your moneyshot line:</p>\n<pre><code>eul = Integrator(ExplicitEuler(ParticleFlow(d0, ec0, 1e05, rp, rf, g, na)),vint,tmin,tmax,2000)\ntemp = eul.integrate()\n</code></pre>\n<p>Becomes</p>\n<pre><code>vv = Integrate(ExplicitEuler(ParticleFlow(p, e)), p.v0, tmin, tmax, nop)\n</code></pre>\n<p>with just a bit of refactoring.</p>\n<p>You can read through my full rewrite below. There are a few odds and ends I won't go into detail on (grouping variables as tuples, adding some functions to spaghetti code sections, adding human readable names and comments, etc).</p>\n<p>But again, the three big things to pay attention to are: <strong>Vectorization, Redudant/Expensive Calculation, and Legibility</strong></p>\n<p>P.S. There are two lines you might notice I cut completely. When I read the article it stated: > In the horizontal direction, we do not consider forces on the particles and we assumed that the particles travel at the velocity of the wind. < It wasn't entirely clear in your code but you seem to partially calculate horizontal drag on the particles</p>\n<pre><code># author: cmelgreen\n# based on vishal's codereview question at\n# https://codereview.stackexchange.com/questions/249239/modelling-of-partcle-flow-under-electric-field\n\nimport numpy as np\nimport scipy.stats as stats\nfrom collections import namedtuple\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\n\n\n# Setup Particle Arrays and Environemntal Consts\ndef NewParticles(mean, sd, alpha, beta, n):\n # Truncate Norm Dist at 0\n diameter = stats.truncnorm((0 - mean) / sd, np.inf, loc=mean, scale=sd).rvs(n)\n charge = np.random.normal(0, alpha, n)\n velocity_0 = np.random.normal(size=n)*(beta/(diameter**2))\n\n return namedtuple('Particles', 'd ec v0')(diameter, charge, velocity_0)\n\ndef NewEnvironment(rf, na, rp, g, el, vh):\n return namedtuple('Environment', 'rf na rp g vh el')(rf, na, rp, g, vh, el)\n\n\n# Setup DiffEq for Particle motion in given Environment\n# Vectorize as much as possible for performance\nclass ParticleFlow:\n def __init__(self, particles, environment):\n self.p = particles\n self.env = environment\n\n # Create const horizontal velocity array for vectorization\n self.vh = np.zeros_like(particles.d)*self.env.vh\n\n # Forces independent of velocity are constant and only need calcuated once\n self.fg = (np.pi*pow(self.p.d, 3)*self.env.rp*self.env.g)/6\n self.fe = np.pi*pow(self.p.d, 2)*self.p.ec*self.env.el\n\n def __call__(self, v):\n # Drag Coefficient\n def cd(v):\n re = (self.env.rf *\n np.linalg.norm([self.vh, v])*self.p.d)/self.env.na\n return (24/re)*(1 + 0.15*pow(re, 0.681)) + 0.407/(1+(8710/re))\n\n # Drag\n def fd(v):\n return (1/8)*(cd(v)*self.env.rf*np.pi*pow(self.p.d, 2)*pow(v, 2))*np.reciprocal(np.linalg.norm([self.vh, v]))\n\n # Return Total Forces\n return (6/(np.pi*pow(self.p.d, 3)*self.env.rp))*(self.fg + self.fe + fd(v))\n\n\ndef ExplicitEuler(func):\n # Wrap ParticleFlow for Integration\n def f(v, dt):\n return v+dt*func(v)\n return f\n\ndef Integrate(method, v0, tMin, tMax, n):\n dt = (tMax - tMin)/(n-1)\n v = np.zeros((int((tMax - tMin) / dt), n))\n p = np.zeros((2, *v.shape))\n v[0] = v0\n\n # Calculate Integral\n for i in range(1, len(v)):\n v[i] = method(v[i - 1], dt)\n\n return v\n\n# Used solved velocities to create array of Particle positions over time\ndef PositionOverTime(vv, vh, tMin, tMax):\n p = np.zeros((*vv.shape, 2))\n dt = (tMax - tMin) / (len(vv) - 1)\n\n for i in range(1, len(p)):\n p[i, :, 0] = p[i-1, :, 0] + vh*dt\n p[i, :, 1] = p[i-1, :, 1] + vv[i-1]*dt\n\n return p\n\n\ndef GeneratePoints():\n # Bunch of constants that could be passed in as tuples but hardcoded for example\n (rf, na, rp, g, el, vh) = (1.18, 1.5*1e-05, 2600, 9.8, 1e05, 4.95)\n (da, sd, alpha, beta, nop) = (132 * 1e-06, 45 * 1e-06, 1.4 * 1e-06, 11000 * 1e-12, 100)\n (tmin, tmax) = (1e-06, 18e-03)\n\n # Time Setup and Euler Method\n start = time.time()\n\n # Create Environment and Particle Arrays\n e = NewEnvironment(rf, na, rp, g, el, vh)\n p = NewParticles(da, sd, alpha, beta, nop)\n\n # Run Euler Method\n vv = Integrate(ExplicitEuler(ParticleFlow(p, e)), p.v0, tmin, tmax, nop)\n\n end = time.time()\n print("Ran in: ", end - start)\n\n return PositionOverTime(vv, np.ones(nop) * e.vh, tmin, tmax), p.d, p.ec\n\n# Plot the points based on diameter and charge\ndef Plot(p, d, c):\n frames = 99\n interval = 65\n scale = 1.7e6\n alpha = .67\n\n def init():\n return scatter,\n\n def animate(i):\n X = np.c_[p[i, :, 0], p[i, :, 1]]\n scatter.set_offsets(X)\n return scatter,\n\n # Scale marker size array once instead of recalculaing for each frame\n s = (d * scale)\n \n # Setup figure and axes\n fig = plt.figure()\n ax = plt.axes(\n xlim=(p[0, :, 0].min(), p[-1, :, 0].max()),\n ylim=(p[-1, :, 1].min(), p[-1, :, 1].max())\n )\n scatter = ax.scatter(p[1, :, 0], p[1, :, 1], c=c, cmap='bwr', s=s, alpha=alpha)\n\n # Start animation and display\n _ = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=interval, blit=True, repeat=False)\n plt.show()\n\n# Run\nif __name__ == "__main__":\n Plot(*GeneratePoints())\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/hpCW8.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hpCW8.png\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T07:53:32.610",
"Id": "488586",
"Score": "0",
"body": "Thanks a lot @Coupcoup. Yes, I saw that the fg and fe do not change over time... so need to calculate them repeatedly..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T07:58:13.593",
"Id": "488588",
"Score": "0",
"body": "I used `temp` to store velocity at various `dt` steps... and used those to calculate position `r`. The variable naming was really terrible at many places and I invoked variables like `k = 0` but didn't use them... I will keep in mind those things.... and also give proper explanations for the terms..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T08:04:42.100",
"Id": "488590",
"Score": "0",
"body": "I included horizontal drag force on purpose... because according to my knowledge drag force acts opposite to the direction of particle flow, and here I don't see any reason to exclude the drag in horizontal direction... I don't know why the authors excluded them... further if you include horizontal drag much realistic flow is seen..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T08:45:32.390",
"Id": "488594",
"Score": "1",
"body": "https://www.youtube.com/watch?v=FfKRoBn5ISM - This simulation was produced using the code that I provided... you can see clearly that particles disperse both in horizontal and vertical direction...The colors represent polarity and size the amount of electric charge, respectively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:28:24.883",
"Id": "488641",
"Score": "0",
"body": "My guess is the researchers were primarily focused on being able to calculate atmospheric dispersion at scale where overall wind patterns make drag less if a deal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:34:45.243",
"Id": "488642",
"Score": "2",
"body": "And one last thing I forgot to mention was generating the particle distributions! If you check out NewParticles() you'll see how to sample directly from a truncated normal distribution instead of the hack-y sampling and throwing out negatives. I also worked using beta directly into a vectorized sampling function. When you have problems like that generally you can sample from a standard normal dist and then simply multiply the vector by whatever standard deviation you want to reshape it and then add/subtract the mean i.e. doing the opposite of normalization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:58:49.407",
"Id": "488644",
"Score": "0",
"body": "Yes, I saw how you did the distribution for diameter and velocity. Both of these techniques are new to me. I am trying to understand what those functions actually do. Thank you, again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:57:17.217",
"Id": "488656",
"Score": "1",
"body": "After adding horizontal component of drag force. This is the final result\nhttps://youtu.be/0KVvG16CK1k\nTotal time taken was 0.014 sec. Now, I am thinking of adding collision between particles and use momentum conservation for that. Thank you, again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T21:20:07.483",
"Id": "488657",
"Score": "0",
"body": "Great job! If you plan to keep building on it there are a couple little bugs in my code you should fix. First, I missed a negative sign in fd() before the (1/8) so the vertical drag component is flipped. And second I *think* the two places I wrote np.linalg.norm([self.vh, v]) in cd and fd actually calculating a scalar norms for the whole arrays and not point-by-point values. Anywhere vectors are packed in an array/tuple should probably be np.linalg.norm(np.stack((vh.T, v.T), axis=1), axis=1). I ran a quick test and shouldn't impact performance to change. Good luck with the rest of your work!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:04:14.320",
"Id": "488659",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112975/discussion-between-vishal-and-coupcoup)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:50:35.513",
"Id": "249300",
"ParentId": "249239",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "249300",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T18:51:32.570",
"Id": "249239",
"Score": "4",
"Tags": [
"python",
"statistics",
"numerical-methods"
],
"Title": "Modelling of partcle flow under electric field"
}
|
249239
|
<p>I have this code that gets a CSV string from a list of objects where the first row in the string is the object's properties and the rows underneath are the properties values. I then create a <code>MemoryStream</code> of the string so it's about the same as reading from an actual <code>.csv</code> file into a <code>Stream</code>. Is there any way to cutdown on this code and perhaps do more with LINQ?</p>
<pre><code>public class Lead
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
...
List<Lead> leads = new List<Lead>();
Lead lead1 = new Lead();
lead1.FirstName = "Joe";
lead1.MiddleName = "M";
lead1.LastName = "DiFabio";
leads.Add(lead1);
Lead lead2 = new Lead();
lead2.FirstName = "Dave";
lead2.MiddleName = "";
lead2.LastName = "Palacios";
leads.Add(lead2);
Lead lead3 = new Lead();
lead3.FirstName = "Andy";
lead3.MiddleName = "A";
lead3.LastName = "Nevers";
leads.Add(lead3);
List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
string s = string.Join(",", headers);
foreach (Lead lead in leads)
{
List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
string ss = string.Join(",", values);
s = $"{s}\n{ss}\n";
}
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:00:17.073",
"Id": "488466",
"Score": "0",
"body": "Did you try [CsvHelper](https://www.nuget.org/packages/CsvHelper/)? About code improvement, what is more important: compact code or performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:09:22.773",
"Id": "488467",
"Score": "1",
"body": "@aepot Unfortunately I have to use .NET standard. I would be more concerned about performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:10:54.067",
"Id": "488468",
"Score": "0",
"body": "Ok. Please add `Lead` class to the question to make me able to run the code. Btw, CsvHelper targets .NET Standard 2.1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:16:34.120",
"Id": "488469",
"Score": "0",
"body": "One more question. What the purpose of `MemoryStream`? Is it for file writing or is it just for test without saving the result to disk?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:17:54.397",
"Id": "488471",
"Score": "1",
"body": "@aepot I cannot use any third party nuget packages. I am using `MemoryStream` because it's to save the results without saving the result to disk. I need to send this Stream inside of an HTTP request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T04:03:15.587",
"Id": "488481",
"Score": "1",
"body": "Comment because no time for proper review: 1) If performance is priority, avoid LINQ. 2) Factor this into a method taking the target stream and use a StreamWriter to write directly to the stream. 3) Don't forget to consider commas in the output values. Either quote the entire string value containing the comma, escape the character, or drop it. There is no official CSV specification on how this condition should be handled."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T05:16:44.707",
"Id": "488485",
"Score": "0",
"body": "I posted an answer but also if going to http you might want to check out https://stackoverflow.com/a/22834363 as maybe an inspiration of another option depending on the http framework being used."
}
] |
[
{
"body": "<p>Let's do some performance tweaks.</p>\n<p>I will measure the time simply with <code>Stopwatch</code> and first of all I'll cleanup your code to generate proper <strong>CSV</strong> (without reduntant empty lines as initial).</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();\nstring s = string.Join(",", headers) + Environment.NewLine;\n\nforeach (Lead lead in leads)\n{\n List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();\n string ss = string.Join(",", values);\n s += $"{ss}{Environment.NewLine}";\n}\n</code></pre>\n<p><code>Environment.NewLine</code> returns <code>\\r\\n</code> on Windows and <code>\\n</code> on Linux.</p>\n<p>Output will be</p>\n<pre class=\"lang-none prettyprint-override\"><code>FirstName,MiddleName,LastName\nJoe,M,DiFabio\nDave,,Palacios\nAndy,A,Nevers\n</code></pre>\n<p>Looks like CSV :)</p>\n<p>Then to measure performance I'll imagine that you have very large amount of data e.g. 30000 lines. I'll run the test in a loop of 10000 iterations.</p>\n<p><strong>TestOriginal</strong></p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private static string TestOriginal(List<Lead> leads)\n{\n List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();\n string s = string.Join(",", headers) + Environment.NewLine;\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();\n string ss = string.Join(",", values);\n s += $"{ss}{Environment.NewLine}";\n }\n return s;\n}\n</code></pre>\n<p>Let's run.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>Stopwatch sw = new Stopwatch();\nsw.Start();\nstring s = TestOriginal(leads);\nsw.Stop();\nConsole.WriteLine("Original: {0}ms", sw.ElapsedMilliseconds);\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Original: 3162ms\n</code></pre>\n<p>Ugh. :)</p>\n<p>Almost everyone knows that <code>Reflection</code> is slow. Let's somewhat optimize that.</p>\n<p><strong>ReflectionTweak</strong></p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private static string ReflectionTweak(List<Lead> leads)\n{\n PropertyInfo[] properties = typeof(Lead).GetProperties();\n List<string> headers = properties.Select(x => x.Name).ToList();\n string s = string.Join(",", headers) + Environment.NewLine;\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n List<object> values = properties.Select(prop => prop.GetValue(lead)).ToList();\n string ss = string.Join(",", values);\n s += $"{ss}{Environment.NewLine}";\n }\n return s;\n}\n</code></pre>\n<p>Go go go</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>sw.Restart();\nstring sr = ReflectionTweak(leads);\nsw.Stop();\nConsole.WriteLine("Reflection tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sr);\n</code></pre>\n<p>Output with matching the string to original one</p>\n<pre class=\"lang-none prettyprint-override\"><code>Reflection tweak: 3040ms, match: True\n</code></pre>\n<p>Better but still slow</p>\n<p>One more idea - <code>StringBuilder</code>. Afaik, it's the fastest way to build a string (maybe except some <code>unsafe</code>/unmanaged code).</p>\n<p><strong>StringBuilderTweak</strong></p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private static string StringBuilderTweak(List<Lead> leads)\n{\n StringBuilder sb = new StringBuilder();\n PropertyInfo[] properties = typeof(Lead).GetProperties();\n sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));\n }\n return sb.ToString();\n}\n</code></pre>\n<p>Interesting...</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>sw.Restart();\nstring sb = StringBuilderTweak(leads);\nsw.Stop();\nConsole.WriteLine("StringBuilder tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sb);\n</code></pre>\n<p>Output</p>\n<pre class=\"lang-none prettyprint-override\"><code>StringBuilder tweak: 24ms, match: True\n</code></pre>\n<h3>WOW!!!</h3>\n<p>By the way, you may write the output directly to <code>MemoryStream</code> with <code>StreamWriter</code>.</p>\n<p><strong>StreamWriterTweak</strong></p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private static MemoryStream StreamWriterTweak(List<Lead> leads)\n{\n MemoryStream ms = new MemoryStream();\n // Encoding.UTF8 produces stream with BOM, new UTF8Encoding(false) - without BOM\n using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false), 8192, true)) \n {\n PropertyInfo[] properties = typeof(Lead).GetProperties();\n sw.WriteLine(string.Join(",", properties.Select(x => x.Name)));\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n sw.WriteLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));\n }\n }\n ms.Position = 0;\n return ms;\n}\n</code></pre>\n<p>Must be fast too...</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>sw.Restart();\nMemoryStream stream = StreamWriterTweak(leads);\nsw.Stop();\nConsole.WriteLine("StreamWriter tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == Encoding.UTF8.GetString(stream.ToArray()));\n</code></pre>\n<p>Output</p>\n<pre class=\"lang-none prettyprint-override\"><code>StreamWriter tweak: 28ms, match: True\n</code></pre>\n<p>Yes!</p>\n<hr />\n<p><strong>The fastest</strong></p>\n<pre class=\"lang-csharp prettyprint-override\"><code>StringBuilder sb = new StringBuilder();\nPropertyInfo[] properties = typeof(Lead).GetProperties();\nsb.AppendLine(string.Join(",", properties.Select(x => x.Name)));\n\nforeach (Lead lead in leads)\n{\n sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));\n}\nstring s = sb.ToString();\n</code></pre>\n<p>The whole code to reproduce and play more</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>internal class Program\n{\n public static void Main(string[] args)\n {\n List<Lead> leads = new List<Lead>();\n Lead lead1 = new Lead();\n lead1.FirstName = "Joe";\n lead1.MiddleName = "M";\n lead1.LastName = "DiFabio";\n leads.Add(lead1);\n\n Lead lead2 = new Lead();\n lead2.FirstName = "Dave";\n lead2.MiddleName = "";\n lead2.LastName = "Palacios";\n leads.Add(lead2);\n\n Lead lead3 = new Lead();\n lead3.FirstName = "Andy";\n lead3.MiddleName = "A";\n lead3.LastName = "Nevers";\n leads.Add(lead3);\n\n Stopwatch sw = new Stopwatch();\n sw.Start();\n string s = TestOriginal(leads);\n sw.Stop();\n Console.WriteLine("Original: {0}ms", sw.ElapsedMilliseconds);\n sw.Restart();\n string sr = ReflectionTweak(leads);\n sw.Stop();\n Console.WriteLine("Reflection tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sr);\n sw.Restart();\n string sb = StringBuilderTweak(leads);\n sw.Stop();\n Console.WriteLine("StringBuilder tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sb);\n\n //MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s));\n\n sw.Restart();\n MemoryStream stream = StreamWriterTweak(leads);\n sw.Stop();\n Console.WriteLine("StreamWriter tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == Encoding.UTF8.GetString(stream.ToArray()));\n\n Console.ReadKey();\n }\n\n private static string TestOriginal(List<Lead> leads)\n {\n List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();\n string s = string.Join(",", headers) + Environment.NewLine;\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();\n string ss = string.Join(",", values);\n s += $"{ss}{Environment.NewLine}";\n }\n return s;\n }\n\n private static string ReflectionTweak(List<Lead> leads)\n {\n PropertyInfo[] properties = typeof(Lead).GetProperties();\n List<string> headers = properties.Select(x => x.Name).ToList();\n string s = string.Join(",", headers) + Environment.NewLine;\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n List<object> values = properties.Select(prop => prop.GetValue(lead)).ToList();\n string ss = string.Join(",", values);\n s += $"{ss}{Environment.NewLine}";\n }\n return s;\n }\n\n private static string StringBuilderTweak(List<Lead> leads)\n {\n StringBuilder sb = new StringBuilder();\n PropertyInfo[] properties = typeof(Lead).GetProperties();\n sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));\n }\n return sb.ToString();\n }\n\n private static MemoryStream StreamWriterTweak(List<Lead> leads)\n {\n MemoryStream ms = new MemoryStream();\n // Encoding.UTF8 produces stream with BOM, new UTF8Encoding(false) - without BOM\n using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false), 8192, true))\n {\n PropertyInfo[] properties = typeof(Lead).GetProperties();\n sw.WriteLine(string.Join(",", properties.Select(x => x.Name)));\n\n for (int i = 0; i < 10000; i++)\n foreach (Lead lead in leads)\n {\n sw.WriteLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));\n }\n }\n ms.Position = 0;\n return ms;\n }\n\n public class Lead\n {\n public string FirstName { get; set; }\n public string MiddleName { get; set; }\n public string LastName { get; set; }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T22:04:48.320",
"Id": "249247",
"ParentId": "249241",
"Score": "4"
}
},
{
"body": "<p>You could go straight to a Stream. To make this a bit more generic we can create an IFormatProvider and put the CSV code in there</p>\n<pre><code>public class CSVFormatter<T> : IFormatProvider, ICustomFormatter\n{\n // list of converts from types to string\n private static IDictionary<Type, MethodInfo> Converters;\n private static Func<T, string[]> ConvertFunc;\n private static string Header;\n\n static CSVFormatter()\n {\n Converters = typeof(Convert).GetMethods()\n .Where(x => x.Name == nameof(System.Convert.ToString) && x.GetParameters().Length == 1)\n .ToDictionary(x => x.GetParameters()[0].ParameterType, x => x);\n\n var properties = typeof(T).GetProperties();\n ConvertFunc = CreateConvertFunc(properties);\n Header = string.Join(",", properties.Select(x => x.Name)) + Environment.NewLine;\n }\n\n // Creates the Func using Expression Trees to build it on the fly\n private static Func<T, string[]> CreateConvertFunc(PropertyInfo[] properties)\n {\n var parameter = Expression.Parameter(typeof(T), "item");\n var propToStrings = properties.Select<PropertyInfo, Expression>(p =>\n {\n Expression prop = Expression.Property(parameter, p);\n if (Converters.TryGetValue(p.PropertyType, out MethodInfo convertMethod))\n {\n prop = Expression.Convert(prop, typeof(string), convertMethod);\n }\n else if (p.PropertyType != typeof(string))\n {\n prop = Expression.Convert(prop, typeof(string), Converters[typeof(object)]);\n }\n\n var value = Expression.Variable(typeof(string), "value");\n return Expression.Block(new[] { value },\n Expression.Assign(value, prop),\n Expression.Condition(Expression.Equal(value, Expression.Constant(null, typeof(string))),\n Expression.Constant(string.Empty, typeof(string)), value));\n });\n var propValues = Expression.NewArrayInit(typeof(string), propToStrings);\n var func = Expression.Lambda<Func<T, string[]>>(propValues, parameter);\n return func.Compile();\n }\n\n public string Format(string format, object arg, IFormatProvider formatProvider)\n {\n if (format == "Header")\n {\n return Header;\n }\n if (arg is T)\n {\n var item = (T)arg;\n return string.Join(",", ConvertFunc(item)) + Environment.NewLine;\n }\n var formattable = arg as IFormattable;\n if (formattable != null)\n {\n return formattable.ToString(format, formatProvider);\n }\n return arg?.ToString() ?? string.Empty;\n }\n\n\n public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? this : null;\n}\n</code></pre>\n<p>While we do use reflection a bit we use Expression Trees to build up a func. Expression Tree are slow to compile but once compiled they are as fast as native code. I also added in handling if values null and if property isn't a string. If you only have a hand full of options then the expression trees are going to be slower but remember this is cached in a static field so would have the hit once and rest of time would be faster than reflection.</p>\n<p>Now we can implement the Stream class</p>\n<pre><code>public class EnumerableStream<T> : Stream\n{\n private readonly IEnumerator<T> source;\n private readonly IFormatProvider formatProvider;\n private byte[] buffer = new byte[0];\n public EnumerableStream(IEnumerable<T> source, IFormatProvider formatProvider)\n {\n this.source = source.GetEnumerator();\n this.formatProvider = formatProvider;\n // start with header in the buffer\n var customFormatter = formatProvider.GetFormat(typeof(ICustomFormatter)) as ICustomFormatter;\n try\n {\n var header = customFormatter?.Format("Header", null, formatProvider);\n if (!string.IsNullOrWhiteSpace(header))\n {\n this.buffer = Encoding.UTF8.GetBytes(header);\n }\n }\n catch (FormatException)\n {\n // no header so just don't set buffer\n }\n }\n\n public override bool CanRead => true;\n\n public override bool CanSeek => false;\n\n public override bool CanWrite => false;\n\n public override long Length => throw new NotSupportedException();\n\n public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }\n\n public override void Flush()\n {\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n if (buffer == null)\n {\n throw new ArgumentNullException(nameof(buffer));\n }\n if (offset < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(offset));\n }\n if (count < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(count));\n }\n if (buffer.Length - offset < count)\n {\n throw new ArgumentException(nameof(buffer));\n }\n if (count == 0)\n {\n return 0;\n }\n\n var read = 0;\n // read from leftover buffer first\n if (this.buffer.Length > 0)\n {\n if (this.buffer.Length <= count)\n {\n Array.Copy(this.buffer, 0, buffer, offset, this.buffer.Length);\n read = this.buffer.Length;\n this.buffer = new byte[0];\n }\n else\n {\n Array.Copy(this.buffer, 0, buffer, offset, count);\n read = count;\n var newBuffer = new byte[this.buffer.Length - count];\n Array.Copy(this.buffer, count, newBuffer, 0, newBuffer.Length);\n this.buffer = newBuffer;\n }\n }\n\n while (read < count)\n {\n if (this.source.MoveNext())\n {\n var data = Encoding.UTF8.GetBytes(string.Format(this.formatProvider, "{0}", this.source.Current));\n if (data.Length <= count - read)\n {\n Array.Copy(data, 0, buffer, offset + read, data.Length);\n read += data.Length;\n }\n else\n {\n Array.Copy(data, 0, buffer, offset + read, count - read);\n var newBuffer = new byte[data.Length - (count - read)];\n Array.Copy(data, count - read, newBuffer, 0, newBuffer.Length);\n this.buffer = newBuffer;\n read = count;\n }\n }\n else\n {\n return read;\n }\n }\n return read;\n }\n\n\n public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();\n public override void SetLength(long value) => throw new NotSupportedException();\n public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n this.source.Dispose();\n }\n base.Dispose(disposing);\n }\n}\n</code></pre>\n<p>Nothing too fancy going on in the Stream class just looping through the Enumerable and calling the formatter. Only trick is the Array copy and keeping the buffer in sync but that's not too difficult.</p>\n<p>Then to make it easy we can create an extension method on IEnumerable</p>\n<pre><code>public static class EnumerableExtensions\n{\n public static Stream ToCSVStream<TSource>(this IEnumerable<TSource> source)\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n return new EnumerableStream<TSource>(source, new CSVFormatter<TSource>());\n }\n}\n</code></pre>\n<p>Once you have the List of Leads or IEnumerable and can be any just have to call</p>\n<pre><code>leads.ToCSVStream();\n</code></pre>\n<p>Since it's a stream can pass it to any method that is expecting a stream.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T05:15:13.347",
"Id": "249254",
"ParentId": "249241",
"Score": "1"
}
},
{
"body": "<p>@aepot has done a good job of giving you multiple approaches to get the results you need. I can't think of possible faster way than <code>StringBuilder</code> approach when using <code>Reflection</code>. Though these tests have been considered to be more generalized so it can be reused on multiple objects with no extra code required. However, if you really concerned about performance and you have a very maintainable objects that needs to be converted to <code>CSV</code>. You can adjust their models to fit your needs. For instance :</p>\n<pre><code>public class Lead\n{\n public string FirstName { get; set; }\n public string MiddleName { get; set; }\n public string LastName { get; set; }\n}\n</code></pre>\n<p>You can do this :</p>\n<pre><code>public class Lead\n{\n public string FirstName { get; set; }\n \n public string MiddleName { get; set; }\n \n public string LastName { get; set; }\n \n public static string GetCSVHeader()\n {\n return $"FirstName,MiddleName,LastName";\n }\n \n public override string ToString()\n {\n return $"{FirstName},{MiddleName},{LastName}";\n } \n}\n</code></pre>\n<p>Now, you can do this using <code>StringBuilder</code> :</p>\n<pre><code>public string ToCSV(IEnumerable<Lead> leads)\n{\n var sb = new StringBuilder();\n \n sb.AppendLine(Lead.GetCSVHeader());\n\n foreach(var lead in leads)\n {\n sb.AppendLine(lead.ToString());\n }\n\n return sb.ToString();\n}\n</code></pre>\n<p>This would give you the fastest possible performance you can get without <code>Reflection</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:36:00.677",
"Id": "488561",
"Score": "0",
"body": "Good point, but requires specific data model implementation. **Reflection** there called once and then reused `PropertyInfo[]` array. It almost has no performance impact. But string interpolation is 2x faster than `string.Join()` here, I've tested."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T17:04:57.037",
"Id": "249280",
"ParentId": "249241",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249247",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T20:25:49.110",
"Id": "249241",
"Score": "5",
"Tags": [
"c#",
"csv",
"linq"
],
"Title": "Creating a CSV stream from an object"
}
|
249241
|
<p>After blowing up my environment again messing around with installing random programs and packages I decided to write a bash script I can clone from github and use to reinstall everything like I had before</p>
<p>The idea is that I'll be able to keep adding to it as I find more programs to use so that it will always be a stable starting point. Right now it's just a list of whatever I used to reinstall things copy-pasted into a single file.</p>
<p>Do people bother organizing bash scripts? If so what sort of structure do you use? I keep my actual code relatively clean but this whole thing felt like an aside to keep things orderly in the future</p>
<pre><code>echo Email for github?
# get email, assume github username is same and split it off from domain
read email
name=$(echo $email | grep -o '^[^@]*')
mkdir $HOME/GoProjects
mkdir $HOME/GoProjects/src
mkdir $HOME/GoProjects/bin
mkdir $HOME/PyProjects
mkdir $HOME/JSProjects
mkdir $HOME/pemKeys
# basic update and upgrade
sudo apt update && sudo apt -y upgrade
# install Chromium
sudo apt install -y chromium
#install Go
wget https://dl.google.com/go/go1.14.3.linux-amd64.tar.gz
sudo tar xvfz go1.14.3.linux-amd64.tar.gz -C /usr/local/
rm -f go1.14.3.linux-amd64.tar.gz
cat >> $HOME/.profile << EOF
export GOROOT=/usr/local/go
export GOPATH=$HOME/GoProjects
export GOBIN=$HOME/GoProjects/bin
export PATH=$PATH:/usr/local/go:/usr/local/go/bin:$HOME/GoProjects:$HOME/GoProjects/bin
EOF
. $HOME/.profile
go get github.com/lib/pq
# install VScode
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
sudo install -o root -g root -m 644 packages.microsoft.gpg /usr/share/keyrings/
sudo sh -c 'echo "deb [arch=amd64 signed-by=/usr/share/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'
sudo apt install -y apt-transport-https
sudo apt update -y
sudo apt install -y code
rm -f packages.microsoft.gpg
# install postgres
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
RELEASE=$(lsb_release -cs)
echo "deb http://apt.postgresql.org/pub/repos/apt/ ${RELEASE}"-pgdg main | sudo tee /etc/apt/sources.list.d/pgdg.list
sudo apt update -y
sudo apt -y install postgresql-11
sudo apt install -y build-essential
#install docker
sudo apt install -y apt-transport-https ca-certificates curl gnupg2 software-properties-common
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
sudo apt update -y
apt-cache policy docker-ce
sudo apt install -y docker-ce
sudo chmod 666 /var/run/docker.sock
#Add anaconda
sudo apt install -y libgl1-mesa-glx libegl1-mesa libxrandr2 libxrandr2 libxss1 libxcursor1 libxcomposite1 libasound2 libxi6 libxtst6
wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
bash Anaconda3-2020.02-Linux-x86_64.sh -b -p
rm -f Anaconda3-2020.02-Linux-x86_64.sh
sudo apt install -y libpq-dev python3-dev
pip install psycopg2
#Add protobuff compiler and grpc
sudo apt install -y protobuf-compiler
export GO111MODULE=on
go get github.com/golang/protobuf/protoc-gen-go
go get -u google.golang.org/grpc
#Need to add NPM
sudo apt install -y nodejs
sudo apt install -y npm
#setup github
git config --global user.name $name
git config --global user.email $email
git config --global color.ui true
yes "" | ssh-keygen -t rsa -C $email
cat $HOME/.ssh/id_rsa.pub
rm -rf ./SetupDebianDevEnv
</code></pre>
|
[] |
[
{
"body": "<p>First of all, I would suggest using shellcheck when writing bash <a href=\"https://www.shellcheck.net/\" rel=\"noreferrer\">https://www.shellcheck.net/</a>, it will point out many many errors, some trivial and some not so trivial.</p>\n<pre><code>Line 7:\nmkdir $HOME/GoProjects\n ^-- SC2086: Double quote to prevent globbing and word splitting.\n</code></pre>\n<p>Simple enough, if your $HOME has a space in it say, the mkdir won't work as you expect.</p>\n<p>More subtle</p>\n<pre><code>Line 4:\nread email\n^-- SC2162: read without -r will mangle backslashes.\n</code></pre>\n<p>Maybe not a problem for you, but no harm in doing it right.</p>\n<p>You can use shellcheck in editors via plugins etc, there's a cli you can use. Really nice, bash is very easy to make mistakes in as we all know and this will just generally help you.</p>\n<p>Do people organise bash scripts, yes! I've known some old hands who are very skilled with bash. As far as I know there's no consensus on the structure to follow, but generally I think you want to be following good programming guidelines, split things into functions, make it modular, etc. It's good that you have comments, but I think better still to replace the comment with a function with a sensible name which does the part the comment alludes to.</p>\n<p>That being said, what you have is basically as far as I'm concerned one of the canonical applications of a bash script, i.e. not doing much complicated, just running a bunch of commands in order. You probably use it one off infrequently. Is it worth making it any better? Probably not.</p>\n<p>You have no error handling, and various things are hard coded assumptions about the machine you will run this on, your script isn't idempotent, when something does go wrong, when you run it the second time it may have funny results. Idempotency is another good thing to aim for. Is that any of this is missing bad, not really.</p>\n<p>Personally, I don't like bash scripts. I prefer to use a programming language which is a bit more verbose but allows me to be more confident of what I'm doing. For this reason I write my scripts in node or python when I can, as these allow me to accumulate a collection of functions which I find easier to reason about, do error handling with, and externalise configuration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T12:27:12.897",
"Id": "488614",
"Score": "0",
"body": "shellcheck is an excellent suggestion - note to self: should make it a habit"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T22:07:44.777",
"Id": "249248",
"ParentId": "249244",
"Score": "9"
}
},
{
"body": "<p>I think you could benefit from using <a href=\"https://www.ansible.com/\" rel=\"noreferrer\">Ansible</a> in this scenario then you can easily deploy your configuration to other machines and you will have learned a valuable IT skill.</p>\n<p>And rather than use bash scripts, you use yaml configuration files.</p>\n<p>As for your script: there is a fair amount of repetitive code. Rather than repeat the wget or curl, you could gather your sources into an array, then run wget/curl in a loop, because you are performing multiple operations that are similar. Upside: more concise code. Downside: less separation between the various steps. I can understand you did it this way. But if your file grows because you keep adding sources, you'd have to reconsider the approach and start using loops.</p>\n<p>This is something you could have done here too:</p>\n<pre><code>mkdir $HOME/GoProjects\nmkdir $HOME/GoProjects/src\nmkdir $HOME/GoProjects/bin\nmkdir $HOME/PyProjects\nmkdir $HOME/JSProjects\nmkdir $HOME/pemKeys\n</code></pre>\n<p>An array would make sense. As mentioned above, don't forget to quote !</p>\n<p>Same for the apt install, but since you are adding some repo sources, that needs to be done beforehand, and it would require reorganization of your script.</p>\n<p>The other issue is you are downloading specific software versions that will probably be outdated by the time you reinstall your computer. Thus, an <strong>outdated</strong> script becomes less valuable, if you have yet to update or patch your install to have a setup that is current.</p>\n<p>As an example:</p>\n<pre><code>#install Go\nwget https://dl.google.com/go/go1.14.3.linux-amd64.tar.gz\nsudo tar xvfz go1.14.3.linux-amd64.tar.gz -C /usr/local/\nrm -f go1.14.3.linux-amd64.tar.gz\n</code></pre>\n<p>I would use variables instead, so that the package name is defined only once:</p>\n<pre><code>#install Go\ngo_file="go1.14.3.linux-amd64.tar.gz"\nwget "https://dl.google.com/go/$go_file"\nsudo tar xvfz "$go_file" -C /usr/local/\nrm -f "$go_file"\n</code></pre>\n<p>It is a minor change that will make maintenance of this file more manageable.</p>\n<p>Also, you could move the code to dedicated <strong>functions</strong>. That makes it a bit easier to separate the various steps you are performing. Also, you can easily disable certain items by simply commenting out the function call (= changing only 1 line). In fact it would be nice if you could run your script à la carte, it is perfectly possible that you will want to run it again, but discard certain items that are already installed. For instance if your script crashed in the middle and you don't want to waste time reinstalling everything from the beginning, which is wasteful.</p>\n<p>The other benefit of calling functions in sequence, is that you can easily <strong>reorder</strong> them. At some point you may find out that a certain piece of software should or must be installed before another, because of some dependencies.</p>\n<p>I would install software packages from the regular OS repositories whenever possible. Do you really need to install Postgresql from source ?</p>\n<p>I would also avoid PIP and install the Python packages from apt-get instead, unless they are not available for your OS.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:39:58.490",
"Id": "488526",
"Score": "0",
"body": "Agree with everything par the last sentiment - use Pip where necessary to have some capability to control version, as many (I want to say most) apt packages are outdated, same goes for installing from source. I'd personally prefer using Docker images where possible to avoid the infamous works-on-my-machine issues"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T17:09:29.580",
"Id": "488542",
"Score": "2",
"body": "Indeed. I've used an Ansible playbook for years to configure my workstation with exactly what I want the way I want it. It came in handy when I reinstalled the OS and was able to restore pretty much everything immediately (except the tweaks I forgot to add to the playbook). For the home directory, though, I'm less concerned about scripting that because it's more-or-less continuously backed up, and I just restore the backup if necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T19:06:19.030",
"Id": "489291",
"Score": "0",
"body": "Any pointers for getting started with Ansible? Took me a week to get back to this since it's not my main project but after deciding to add a real ci/cd pipeline instead of the hack-y github-dockerhub-golang server solution I'd been using that I might as well circle back and make sure the pipeline setup itself is reproducible and throw in the environment setup while I'm at it"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T22:53:27.777",
"Id": "249250",
"ParentId": "249244",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "249250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T21:02:33.023",
"Id": "249244",
"Score": "8",
"Tags": [
"bash",
"linux"
],
"Title": "Bash script to automate dev environment setup"
}
|
249244
|
<p>So i wrote a program with the documentation for my fx cg50 calculator's micropython to calculate various items, each of which are:</p>
<ol>
<li>Pascal Triangle Entry</li>
<li>Pascal Triangle Level/Entire Row</li>
<li>Binomial Expansion</li>
<li>Binomial Term Finder</li>
<li>First num of terms</li>
<li>Combinations</li>
</ol>
<p>if you look at the code below, you'll notice, I haven't used any modules, and reinvented the wheel on some things. That is because, micropython's python language and standard library is very limited, so I had to make do.</p>
<p>I would like some advice on optimizing, and compacting of my program, and other tips and tricks to improve how a task is done.</p>
<pre><code>def float_integer(num):
"""
returns an integer if the float given, is a whole number.
otherwise returns the same value as the argument num.
Ex:
4.0 ---> 4
3.5 ---> 3.5
"""
if num == int(num):
return int(num)
return num
def seperate_to_pairs(iterator):
"""
changes it so that each item in the list pairs with its neighbor items.
Ex:
[1, 2, 1] ---> [[1, 2], [2, 1]]
[1, 2, 3, 1] ---> [[1, 2], [2, 3], [3, 1]]
[1, 2, 3, 2, 1] ---> [[1, 2], [2, 3], [3, 2], [2, 1]]
"""
return [iterator[i:i+2] for i in range(0, len(iterator)-1)]
def factorial(n, endpoint=1):
"""
acquires the factorial of n
Ex:
5 ---> 120
"""
res = 1
for i in range(endpoint, n+1):
res *= i
return res
def combinations(n, r):
"""
nCr - combination or number of ways of picking r items from n
OR
nCr = n!/r!(n-r)!
Ex:
4C2 ---> 6
6C3 ---> 20
"""
return (factorial(n, n-r+1) // factorial(r))
def pascal_triangle_entry(nth, rth):
"""
acquires the entry in the pascal's triangle at the nth row and rth term
Ex:
4th row, 2nd term ---> 3
"""
return combinations(nth-1, rth-1)
def pascal_triangle_level(level):
"""
acquires an entire row in the pascal triangle designated by the level number, where 0 is [1], and 1 is [1, 1]
Ex:
5 ---> [1, 5, 10, 10, 5, 1]
6 ---> [1, 6, 15, 20, 15, 6, 1]
"""
if level == 0:
return [1]
layer = [1, 1]
for _ in range(level-1):
current_layer = []
for pair in seperate_to_pairs(layer):
current_layer.append(sum(pair))
layer = [1] + current_layer + [1]
return layer
def binomial_expand(a, b, n):
"""
(a + bx)^n = a^n + (nC1) a^(n-1) bx + (nC2) a^(n-2) (bx)^2 + ... + (nCr) a^(n-r) (bx)^r + ... + (bx)^n
Ex:
a = 3, b = 2, n = 4 # example values for (3 + 2x)^4
OUTPUT FORMAT:
[4C0] --> 81.0
(3.0)^4
...
[nCr] --> Term_Value
nCr_value (a)^(n-r) (b)^(r)
...
[4C4] --> 16.0
(2.0)^4
"""
terms = []
coefficients = pascal_triangle_level(n)[1:-1]
for r, coefficient in zip(range(1, len(coefficients)+1), coefficients):
term_value = binomial_term_finder(a, b, n, r, coefficient)
terms.append("[{5}C{4}] --> {6}\n{0} ({1})^({2}) ({3})^({4})".format(coefficient, a, n-r, b, r, n, term_value))
return "\n".join(["[{1}C0] --> {2}\n({0})^{1}".format(a, n, a**n)] + terms + ["[{1}C{1}] --> {2}\n({0})^{1}".format(b, n, b**n)])
def binomial_term_finder(a, b, n, r, coefficient=None):
"""
calculates the coefficient of the rth term in (a + bx)^n
if coefficient is given, it skips calculating it.
Ex:
a = 3, b = 2, n = 4, r = 2 # example values for (3 + 2x)^4
---> 216
"""
if coefficient:
return coefficient * a**(n - r) * b**r
return combinations(n, r) * a**(n - r) * b**r
def first_rth_terms(a, b, n, rth):
"""
calculates the coefficients of x for the first rth terms in (a + bx)^n
Ex:
a = 3, b = 2, n = 4, rth = 3 # example values for (3 + 2x)^4
---> [81, 216, 216]
"""
return [binomial_term_finder(a, b, n, r) for r in range(rth)]
class BIOS:
"""
responsible for input and output operations
Hence called BIOS - Basic Input and Output System
"""
prompt = "\n".join(["a: pascal tri. entry", "b: pascal tri. row", "c: binomial expand", "d: binomial term finder", "e: first rth terms", "f: combinations"])
def __init__(self):
self.running = True
self.choices = {'a': self.pascal_triangle_entry, 'b': self.pascal_triangle_level, 'c': self.binomial_expand, 'd': self.binomial_term_finder, 'e': self.first_rth_terms, 'f': self.combinations}
def stop_decorator(func):
"""
Decorator for stopping certain functions, after they're done by asking with a prompt
"""
def wrapper(self):
func(self)
command = input("Enter nothing to stop: ")
if command == '':
self.running = False
return wrapper
def INPUT_a_b(self):
"""
input a and b for (a + bx)^n, using only one line
"""
return float_integer(float(input("Enter a: "))), float_integer(float(input("Enter b: ")))
@stop_decorator
def pascal_triangle_entry(self):
nth = int(input("Enter row number(n): "))
rth = int(input("Enter entry number(r): "))
print(pascal_triangle_entry(nth, rth))
@stop_decorator
def pascal_triangle_level(self):
level = int(input("Enter level: "))
print(pascal_triangle_level(level))
def binomial_expand(self):
a, b = self.INPUT_a_b()
nth = int(input("Enter nth: "))
self.running = False
print(binomial_expand(a, b, nth))
@stop_decorator
def binomial_term_finder(self):
a, b = self.INPUT_a_b()
nth = int(input("Enter nth: "))
rth = int(input("Enter rth: "))
print(binomial_term_finder(a, b, nth, rth))
@stop_decorator
def first_rth_terms(self):
a, b = self.INPUT_a_b()
nth = int(input("Enter nth: "))
rth = int(input("Enter first num terms: "))
print("First {} terms:".format(rth))
print(first_rth_terms(a, b, nth, rth))
@stop_decorator
def combinations(self):
nth = int(input("Enter nth: "))
rth = int(input("Enter rth: "))
print(combinations(nth, rth))
def main(self):
"""
main program loop, uses a dictionary as an alternative for a switch case
"""
while self.running:
print(self.prompt)
self.choices.get(input(">> "), lambda: None)()
program = BIOS()
program.main()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:47:33.940",
"Id": "488498",
"Score": "0",
"body": "You may want to look at making some of these functions that return lists into generators (e.g. `seperate_to_pairs()`, take a look at `itertools.pairwise()` in the itertools recipes, especially as all you a doing with it is looping through it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:50:11.830",
"Id": "488499",
"Score": "2",
"body": "You can also generate an individual row in pascals triangle without building up from the beginning, it has a recurrence relationship of `c * (n - r + 1) // r`, where `n` is the row number, `r` is the element in the row and `c` is the recurrence value, starting at `1`"
}
] |
[
{
"body": "<h1>Doc Test</h1>\n<p>You have docstrings in your code which illustrates function inputs and expected outputs. Why not format these using the style of the <code>doctest</code> module?</p>\n<pre><code>def float_integer(num):\n """\n Returns an ...\n\n >>> float_integer(4.0)\n 4\n\n >>> float_integer(3.5)\n 3.5\n """\n</code></pre>\n<p>Micropython may not have the <code>doctest</code> module (or maybe it does, I don’t know), but you can still run doctest on the same source file in a full Python environment to check the code and the documentation work as expected.</p>\n<h1>You Can’t Index an Iterator</h1>\n<p>Using <code>[interator[i:i+2] for i in range(...)]</code> means the variable <code>iterator</code> is not an iterator.</p>\n<p>An iterator is constructed from an iterable object, such as a list. An iterator will traverse an iterable object exactly once, and then it is useless, but more than one iterator can be created from an iterable object. Lists are directly indexable, which is what you are doing to the <code>iterator</code> variable.</p>\n<p>Still, Python can be horribly inefficient at indexing, since it has to do math and create objects for temporary results like <code>i+2</code> on every step of the loop; it is much more efficient to use iterators.</p>\n<pre><code>def separate_to_pairs(iterable):\n\n iter1 = iter(iterable) # create 1st iterator\n iter2 = iter(iterable) # create a 2nd iterator\n next(iter2) # advance 2nd iterator one position\n\n return [[a, b] for a, b in zip(iter1, iter2)]\n</code></pre>\n<p>Here, we create two iterators from the iterable object that is given. These are iterators are independent entities. They can be advanced separately, and indeed we advance the second iterator one position forward. <code>zip</code> takes both iterators, and extracts one element from each, until one of the iterators runs out of elements.</p>\n<p>The above returns the same type (<code>List[List[T]]</code>) that your function returned. If we allow changing the return type from the original, the function can be converted to return a list of tuples, using:</p>\n<pre><code> return [(a, b) for a, b in zip(iter1, iter2)]\n</code></pre>\n<p>Or equivalently, more efficiently but perhaps a bit more opaquely:</p>\n<pre><code> return list(zip(iter1, iter2))\n</code></pre>\n<p>Finally, since you process the returned list from <code>separate_to_pairs</code> using a <code>for .. in ...</code> loop, instead of returning a list, we can return a generator for the pairs, which gives the most efficient implementation:</p>\n<pre><code> return zip(iter1, iter2)\n</code></pre>\n<h1>Enumerate</h1>\n<p><code>binomial_expand</code> uses <code>zip(range(1, len(coefficients)+1), coefficients)</code> to get pairings of the each coefficient and its one-based index.</p>\n<p>This operation is built in to Python (and hopefully micropython), and is spelt <code>enumerate</code>.</p>\n<pre><code>for r, coefficient in enumerate(coefficients, 1):\n</code></pre>\n<p>The second argument is often omitted and the enumeration starts at zero, but you can begin at any index value you desired by providing that starting value.</p>\n<p>Since the micropython documentation mentions <code>enumerate</code>, but your implementation does not appear to support it, perhaps you could conditionally implementing it yourself:</p>\n<pre><code>if 'enumerate' not in dir(__builtins__):\n def enumerate(iterable, start=0):\n """Approximation of enumerate"""\n return zip(range(start, len(iterable) + start), iterable)\n</code></pre>\n<p>A proper <code>enumerate</code> function doesn't require the length of the iterable to be known ahead of time; this is just your approximation, with a <code>start</code> argument. When an update to the micro python implementation adds <code>enumerate</code>, the do-it-yourself version should automatically be skipped.</p>\n<h1>List Comprehension</h1>\n<p>Declaring a list and then repeatedly calling <code>append</code> in a loop is often better done using list comprehension. Instead of:</p>\n<pre><code> current_layer = []\n for pair in seperate_to_pairs(layer):\n current_layer.append(sum(pair))\n</code></pre>\n<p>use</p>\n<pre><code> current_layer = [sum(pair) for pair in seperate_to_pairs(layer)]:\n</code></pre>\n<h1>WET -vs- DRY</h1>\n<p>"WET" stands for "Write Everything Twice", and "DRY" for "Don't Repeat Yourself". You want your code do be "DRY"...</p>\n<h2>Data entry & input validation</h2>\n<p>You have a lot of duplicate code like <code>int(input("..."))</code>. You've defined a function for inputting a pair of float values. Why not a function for inputting an integer?</p>\n<pre><code> @staticmethod\n def input_int(prompt):\n return int(input(prompt))\n</code></pre>\n<p>As a bonus, you could add a loop with a <code>try ... except</code> statement, and not crash the program if the user accidentally inputs a non-integer value. Every caller of this method would gain the input validation, without duplicating it everywhere.</p>\n<pre><code> @staticmethod\n def input_int(prompt):\n while True:\n try:\n return int(input(prompt))\n except ValueError:\n print("Invalid input - Please enter an integer")\n</code></pre>\n<h2>Menu</h2>\n<p>You have a prompt string, which lists all the functions and the corresponding letter, and a dictionary, which lists all of the functions to call and the corresponding letter. If you make a change, you have to do the change in both places. It is easy to make a mistake and miss one.</p>\n<p>Instead, consider auto-generating the prompt from the dictionary. Perhaps something like:</p>\n<pre><code>prompt = "\\n".join(key + ": " + method.__name__.replace('_', ' ')\n for key, method in self.choices.items())\n</code></pre>\n<h1>PEP-0008 Violations</h1>\n<p>The Style Guide for Python has many rule to help make Python programs formatted more consistently and thus easier for other people to understand. These rules include:</p>\n<ul>\n<li>One space around binary operators (<code>n - r + 1</code>, not <code>n-r+1</code>)</li>\n<li>Function & methods should be in lowercase <code>snake_case</code>. <code>INPUT_a_b</code> violates this.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T07:25:59.917",
"Id": "488583",
"Score": "0",
"body": "ah yes, sadly enumerate for some reason, is not available on micropython, so i just reinvented it using zip, and i really never bothered with PEP, should probably look into it and take a read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:39:46.227",
"Id": "488603",
"Score": "0",
"body": "Hmm, you talk about efficiency and then unpack and repack every already perfectly fine tuple that `zip` produces for no apparent reason. Did you mean to create lists instead, as the original did? And PEP 8 (not PEP-8 btw :-P) calls `x = x*2 - 1` correct and `x = x * 2 - 1` wrong. Where does it say what you're saying?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:47:04.153",
"Id": "488604",
"Score": "0",
"body": "@ErenYaegar The [documentation](https://docs.micropython.org/en/latest/library/builtins.html) does list `enumerate`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T11:27:33.723",
"Id": "488607",
"Score": "0",
"body": "hmm wierd, it's included in the documentation, but it gives a name error on the micropython shell"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T05:32:38.197",
"Id": "249304",
"ParentId": "249253",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249304",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T04:23:31.063",
"Id": "249253",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"mathematics",
"calculator"
],
"Title": "Binomial Expansion Calculator"
}
|
249253
|
<p>I have made a function to drop a row in a pandas.DataFrame. Since, in general, the input dataframe of a function is just a reference to the dataframe. So any change made in that function to the dataframe will be preserved outside that function. Therefore, there are two choices when designing the function:</p>
<ol>
<li>simply make the change without returning the dataframe.</li>
<li>or, make the change and return the dataframe.</li>
</ol>
<p>See my code below (function <code>change_df_1</code> and <code>change_df_2</code>). Could you please let me know which one is better or do you prefer? My concern is readability/clarity of the code.</p>
<pre><code>import pandas as pd
def get_df():
df = pd.DataFrame({'A': [10, 20, 30], 'B':[100, 200, 300]})
return df
def change_df_1(df: pd.DataFrame):
df.drop(index=[1], inplace=True)
def change_df_2(df: pd.DataFrame) -> pd.DataFrame:
df.drop(index=[1], inplace=True)
return df
def main():
df = get_df()
print(f'Original {df=}')
change_df_1(df=df)
print(f'Changed_with 1: {df=}')
# change_df_2(df=df)
# print(f'Changed_with 2: {df=}')
if __name__ == '__main__':
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The documentation for <code>sort</code>, to pick a common example, <a href=\"https://docs.python.org/3/howto/sorting.html\" rel=\"nofollow noreferrer\">says</a>:</p>\n<blockquote>\n<p>You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion).</p>\n</blockquote>\n<p>One benefit of returning the object is to chain calls. If consumers of your code expect to be able to chain calls, perhaps returning the object makes sense. Otherwise I would say the more common behavior in Python is to return None from functions that mutate their arguments.</p>\n<p>(Other languages may have other conventions.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:25:21.647",
"Id": "488494",
"Score": "0",
"body": "`pandas` follows this convention and when you have `inplace=True` it returns `None`. I believe you call an interface that allows you to chain a `fluent` interface."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T07:29:27.310",
"Id": "249258",
"ParentId": "249255",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249258",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T05:47:28.290",
"Id": "249255",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"pandas",
"reference"
],
"Title": "Dropping a row in a dataframe"
}
|
249255
|
<p>I am trying to create a secure file upload using PHP 7+ where I <strong>only allow PDF files</strong>. I found a lot of posts on this topic on different websites but couldn't find a complete solution that ensures that no harmful files can be uploaded this way.</p>
<p>So far I have the following code. Can someone tell me if I am missing any important steps here or if anything should be changed or removed in my code?</p>
<p>(<strong>Note:</strong> I am not interested in the old x-pdf file types.)</p>
<pre><code><?php
include 'session.php';
include 'header.php';
if (empty($_FILES['files'])) {
echo json_encode(['error'=>'No files found for upload.']);
return;
}
if(!empty($_POST['csrfToken'])) {
if(hash_equals($_SESSION['csrfToken'], $_POST['csrfToken'])) {
$postData = $_POST;
$files = $_FILES['files'];
$uploadRef = preg_replace('/[^A-Za-z0-9]/', '', $_GET['uploadRef']);
$categoryId = preg_replace('/[^A-Za-z0-9]/', '', $_GET['categoryId']);
$tags = preg_replace('/[^A-Za-z0-9,]/', '', $_GET['tagsList']);
$success = null;
$paths= [];
$filenames = $files['name'];
for($i=0; $i < count($filenames); $i++){
if($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die('Upload failed with error ' . $_FILES['file']['error']);
}
$fileTitle = $files['name'][$i];
$fileTitle = substr($fileTitle, 0 , (strrpos($fileTitle, ".")));
$fileExtensions = explode('.', basename($filenames[$i]));
$fileExtension = strtolower(array_pop($fileExtensions));
$ok = false;
switch($fileExtension) {
case 'pdf':
$ok = true;
default:
die('Unknown/not permitted file type');
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch($mime) {
case 'application/pdf':
$ok = true;
default:
die('Unknown/not permitted file type');
}
$uploadId = md5(uniqid()) . '_' . $i;
$target = 'uploads' . DIRECTORY_SEPARATOR . $uploadId . '.' . $fileExtension;
if(move_uploaded_file($files['tmp_name'][$i], $target)) {
$success = true;
$paths[] = $target;
$conn = new mysqli($dbHost, $dbUser, $dbPw, $dbName);
if($conn->connect_error) {
exit($trans['errorConnectionFailedTxt'][$lang]);
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare("INSERT INTO uploads (uploadId, uploadRef, categoryId, tags, fileTitle, fileExtension) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $uploadId, $uploadRef, $categoryId, $tags, $fileTitle, $fileExtension);
$stmt->execute();
$stmt->close();
$conn->close();
} else {
$success = false;
break;
}
}
if ($success === true) {
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
unset($postData);
echo json_encode($output);
} else {
echo json_encode('invalid CSRF token');
}
} else {
echo json_encode('no CSRF token');
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:36:13.447",
"Id": "488495",
"Score": "2",
"body": "How many `header('Location...')` calls are you planning to make?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:08:00.457",
"Id": "488501",
"Score": "0",
"body": "@mickmackusa: One. Why ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:13:30.077",
"Id": "488502",
"Score": "2",
"body": "It's inside a loop. Do you mean to redirect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:33:40.540",
"Id": "488504",
"Score": "0",
"body": "@mickmackusa: Thanks. Yes, I mean to redirect after successful upload, but only once (also in case of multiple files) so I may have placed this wrongly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:34:57.873",
"Id": "488505",
"Score": "0",
"body": "You may edit your script until you receive an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:36:06.157",
"Id": "488506",
"Score": "0",
"body": "My main concern is that someone can take a harmful file and just make it look like a pdf so I want to prevent that this could be misused to upload a shell, exe or other harmful file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:37:22.197",
"Id": "488507",
"Score": "0",
"body": "That may be true, but we will review your entire script. There are several things to improve in your script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T11:47:51.473",
"Id": "488518",
"Score": "0",
"body": "Ok. I removed the header completely as it is not a must-have here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:06:12.423",
"Id": "488557",
"Score": "0",
"body": "@mickmackusa: Are you still looking into this ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:07:20.247",
"Id": "488558",
"Score": "1",
"body": "At 7am on a Sunday I am sleeping in my bed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T04:40:53.480",
"Id": "488576",
"Score": "0",
"body": "Sorry, I am in another time zone."
}
] |
[
{
"body": "<h2>Bug / Logic error</h2>\n<p>The two <code>switch</code> statements have one case plus the default case. In both switch statements the <code>default</code> case is always executed. Perhaps a better understanding of how <code>switch</code> statements work would be useful. Also, for a single case it doesn't make sense to use a <code>switch</code> statement - a simple <code>if</code> statement would suffice.</p>\n<h2>Inconsistent return types</h2>\n<p>In some cases an array is passed to <code>json_encode()</code> and used with an <code>echo</code> statement, yet in other cases <code>die()</code> is called. The json encoded arrays would have me believe this script is used in conjunction with an asynchronous loading mechanism (e.g. AJAX), but that would likely be thrown off if <code>die()</code> or <code>exit()</code> is used, unless it looks for both arrays and simple strings.</p>\n<p>Then apparently when the upload is successful there is this code:</p>\n<blockquote>\n<pre><code>if ($success === true) {\n $output = [];\n</code></pre>\n</blockquote>\n<p>That doesn't seem to be very helpful for the front-end code.</p>\n<p>It would also be wise to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\" rel=\"nofollow noreferrer\">HTTP response codes</a> - e.g. 200 to indicate success, 422 for invalid input, etc.</p>\n<h2>returning early</h2>\n<p>When the first condition, i.e. <code>if (empty($_FILES['files'])) {</code> evaluates to <code>true</code> then the JSON response is returned with the appropriate error message. The other conditions that lead to error messages should follow the same fashion e.g. empty value in <code>$_POST['csrfToken']</code>, etc. Doing so will decrease the amount of indentation for the rest of the code. For more information on this topic see <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> where Rafael Dohms talks about many ways to keep code lean - like avoiding the <code>else</code> keyword (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n<p>Because it doesn’t depend on the loop iterator variable, this block can be moved above the <code>for</code> loop:</p>\n<blockquote>\n<pre><code>if($_FILES['file']['error'] !== UPLOAD_ERR_OK) {\n die('Upload failed with error ' . $_FILES['file']['error']);\n}\n</code></pre>\n</blockquote>\n<h2>checking MIME type</h2>\n<p>Instead of calling <code>finfo_open(FILEINFO_MIME_TYPE)</code> just to get the mime-type, the <a href=\"https://www.php.net/manual/en/function.mime-content-type.php\" rel=\"nofollow noreferrer\"><code>mime-content-type()</code></a> function could be used.</p>\n<pre><code>$mime = mime-content-type($_FILES['file']['tmp_name'])\n</code></pre>\n<p>Additionally, the mime-type may be provided from the browser in <code>$_FILES['files']['type'][$i]</code> though it "<em>not checked on the PHP side and therefore don't take its value for granted.</em>"<sup><a href=\"https://www.php.net/manual/en/features.file-upload.post-method.php#example-395\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<h2>variable <code>$postData</code> - really needed?</h2>\n<p>After <code>postData</code> is assigned, it only appears to be used in one spot- passed to <code>unset()</code>. It hardly seems necessary...</p>\n<h2>variadic field name checks</h2>\n<p>While the form submitted to this script is not included one can only guess as to the fields. The script checks both <code>$_FILES['files']</code> as well as <code>$_FILES['file']</code> - while the former most likely allows multiple files to be uploaded, are there really two different file input fields?</p>\n<h2>database query in loop</h2>\n<p>The code currently inserts records into the database on each iteration of the loop. Consider using only one statement to insert all records. This will minimize database connections (which can increase execution time) as well as prevent invalid data from being inserted (e.g. if first file was valid but subsequent files were not).</p>\n<h2>regular expressions to replace characters</h2>\n<p>The regular expressions could perhaps be simplified using the <a href=\"https://www.php.net/manual/en/parle.regex.charclass.php\" rel=\"nofollow noreferrer\">character type</a> <code>\\w</code> though that includes the underscore characters i.e. <code>_</code> but must those be removed? Also not that <code>preg_replace()</code> won't safely clean multi-byte strings so consider that if unicode strings need to be supported.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T14:53:22.567",
"Id": "249351",
"ParentId": "249257",
"Score": "1"
}
},
{
"body": "<h2>Guard statements</h2>\n<pre><code>if(!empty($_POST['csrfToken'])) {\n if(hash_equals($_SESSION['csrfToken'], $_POST['csrfToken'])) {\n</code></pre>\n<p>I think that this should be performed in a separate method that validates tokens. Furthermore, I think that this should end in an HTTP error (as indicated by the other answer).</p>\n<p>Above is called a "guard statement", it checks if the state or parameter is valid before the method is executed. If it isn't valid, it should terminate it. Termination can be performed locally, you definitely don't want to have to scroll through the method to find:</p>\n<pre><code> } else {\n echo json_encode('invalid CSRF token');\n }\n} else {\n echo json_encode('no CSRF token');\n}\n</code></pre>\n<p>at the end. Furthermore, if you simply exit the method you remove a layer of indentation making the method less complex to read.</p>\n<h2>Unclear regular expressions</h2>\n<pre><code>$uploadRef = preg_replace('/[^A-Za-z0-9]/', '', $_GET['uploadRef']);\n</code></pre>\n<p>This should also be a method, not so much because the regular expression is hard to understand (the "what"), but it isn't clear <strong>why</strong> it is performed.</p>\n<h2>Success?</h2>\n<pre><code> $success = null;\n</code></pre>\n<p>Success is a boolean, it should not be used as a variable with three values. Use either two variables or an enumeration. Furthermore, <code>$success</code> is a terrible bad name, try <code>filesUploaded</code> or similar.</p>\n<p>If we'd check that <code>count($filenames)</code> is zero beforehand we can simply set the output beforehand and skip the rest of the execution (remember the guard statements). Programming is all about limiting complexity.</p>\n<h2>Recovering C programmer</h2>\n<pre><code> $ok = false;\n</code></pre>\n<p>Not required if you <code>die</code> anyway, right?</p>\n<h2>Not so unique</h2>\n<pre><code> uniqid()\n</code></pre>\n<p>"This function does not guarantee uniqueness of return value."<sup><a href=\"https://www.php.net/manual/en/function.uniqid.php#refsect1-function.uniqid-description\" rel=\"nofollow noreferrer\">1</a></sup> Um, right. This is just waiting to fail horribly, whatever you do with it. Using <code>md5()</code> on it will not accomplish <em>anything</em>. Extension with a counter will help unless the same folder is used by parallel processes (is that possible?).</p>\n<h2>The sequel</h2>\n<p>The SQL statements should be in a separate method, e.g. <code>createFileUploadReport</code>. If you make a separate class you can even use different ways of reporting, e.g. reporting to console or log file instead, so you can test your method without SQL server present.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:58:02.480",
"Id": "488741",
"Score": "1",
"body": "Unfortunately I'm not sure how secure the MIME type testing is. I would not be surprised if it can be fooled to some extend."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T16:52:53.200",
"Id": "249356",
"ParentId": "249257",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T07:15:35.740",
"Id": "249257",
"Score": "2",
"Tags": [
"php",
"sql",
"file",
"security",
"pdf"
],
"Title": "Secure file upload for PDF only"
}
|
249257
|
<p>I solved a Risk game question (<a href="http://www.pyschools.com/quiz/view_question/s3-q12" rel="nofollow noreferrer">http://www.pyschools.com/quiz/view_question/s3-q12</a>) in two ways, but as I am currently learning Python, I'm just wondering how to rate my methods of solving this question. Like which one of these ways is really a better, effective, and efficient method to solve this question? Or maybe there is a better approach than what I did?</p>
<p>This is the game instruction:
"In the Risk board game, there is the situation where the attacker rolls 3 dice while the defender rolls 2 dice. To determine the outcome, the highest die of each player is compared, followed by the next highest die. For each case, the attacker's die has to be higher than that of the defender to win. The loser will lose 1 army in each case."</p>
<p>This is the sample of the function and the return statement:</p>
<pre><code> >>> RiskGame([6,2,6], [6, 6])
'Attacker loses 2 armies.'
>>> RiskGame([1,4,1], [1, 2])
'Attacker loses 1 army and defender loses 1 army.'
</code></pre>
<h2>Method 1</h2>
<pre><code>def RiskGame(attacker, defender):
a_score = 0
a_loose = 0
d_score = 0
d_loose = 0
for e in range(len(defender)):
a= max(attacker)
d= max(defender)
if a>d:
a_score +=1
d_loose +=1
else:
d_score +=1
a_loose +=1
attacker.remove(a)
defender.remove(d)
if a_loose == 0:
return 'Defender Loses %i armies.' %d_loose
elif d_loose == 0:
return 'Attacker loses %i armies.' %a_loose
else:
return 'Attacker loses %i army and defender loses %i army.' %(a_loose, d_loose)
RiskGame([1,2,6], [1, 5])
RiskGame([1,4,1], [1, 2])
RiskGame([6,2,6], [6, 6])
</code></pre>
<h2>Method 2</h2>
<pre><code>def RiskGame(attacker, defender):
a = sorted(attacker, reverse=True)
b = sorted(defender, reverse=True)
a_scr =0
d_scr =0
pairs = zip(a,b)
for i,j in pairs:
if i>j:
a_scr +=1
else:
d_scr +=1
if d_scr == 0:
return 'Defender loses %i armies.' %a_scr
elif a_scr == 0:
return 'Attacker loses %i armies.' %d_scr
else:
return 'Attacker loses %i army and defender loses %i army.' %(a_scr, d_scr)
RiskGame([1,2,6], [1, 5])
RiskGame([1,4,1], [1, 2])
RiskGame([6,2,6], [6, 6])
</code></pre>
|
[] |
[
{
"body": "<p>Nice implementation for both methods, few suggestions:</p>\n<ul>\n<li><strong>Camel case or underscores.</strong> The function <code>RiskGame</code> uses camel case notation but the variables use underscore notation (<code>a_score</code>). Better to use only one notation. Generally, underscores are preferred in Python.</li>\n<li><strong>Unused variables</strong>: <code>a_score</code> and <code>d_score</code> in Method 1.</li>\n<li><strong>Variable names can be improved</strong>: <code>a_scr</code> can be renamed to <code>attacker_score</code>. This statement <code>a=max(attacker)</code> could be <code>attacker_max_number=max(attacker)</code> or similar. Even if it's longer, makes the code easier to read.</li>\n<li><strong>Return the result</strong> instead of a human-readable string, it's easier to reuse and test. For example instead of:\n<pre><code>def RiskGame(attacker, defender):\n #...\n if d_scr == 0:\n return 'Defender loses %i armies.' %a_scr\n elif a_scr == 0:\n return 'Attacker loses %i armies.' %d_scr\n else:\n return 'Attacker loses %i army and defender loses %i army.' %(a_scr, d_scr)\n</code></pre>\nreturn the result directly:\n<pre><code>def RiskGame(attacker, defender):\n #...\n return attacker_score, defender_score\n\nattacker_score, defender_score = RiskGame([1,2,6], [1, 5])\nif defender_score == 0:\n print('Defender Loses %i armies.' %attacker_score)\n#...\n</code></pre>\n</li>\n</ul>\n<h2>Which method is more efficient?</h2>\n<p>There are no issues about performances given the requirements of max three elements for the input list. In fact, as @Jasmijn points out in the comments, on the condition that <code>1 <= len(attacker) <= 3</code> and <code>1 <= len(defender) <= 2</code>, the time complexity of both methods is <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n<p>If the input lists have many elements and the attacker's list is bigger than the defender's list, I would say Method 2 is faster. The time complexity of Method 1 would be <span class=\"math-container\">\\$O(d*a)\\$</span> where <span class=\"math-container\">\\$d\\$</span> is the length of the defender's list and <span class=\"math-container\">\\$a\\$</span> is the length of the attacker's list. Even if the lists shrink at each iteration we can say that for big inputs. Method 2 would be <span class=\"math-container\">\\$O(a*log(a))\\$</span>, assuming that the <code>zip()</code> function runs in <span class=\"math-container\">\\$O(d)\\$</span> and sorting the attacker's list takes <span class=\"math-container\">\\$O(a*log(a))\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:04:36.263",
"Id": "488523",
"Score": "1",
"body": "thank you very much for this thorough and marvelous review and feedback. I really appreciate it, next time, I will use your comments as a guide to improve my codes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:07:00.077",
"Id": "488543",
"Score": "3",
"body": "Given the rules of Risk, `1 <= len(attacker) <= 3 and 1 <= len(defender) <= 2`, both methods are O(1) under those constraints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:18:28.707",
"Id": "488570",
"Score": "0",
"body": "@Jasmijn thanks, I included your feedback in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:20:14.963",
"Id": "488571",
"Score": "1",
"body": "@teemran thanks, I am glad I could help. Please consider to choose an answer when you are satisfied ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T03:35:16.560",
"Id": "488673",
"Score": "0",
"body": "The time complexity of any algorithm with a maximum input size is O(1). Bubble sort on a deck of cards is O(1). It's a rather vacuous statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T10:54:56.590",
"Id": "488701",
"Score": "0",
"body": "Re: the last paragraph. Since we know the attacker's list will contain the results of six-sided dice, wouldn't a simple tallying provide a sorting of order O(a)? Not that I think python's sorting functions would know to exploit that."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T11:40:31.117",
"Id": "249272",
"ParentId": "249260",
"Score": "13"
}
},
{
"body": "<p>The first one changes the input, which is bad unless it's supposed to. You could fix that by making copies of the given lists and working on them instead.</p>\n<p>The string formatting is unnecessary, since the values are always <code>2</code>, <code>2</code> or <code>(1, 1)</code>, respectively. Also gives us the opportunity for good writing style, writing the numbers as words, not digits. Yes, I realize digits are required by the problem setter so it's their fault, not yours. Just saying. You could argue that yours are more general, in case more dice were used, but then you should also use singular/plural appropriately, to avoid saying something like "Attacker loses 5 army".</p>\n<p>Finally, I'd pick a side. That is, only count one side's statistic. I'll go with the attacker, as that's the "active" party (as opposed to defense being a <em>reaction</em>).</p>\n<pre><code>def RiskGame(attacker, defender):\n _, a1, a2 = sorted(attacker)\n d1, d2 = sorted(defender)\n wins = (a2 > d2) + (a1 > d1)\n if wins == 2:\n return 'Defender loses two armies.'\n elif wins == 0:\n return 'Attacker loses two armies.'\n else:\n return 'Attacker loses one army and defender loses one army.'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T09:59:20.510",
"Id": "488596",
"Score": "0",
"body": "Hi, thanks for your suggestion. But can you tell me why this underscore ```_, a1,...```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:06:44.817",
"Id": "488597",
"Score": "0",
"body": "And for the string formatting, it is actually the problem of the questions setter, I just acted based on the requirements, just as you said. Lastly, I simply couldn't understand your boolean comparison for the ```wins``` parameter, can you help to clear this? thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:20:30.643",
"Id": "488600",
"Score": "1",
"body": "The underscore is because I can't assign three values to only two variables. So I use the underscore variable conventionally used for unused values. Booleans `True` and `False` act like 1 and 0, so I can just add the two match results to get the total."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:24:13.510",
"Id": "488602",
"Score": "0",
"body": "Got it now, you are very correct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T03:42:19.950",
"Id": "488674",
"Score": "1",
"body": "You can do `a1, a2 = sorted(attacker)[1:]`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T14:06:33.653",
"Id": "249276",
"ParentId": "249260",
"Score": "5"
}
},
{
"body": "<p>You have some good answers already. Rather than focusing on the details of your\ncode, I'll offer some comments about how to approach the design of a full\nprogram. I don't know your exact situation, but when you are learning,\ncommand-line programs are a good focal point for various practical reasons, so\nI'll use that as an illustration.</p>\n<p><strong>Functional core and imperative shell</strong>. As much as possible, strictly\nseparate your program into two types of functions: (A) those that do nothing\nbut take data and return data (the core); and (B) those that have side-effects\n(the shell). What counts as a side-effect? Many things, but printing and\nexceptions are two of the most common. The core idea here is that most of your\nprogram (and especially its algorithmic, computational details) should reside\nin the functional core. The outer shell concerned with printing and\ninteractivity should be as thin and as non-algorithmic as possible. In the\nexample below, <code>main()</code> is the outer shell and it is puny from an\nalgorithmic perspective -- nothing more than a trivial <code>if-else</code>. If you want\nto learn more about these ideas, the best talk I've seen on this core-shell\nseparation is from <a href=\"https://www.youtube.com/watch?v=eOYal8elnZk\" rel=\"nofollow noreferrer\">Gary\nBernhardt</a>.</p>\n<p><strong>Break it down</strong>. Once you have that fundamental separation in mind, start\ndecomposing the needed computations into reasonably small parts. This effort is\npart art, part science. How far you should pursue decomposition depends on the\ncontext. The example below takes it pretty far. The more complex the program,\nand the higher the stakes, the more seriously you want to take the decomposition\neffort. In simpler situations, various shortcuts are fine. But when the program\nis important, you need to write tests for it, and the demands of testability\nwill often drive you to decompose more (it can be difficult to test functions\nthat do too many things at once, and it's a big headache to test functions that\nhave major side effects).</p>\n<p><strong>Notice the simplicity that emerges</strong>. The functions end up being small, easy\nto understand, quick to describe in a comment for the reader. In most\nsituations those benefits outweigh (often significantly) the extra costs of\ntaking the extra time to break things apart.</p>\n<pre><code>import sys\n\ndef main(args):\n # Command-line usage example: `python risk_game.py 3,4,6 3,5`\n attacker, defender, error = parse_entries(args)\n if error:\n print(error)\n sys.exit(1)\n else:\n message = risk_game(attacker, defender)\n print(message)\n\ndef parse_entries(entries):\n # Takes attacker and defender entries. Returns a 3-tuple: (ATTACKER-ROLLS,\n # DEFENDER-ROLLS, ERROR-MESSAGE). There are more featureful and robust ways\n # to handle this; adjust as needed.\n try:\n return (parse_entry(entries[0]), parse_entry(entries[1]), None)\n except Exception as e:\n return (None, None, 'Invalid entry')\n\ndef parse_entry(entry):\n # Parses a single entry and returns a list of dice rolls.\n return [int(val) for val in entry.split(',')]\n\ndef risk_game(attacker, defender):\n # Takes two lists of dice rolls. Returns a message describing the outcome.\n score = compute_battle_score(attacker, defender)\n return generate_message(attacker, defender, score)\n\ndef compute_battle_score(attacker, defender):\n # Takes two lists of dice rolls. Returns a battle score.\n atts = sorted(attacker, reverse = True)\n defs = sorted(defender, reverse = True)\n return sum(1 if a > d else -1 for a, d in zip(atts, defs))\n\n # Or if you need to know N of victories for each combatant.\n return collections.Counter(a > d for a, d in zip(atts, defs))\n\ndef generate_message(attacker, defender, score):\n # Make it as fancy as you want.\n return f'Attacker score: {score}'\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:09:24.033",
"Id": "488559",
"Score": "4",
"body": "Very nice explaination of how and why you should structure your source code this way. However, two remarks about your example code: I would not catch exceptions just to convert them to a regular error message. Just let them propagate to the point where the error can really be dealt with. As for `compute_battle_score`: a battle round of Risk is not a single number, both attacker and defender can lose armies. While a single number might be enough information for 3 attacker armies and 2 defender armies, the actual game of Risk allows different army sizes, so a single number no longer suffices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:25:29.117",
"Id": "488560",
"Score": "2",
"body": "@G.Sliepen Good point about Risk: I'll leave that to the OP to enhance based on what is known to be needed. Regarding exception handling strategy, I agree with you in many contexts, but not this one. If `parse_entries()` raises, the algorithmic burden on the \"imperative shell\" increases – not necessarily in my trivial demo, but in a real program where one would want the error message to be specific to the mistake. I want the algorithmic complexity of picking the right message to reside outside of `main()`, so I illustrated it that way to point the OP on that path."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:43:08.917",
"Id": "488562",
"Score": "1",
"body": "Ah, I can see how a `ValueError`might not be so helpful for the end user. But perhaps rethrowing a more specific exception from within `parse_entries()` might be better? Returning a tuple makes it easy for the caller to forget to check the error condition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T01:13:18.390",
"Id": "488568",
"Score": "0",
"body": "I'd be happy to CR this if you post it as a question. There's a number of things I would suggest changing if this came through in a real PR, e.g., using a function to wrap a list comprehension one-liner, using a function to wrap an f-string, throwing a generic exception and then immediately catching it to print a message, completely hiding the error, and so forth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T01:23:35.867",
"Id": "488569",
"Score": "1",
"body": "@user1717828 Feel free to comment (I'm always willing to learn and am not bothered by a world of differing opinions), but I'm not building a Risk game (the OP is), so my desire to have it code reviewed is quite low. It wasn't written with that intent (see the text discussion). If it were real software, I would change various details myself. But that's not the context. It's a tiny educational demo written with a specific purpose in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:27:35.533",
"Id": "488572",
"Score": "0",
"body": "@user1717828 Having read your now edited comment I must conclude that you missed the point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T09:55:59.447",
"Id": "488595",
"Score": "0",
"body": "@FMc thank you very much for this advanced suggestions. I really benefited from your explanation a lot, although I recently started learning python just two weeks ago and yet to get to this stage, I see a lot of benefits for using core-shell separation and for the comment header in particular. I will try to re-implement my codes this way and see. Should I have any issues, I will revert. Thanks!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:46:37.233",
"Id": "249284",
"ParentId": "249260",
"Score": "7"
}
},
{
"body": "<p>If this were a real PR, I would highlight one of the <code>*loose</code> variables and ask <em>Should this read <code>lose</code></em>?</p>\n<p>I really like your second approach. While reading it, I felt like the next line of code was doing exactly what I was anticipating it would do, and I didn't have to use as much mental memory while reading it like I did your first approach, keeping track of all those variables that were set to zero. One way you might consider improving it is to remove the <code>a_scr</code> and <code>d_scr</code> initializations and use a <code>sum()</code> to calculate them, such as:</p>\n<pre><code>def RiskGame(attacker, defender):\n a = sorted(attacker, reverse=True)\n b = sorted(defender, reverse=True)\n \n a_scr = sum([i > j for i, j in zip(a,b)])\n d_scr = sum([i < j for i, j in zip(a,b)])\n\n if d_scr == 0:\n return 'Defender loses %i armies.' %a_scr\n elif a_scr == 0:\n return 'Attacker loses %i armies.' %d_scr\n else:\n return 'Attacker loses %i army and defender loses %i army.' %(a_scr, d_scr)\n\nRiskGame([1,2,6], [1, 5])\n</code></pre>\n<p>I have similar reservations about the Pascal casing of the functions and returning strings instead of values, but these are covered nicely in the other answers.</p>\n<h1>Edit: Demonstrate how to use tests</h1>\n<p>This part covers another way of ensuring your example battles run correctly in a systematic way using pytest. It illustrates why some other the other answers' suggestions to get the printing out of the function makes it easier to code.</p>\n<h2>Step 1.</h2>\n<p>Have your main function just return <code>a_scr</code> and <code>d_scr</code>, and put the printing logic in the main script:</p>\n<pre><code># riskgame.py\ndef risk_game(attacker, defender):\n a = sorted(attacker, reverse=True)\n b = sorted(defender, reverse=True)\n\n a_scr = sum([i > j for i, j in zip(a,b)])\n d_scr = sum([i <= j for i, j in zip(a,b)])\n\n return a_scr, d_scr\n\nif __name__ == "__main__":\n a_scr, d_scr = risk_game([6,2,6], [6, 6])\n\n if d_scr == 0:\n print('Defender loses %i armies.' %a_scr)\n elif a_scr == 0:\n print('Attacker loses %i armies.' %d_scr)\n else:\n print('Attacker loses %i army and defender loses %i army.' %(a_scr, d_scr))\n</code></pre>\n<p>When you execute the script, you get the same behavior as before:</p>\n<pre><code>$ python riskgame.py \nAttacker loses 2 armies.\n</code></pre>\n<h2>Step 2.</h2>\n<p>In the same directory create <code>test_wins_and_losses.py</code> and create some tests:</p>\n<pre><code># test_wins_and_losses.py\nfrom riskgame import risk_game\n \ndef test_d_wins():\n a_scr, d_scr = risk_game([1,2,6], [1, 5])\n assert a_scr == 2\n assert d_scr == 0\n\ndef test_a_wins():\n a_scr, d_scr = risk_game([6,2,6], [6, 6])\n assert a_scr == 0\n assert d_scr == 2\n\ndef test_equal():\n a_scr, d_scr = risk_game([1,4,1], [1, 2])\n assert a_scr == 1\n assert d_scr == 1\n</code></pre>\n<p>Notice I used the same values you put in the original post, but you could have any example games you want in there. Ideally, you would have lots, covering as many use cases as you can.</p>\n<h2>Step 3.</h2>\n<p>Install pytest if you haven't already.</p>\n<pre><code>$ pip install pytest\n</code></pre>\n<h2>Step 4.</h2>\n<p>Run it!</p>\n<pre><code>$ pytest\n============================= test session starts ==============================\nplatform linux -- Python 3.7.4, pytest-6.0.2, py-1.9.0, pluggy-0.13.1\nrootdir: /tmp/risk_game\ncollected 3 items \n\ntest_wins_and_losses.py ... [100%]\n\n============================== 3 passed in 0.02s ===============================\n</code></pre>\n<p>The idea is now you can change your code, and <strong>every time you do you can just type <code>pytest</code> at the command line to confirm everything is still functioning the way you expect</strong>. For example, if we make the mistake I made earlier and change the line to</p>\n<pre><code>d_scr = sum([i < j for i, j in zip(a,b)])\n</code></pre>\n<p>and run the tests, we get:</p>\n<pre><code>$ pytest\n==================================================================== test session starts =====================================================================\nplatform linux -- Python 3.7.4, pytest-6.0.2, py-1.9.0, pluggy-0.13.1\nrootdir: /tmp/risk_game\ncollected 3 items \n\ntest_wins_and_losses.py .FF [100%]\n\n========================================================================== FAILURES ==========================================================================\n________________________________________________________________________ test_a_wins _________________________________________________________________________\n\n def test_a_wins():\n a_scr, d_scr = risk_game([6,2,6], [6, 6])\n assert a_scr == 0\n> assert d_scr == 2\nE assert 0 == 2\n\ntest_wins_and_losses.py:11: AssertionError\n_________________________________________________________________________ test_equal _________________________________________________________________________\n\n def test_equal():\n a_scr, d_scr = risk_game([1,4,1], [1, 2])\n assert a_scr == 1\n> assert d_scr == 1\nE assert 0 == 1\n\ntest_wins_and_losses.py:16: AssertionError\n================================================================== short test summary info ===================================================================\nFAILED test_wins_and_losses.py::test_a_wins - assert 0 == 2\nFAILED test_wins_and_losses.py::test_equal - assert 0 == 1\n================================================================ 2 failed, 1 passed in 0.09s ================================================================\n</code></pre>\n<p>Happy testing!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:10:06.917",
"Id": "488598",
"Score": "0",
"body": "Yes, I also realized the bad definition of the ```lose``` variable. Thanks for this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:15:59.070",
"Id": "488599",
"Score": "0",
"body": "I really like this idea to just sum and calculate the score directly without initialing the variable to 0, this list comprehensions could be one of the faster ways to create a list, this could enhanced the efficiency of my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:22:45.200",
"Id": "488601",
"Score": "0",
"body": "However, your code suggestion, will not be able to address the issue when both the attacker and the defender have the same elements ```eg., RiskGame([1,1,1], [1, 1]) ``` in this way neither the defender nor the attacker will lose any armies. Remember the game instructions: ```For each case, the attacker's die has to be higher than that of the defender to win.``` So I refined your code by just changing the d_scr condition with ```i<=j``` instead of ```i<j```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T11:30:05.000",
"Id": "488608",
"Score": "1",
"body": "@teemran Nice catch! BTW, do you know how to use pytests? I think that might be out of scope for your requested code review, but this is an excellent motivation to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T12:21:09.580",
"Id": "488612",
"Score": "0",
"body": "I don't know, please can you guide me on where and how to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T12:50:57.833",
"Id": "488616",
"Score": "1",
"body": "@teemran Updated the answer to help you get started with pytest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:31:16.603",
"Id": "488628",
"Score": "0",
"body": "This is wow. Many thanks for this"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T01:06:04.173",
"Id": "249296",
"ParentId": "249260",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249272",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T08:07:24.460",
"Id": "249260",
"Score": "12",
"Tags": [
"python",
"game"
],
"Title": "Python Risk game"
}
|
249260
|
<p>I've been coding for a couple weeks now and have nearly finished the first version of a gatsby site for a landing page. My aim is to make the addition of new pages to the website as fast as possible by setting up a system where this can be done quickly, but still work across mobile or desktop. I'd really appreciate some feedback as to whether my code follows best practices and if there are any major rookie errors.</p>
<p>The structure of the website is built around a main sitewrapper, with all content inside the central column:</p>
<pre><code> .siteWrapper {
display: grid;
position: relative;
grid-template-columns: 5vw 90vw 5vw;
grid-auto-rows: auto auto auto auto auto auto;
color: var(--primary-text);
font-family: var(--font);
border-style: var(--border-style);
border-color: var(--border-color);
}
</code></pre>
<p>When the site loads in it uses a snippet of code I borrowed to get the viewport width and height, then compare them such that if the viewport is taller than it is wide, it sets the page to mobile and vice versa, as it returns a component tag, i decided to build the mobile and desktop versions of the page separately, and have them used through this. This piece of code is loaded in using loadable-component as when using netlify it couldn't find the viewport when server-side-rendered so crashed. The file landing-page.js contains the piece of borrowed code and imports the two page layouts to be used. This means that the main page file only contains this:</p>
<pre><code>import React from "react";
import loadable from "@loadable/component";
const PageLayout = loadable(() => import("./landing-page.js"))
const IndexPage = () => (
<PageLayout/>
)
export default IndexPage
</code></pre>
<p>All text in the site is styled based on a series of classes held in the layout.css file, with different styling for mobile and desktop (with larger text on mobile for visibility etc.):</p>
<pre><code>.mobileTextHeading {
color: var(--primary-text);
font-family: var(--font);
font-weight: var(--mobile-heading-weight);
text-rendering: optimizeLegibility;
font-size: var(--mobile-heading);
line-height: 1.1;
}
.mobileTextBody {
color: var(--primary-text);
font-family: var(--font);
font-weight: 400;
text-rendering: optimizeLegibility;
font-size: var(--mobile-body);
line-height: 1.1;
}
.desktopTextHeading {
color: var(--primary-text);
font-family: var(--font);
font-weight: var(--desktop-heading-weight);
text-rendering: optimizeLegibility;
font-size: var(--desktop-heading);
line-height: 1.1;
}
.desktopTextBody {
color: var(--primary-text);
font-family: var(--font);
font-weight: 400;
text-rendering: optimizeLegibility;
font-size: var(--desktop-body);
line-height: 1.1;
}
</code></pre>
<p>Inside the central column of the sitewrapper is a series of predefined rows which is where i place the components, i had some issues with making these autosize around the components so i used a set of variables for each one which gives them their height, i gave 5 to each one as then i can include the heights given to each part of the component within it, which can be added to give the row height. Here's an example of the first variable set:</p>
<pre><code>:root {
--row1-h1: 0vh;
--row1-h2: 0vh;
--row1-h3: 0vh;
--row1-h4: 0vh;
--row1-h5: 0vh;
--row1: calc(var(--row1-h1) + var(--row1-h2) + var(--row1-h3) + var(--row1-h4) + var(--row1-h5));
</code></pre>
<p>To use these variables i pass a prop with the name of the row used, and the heights of each part of the component (title row, body text row etc.) which are then used to set the properties of the main variable for that row. The props are passed as such:</p>
<pre><code><TripleColumn
headings="desktopTextHeading"
bodytext="desktopTextBody"
triplecolumn1height="30vh"
triplecolumn1row="--row2-h1"
triplecolumn2height="40vh"
triplecolumn2row="--row2-h2"
imgtopleft={speed}
topleft="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tincidunt tincidunt arcu a ultricies. Maecenas laoreet placerat mauris vel aliquam. "
toplefttitle="Lorem ipsum dolor sit amet"
imgtopleftheight="50vw"
imgtopmid={accuracy}
imgtopmidheight="50vw"
topmid="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tincidunt tincidunt arcu a ultricies. Maecenas laoreet placerat mauris vel aliquam. "
topmidtitle="Lorem ipsum dolor sit amet"
topright="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tincidunt tincidunt arcu a ultricies. Maecenas laoreet placerat mauris vel aliquam. "
toprighttitle="Lorem ipsum dolor sit amet"
imgtopright={humanerror}
imgtoprightheight="50vw"
/>
</code></pre>
<p>They are used in the component like so:</p>
<pre><code>function TripleColumn(props) {
let heightVar1 = props.triplecolumn1height;
let heightVar2 = props.triplecolumn2height;
let tripleColumnRowNo1 = props.triplecolumn1row;
let tripleColumnRowNo2 = props.triplecolumn2row;
document.documentElement.style.setProperty(String(tripleColumnRowNo1), heightVar1);
document.documentElement.style.setProperty(String(tripleColumnRowNo2), heightVar2);
document.documentElement.style.setProperty("--tripleColumnH1", heightVar1);
document.documentElement.style.setProperty("--tripleColumntext", heightVar2);
return(
<div class="tripleColumn">
<div class='leftTitle'>
<img src={props.imgtopleft} alt={props.imgtopleftalt} height={props.imgtopleftheight}></img>
<p class={props.headings}>{props.toplefttitle}</p>
</div>
<div class='midTitle'>
<img src={props.imgtopmid} alt={props.imgtopmidalt} height={props.imgtopmidheight}></img>
<p class={props.headings}>{props.topmidtitle}</p>
</div>
<div class='rightTitle'>
<img src={props.imgtopright} alt={props.imgtoprightalt} height={props.imgtoprightheight}></img>
<p class={props.headings}>{props.toprighttitle}</p>
</div>
<div class='leftText'>
<p class={props.bodytext}>{props.topleft}</p>
</div>
<div class='midText'>
<p class={props.bodytext}>{props.topmid}</p>
</div>
<div class='rightText'>
<p class={props.bodytext}>{props.topright}</p>
</div>
</div>
);
}
</code></pre>
<p>This is what i saw to be the simplest way i could do it, without rebuilding my code into classes or something similar, is this a reasonable way to do the job or are there other methods of sizing the rows that would make the code run faster/be neater? I've tried autosizing for the main rows but for some reason haven't managed to make that work.</p>
<p>To see the code in context, the github repo is here:
<a href="https://github.com/bolty-boi/component-testing.git" rel="nofollow noreferrer">https://github.com/bolty-boi/component-testing.git</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:39:03.233",
"Id": "488496",
"Score": "0",
"body": "Do you have a link to the page and the entirety of the source?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:41:54.873",
"Id": "488497",
"Score": "0",
"body": "Can we see the code you mentioned you 'borrowed'? What's landing-page.js? Can we get a layout of project structure? What's your directory structure?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:24:45.277",
"Id": "249264",
"Score": "2",
"Tags": [
"javascript",
"css",
"react.js"
],
"Title": "Device-specific page design with gatsby"
}
|
249264
|
<p>Much like <a href="https://codereview.stackexchange.com/questions/226073/function-composition-in-c">this question</a> I'm attempting to write in C++ something which can resemble Haskell's <code>(.)</code> function as much as possible, which is basically Chapter 1's second exercise from <a href="https://bartoszmilewski.com/2014/11/04/category-the-essence-of-composition/" rel="nofollow noreferrer">Bartosz Milewski's Category Theory for Programmers</a>.</p>
<p><a href="https://codereview.stackexchange.com/questions/134627/c-identity-function">This similar question</a> about writing the <em>identity</em> function served as a reference too.</p>
<p><a href="https://stackoverflow.com/a/42799251/5825294">This answer on StackOverflow</a> reassured me that <code>decltype</code> used on lambdas' <code>auto</code> parameters is equivalent to <code>decltype</code> used on template parameters.</p>
<p>And this is what I came up with:</p>
<pre class="lang-cpp prettyprint-override"><code>static constexpr struct compose_t {
template <typename F, typename G>
constexpr decltype(auto) operator()(F&& f, G&& g) const noexcept {
return [&f,&g](auto&& x){
return f(g(std::forward<decltype(x)>(x)));
};
}
} compose;
</code></pre>
<p>Some thoughts:</p>
<ul>
<li><code>operator()</code> takes <code>f</code> and <code>g</code> by reference, and the returned lambda captures them by reference; and I made this choice thinking it should make passing non-stateless callables cheaper, but <a href="https://stackoverflow.com/questions/8196345/passing-functor-object-by-value-vs-by-reference-c">I'm not sure I made the right choice</a>. Another reference is <a href="https://stackoverflow.com/a/5522198/5825294">this</a>.</li>
<li>Since I'm passing them by reference, I had to choose between <code>const&</code> and <code>&&</code>, and I've basically chosen randomly.</li>
<li>I've not concerned myself with variadics, as I wanted a <em>binary</em> function composition "operator", in line with Haskell's <code>(.) :: (b -> c) -> (a -> b) -> a -> c</code>.</li>
<li>I cannot compose <code>compose</code> with something else, because it is binary, whereas the implementation implicitly assumes that <code>F</code> and <code>G</code> be unary. I guess making something like <code>compose(compose,compose)</code> (which is <code>(.).(.)</code> in Haskell) possible would be up to a partial application "facility".</li>
</ul>
<p>This is a code where I tried to test it:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cassert>
#include <utility>
// ... the code from above
static constexpr struct changesign_t {
template<typename T>
constexpr decltype(auto) operator()(T&& t) const noexcept { return -t; };
} changesign;
int square(int x) { return x*x; }
int twice(int x) { return 2*x; }
int main() {
assert(compose(square,twice)(3) == 36);
assert(compose([](int x){ return x*x; },[](int x){ return 2*x; })(3) == 36);
assert(compose(changesign, compose([](auto x){ return x*x; }, [](auto x){ return 2*x; }))(3) == -36);
}
</code></pre>
|
[] |
[
{
"body": "<p>There's no need to use a <code>struct compose_t</code> to wrap <code>operator()</code>, you can just move <code>operator()</code> out of it and rename it <code>compose()</code>:</p>\n<pre><code>template <typename F, typename G>\nconstexpr decltype(auto) compose(F&& f, G&& g) noexcept {\n return [&f,&g](auto&& x){\n return f(g(std::forward<decltype(x)>(x)));\n };\n}\n</code></pre>\n<p>Now it is also much closer to the code written in <a href=\"https://codereview.stackexchange.com/questions/226073/function-composition-in-c\">this post you mentioned</a>, except of course you are limited to composing only two unary functions.</p>\n<p>Other than that, if you can live with the restrictions you have, I see nothing wrong with your implementation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T15:38:27.947",
"Id": "250328",
"ParentId": "249266",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250328",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T09:49:26.287",
"Id": "249266",
"Score": "3",
"Tags": [
"c++",
"haskell",
"functional-programming",
"template-meta-programming",
"type-safety"
],
"Title": "Haskell-like function composition function"
}
|
249266
|
<p>Is there a better way to check if the variable <code>x</code> is in the 0-255 range and:</p>
<ul>
<li>if <code>x</code> is less than 255, add <code>colVel</code> to it</li>
<li>if <code>x</code> equals 255 minus <code>colVel</code> from it.</li>
</ul>
<p>My implementation, in Python 3.8.</p>
<pre class="lang-py prettyprint-override"><code>if 0 <= x < colVel:
flag = True
if (255-colVel) < x < 255:
x = 255
if (255-colVel) <= x <= 255:
flag = False
if flag == True:
x += colVel
if flag == False:
x -= colVel
</code></pre>
<p>This section of code is a function that creates iridescence while an object moves. This is all of my code, and I'm happy for it to be reviewed.</p>
<pre class="lang-py prettyprint-override"><code>import pygame
import random
pygame.init()
win = pygame.display.set_mode((800,600))
pygame.display.set_caption('Chachi')
x = 50
y = 50
width = 2
height = 2
vel = 5
colVel = 10
rf = True
gf = True
bf = True
running = True
def irid(r, g, b, rFlag=True, gFlag=True, bFlag=True):
def rgbRange(x, flag):
if 0<= x< colVel:
x = random.randint(1, 100)
flag = True
if (255-colVel) < x < 255:
x = 255
if (255-colVel) <= x <= 255:
flag = False
if flag==True:
x += colVel
if flag==False:
x -= colVel
return x, flag
r, rFlag = rgbRange(r, rFlag)
g, gFlag = rgbRange(g, gFlag)
b, bFlag = rgbRange(b, bFlag)
return r, g, b, rFlag, gFlag, bFlag
r = irid(0, 255, 0)[0]
g = irid(0, 255, 0)[1]
b = irid(0, 255, 0)[2]
while running:
pygame.time.delay(1)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
r, g, b, rf, gf, bf = irid(r, g, b, rf, gf, bf)
if keys[pygame.K_RIGHT]:
x += vel
r, g, b, rf, gf, bf = irid(r, g, b, rf, gf, bf)
if keys[pygame.K_UP]:
y -= vel
r, g, b, rf, gf, bf = irid(r, g, b, rf, gf, bf)
if keys[pygame.K_DOWN]:
y += vel
r, g, b, rf, gf, bf = irid(r, g, b, rf, gf, bf)
pygame.draw.rect(win, (r, g, b), (x, y, width, height) )
pygame.display.update()
pygame.quit()
</code></pre>
<p><a href="https://i.stack.imgur.com/xHDck.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xHDck.png" alt="Image of all the code running" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T12:03:39.073",
"Id": "488519",
"Score": "0",
"body": "Your specification is unclear and I don't think your implementation gets it right..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T12:32:09.143",
"Id": "488522",
"Score": "0",
"body": "As for what section to review - it's up to a reviewer. I couldn't ask to review the whole code, as its too big to ask. If you can propose the better practice for the whole task - it would be only better. But as for my first section with 255 range checker I absolutely sure there is much more of a solution. Maybe I don't even need a function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:05:40.533",
"Id": "488524",
"Score": "2",
"body": "The amount of code above is quite small, so it's perfectly fine for you to ask for a review of all of it. :) If it fits in the question then you can ask us to review it all. If it doesn't fit in the question you can post multiple questions so we review all of it."
}
] |
[
{
"body": "<h1>Avoid repeating yourself</h1>\n<p>First, avoid having separate variables for <code>r</code>, <code>g</code> and <code>b</code>. It means you have to write all code three times. Just store the three components in a list, like so:</p>\n<pre><code>color = [0, 255, 0]\n</code></pre>\n<p>Then you can pass <code>color</code> to other functions, and have those functions iterate over the elements of the list.</p>\n<h1>Better way to create a triangle wave</h1>\n<p>What you are doing is basically creating a <a href=\"https://en.wikipedia.org/wiki/Triangle_wave\" rel=\"nofollow noreferrer\">triangle wave</a> shape for the intensity of each color component. Instead of keeping the current color value and a flag to store whether you are on the increasing slope or decreasing slope, just store a variable that holds the phase in a full cycle of the triangle wave.</p>\n<p>In this case, I would store an integer between 0 and 511 for each color component. Initialize the phase like you did the color vector before:</p>\n<pre><code>phase = [0, 255, 0]\n</code></pre>\n<p>When updating the phase, do:</p>\n<pre><code>for i in range(3):\n phase[i] += colorVel\n phase[i] %= 512\n</code></pre>\n<p>Of course, this gives a sawtooth wave, and the values you get will be too high, but now you can map it onto a triangle wave with the correct amplitude:</p>\n<pre><code>color = list(map(lambda x: x if x < 256 else 511 - x, phase))\n</code></pre>\n<h1>Create a class to store the state of the iridescence</h1>\n<p>Even better would be to have a class manage all the internal state of an iridescence color, and allow it to be called as a function that generates the next color:</p>\n<pre><code>class Iridecence:\n def __init__(self, r, g, b, colVel=10):\n self.phase = [r, g, b]\n self.colVel = colVel\n\n def __call__(self):\n for i in range(3):\n if self.phase[i] < self.colVel:\n self.phase[i] = random.randint(1, 100)\n self.phase[i] += self.colVel\n self.phase[i] %= 512;\n return list(map(lambda x: x if x < 256 else 511 - x, self.phase))\n</code></pre>\n<p>Now you can use this as follow in your code:</p>\n<pre><code>irid = Iridescence(0, 255, 0)\ncolor = irid()\n\nwhile running:\n ...\n if keys[pygame.K_LEFT]:\n x -= vel\n color = irid()\n ...\n pygame.draw.rect(win, color, (x, y, width, height) )\n pygame.display.update()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:54:13.043",
"Id": "488530",
"Score": "2",
"body": "a m a z i n g. Thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:02:38.010",
"Id": "249274",
"ParentId": "249269",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249274",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T11:05:36.157",
"Id": "249269",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x",
"pygame"
],
"Title": "Checking if a value is in the RGB range and then increment/decrement"
}
|
249269
|
<p>Below is my app's start/stop procedure, start/stop code is handled by a single-threaded <code>ThreadPoolExecutor</code>, so I'm guaranteed there's only one thread can be active at the same time.</p>
<p>I'm asking about <code>isRunning</code> variable. Is making the variable <code>volatile</code> enough?
The variable will be accessed (read/modify) from different threads (but only one at the same time!)</p>
<pre><code>public final class Work {
private static final ThreadPoolExecutor processor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1),
new ThreadPoolExecutor.DiscardPolicy());
private static final Runnable startQuery = Work::startProcedure,
stopQuery = Work::stopProcedure;
private static boolean isRunning = false;
private Work() {}
private static void startProcedure() {
isRunning = true;
//<some code>
}
private static void stopProcedure() {
//<some code>
isRunning = false;
}
//------Public API
public static void start() {
processor.execute(startQuery);
}
public static void stop() {
processor.execute(stopQuery);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:43:00.313",
"Id": "488527",
"Score": "1",
"body": "if only those `stop`/`stop` funcs update that `isRunning`, then marking the var as `volatile` would be enough **if and if** the update is `direct-set`, and not `read-update`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T11:24:41.183",
"Id": "249271",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Is volatile enough in this case?"
}
|
249271
|
<p>The following is the program 3.2.6. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<pre><code>// This data type is the basis for writing Java programs that manipulate complex numbers.
public class Complex
{
private final double re;
private final double im;
public Complex(double real, double imag)
{ re = real; im = imag; }
public double re()
{ return re; }
public double im()
{ return im; }
public double abs()
{ return Math.sqrt(re*re + im*im); }
public Complex plus(Complex b)
{
double real = re + b.re;
double imag = im + b.im;
return new Complex(real, imag);
}
public Complex times(Complex b)
{
double real = re*b.re - im*b.im;
double imag = re*b.im + im*b.re;
return new Complex(real, imag);
}
public String toString()
{
return re + " + " + im + "i";
}
public static void main(String[] args)
{
Complex z0 = new Complex(1.0, 1.0);
Complex z = z0;
z = z.times(z).plus(z0);
z = z.times(z).plus(z0);
System.out.println(z);
}
}
</code></pre>
<p>The next section in the book discusses the creation of <a href="https://mathworld.wolfram.com/MandelbrotSet.html" rel="nofollow noreferrer">Mandelbrot set</a> in black-and-white. But before studying the program written by the authors of the book I tried to implement my own program to draw the Mandelbrot set in color.</p>
<p>Here is my program:</p>
<pre><code>import java.awt.Color;
public class MandelbrotSet
{
public static int checkDegreeOfDivergence(Complex c, int degree)
{
Complex nextRecurrence = c;
for (int i = 0; i < degree; i++)
{
if (nextRecurrence.abs() >= 2) return i;
nextRecurrence = nextRecurrence.times(nextRecurrence).plus(c);
}
return degree;
}
public static double randomize(double left, double right)
{
return left + Math.random()*(right-left);
}
public static Color[] createRandomColors(int degree)
{
Color[] colors = new Color[degree+1];
colors[degree] = new Color(0,0,0);
double r = Math.random();
int red = 0, green = 0, blue = 0;
if (r < 1.0/3.0)
{
for (int i = 0; i < degree; i++)
{
red = 255;
green = (int) randomize(0,255);
blue = (int) randomize(0,255);
colors[i] = new Color(red,green,blue);
}
}
else if (r < 2.0/3.0)
{
for (int i = 0; i < degree; i++)
{
red = (int) randomize(0,255);
green = 255;
blue = (int) randomize(0,255);
colors[i] = new Color(red,green,blue);
}
}
else if (r < 3.0/3.0)
{
for (int i = 0; i < degree; i++)
{
red = (int) randomize(0,255);
green = (int) randomize(0,255);
blue = 255;
colors[i] = new Color(red,green,blue);
}
}
return colors;
}
public static void main(String[] args)
{
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
int contrast = Integer.parseInt(args[2]);
double x = Double.parseDouble(args[3]);
double y = Double.parseDouble(args[4]);
double zoom = Double.parseDouble(args[5]);
Picture mandelbrotSet = new Picture(width,height);
Color[] colors = createRandomColors(contrast);
for (int j = 0; j < width; j++)
{
for (int i = 0; i < height; i++)
{
double realPart = x + zoom*j/width;
double imaginaryPart = y + zoom*i/height;
Complex c = new Complex(realPart,imaginaryPart);
int degreeOfDivergence = checkDegreeOfDivergence(c, contrast);
Color color = colors[degreeOfDivergence];
mandelbrotSet.set(j,i,color);
}
}
mandelbrotSet.show();
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/Picture.html" rel="nofollow noreferrer">Picture</a> is a simple API written by the authors of the book. I checked my program and it works. Here are a few instances of it:</p>
<p>Input: 3840 2160 255 -0.1015 0.833 0.01</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/dKk5w.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dKk5w.jpg" alt="enter image description here" /></a></p>
<p>Input 3840 2160 255 -0.2404 0.8354 0.001</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/oMaNB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oMaNB.jpg" alt="enter image description here" /></a></p>
<p>Input: 3840 2160 255 0.1015 -0.633 0.01</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/XjJYa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjJYa.png" alt="enter image description here" /></a></p>
<p>One thing to note: The above pictures are not in the original resolution. Due to size restriction of uploads I took screenshots of the original images. I did not decrease the resolution of the above pictures directly from the command-line because I wanted them to look prettier.</p>
<p>One other thing to note: Since blue is my favorite color, they are intentionally in the blue spectrum.</p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
<p><strong>New edit:</strong></p>
<p>I added the following method to the <code>Complex</code> class:</p>
<pre><code>public Complex conjugate()
{
return new Complex(re, -1.0*im);
}
</code></pre>
<p>and the following method to the <code>MandelbrotSet</code> class:</p>
<pre><code>public static int checkDegreeOfDivergenceForMandelbar(Complex c, int degree)
{
Complex nextRecurrence = c;
for (int i = 0; i < degree; i++)
{
if (nextRecurrence.abs() >= 2) return i;
nextRecurrence = (nextRecurrence.conjugate()).times(nextRecurrence.conjugate()).plus(c);
}
return degree;
}
</code></pre>
<p>Here is one instance of this <a href="https://mathworld.wolfram.com/MandelbarSet.html" rel="nofollow noreferrer">Mandelbar set</a>:</p>
<p>Input: 3840 2160 255 -1.5 -1.5 3</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/U1n7D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U1n7D.png" alt="enter image description here" /></a></p>
<p><strong>Newer edit:</strong></p>
<p>I found an ASTONISHING color palette from the book site and applied it as follows (within the <code>createRandomColors</code> method):</p>
<pre><code> for (int i = 0; i < degree; i++)
{
red = 13*(256-i) % 256;
green = 7*(256-i) % 256;
blue = 11*(256-i) % 256;
colors[i] = new Color(red,green,blue);
}
</code></pre>
<p>Here is one of the above results with this new color palette:</p>
<p><a href="https://i.stack.imgur.com/wO2mj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wO2mj.jpg" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:46:23.563",
"Id": "488528",
"Score": "2",
"body": "Unfortunately, I've forgotten too much Java to be able to comment on anything here, except, playing around with coloring is a *lot* of fun. You're doing it quite different than I normally do. [I usually create a \"color function\"](https://github.com/carcigenicate/mandelbrot/blob/500eb8c1a4ba4dd2c7430f84e54e1e5a042a96cb/src/mandelbrot/color_options.clj#L25) that accepts the current (r)eal and (i)maginary values, and the (n)umber of iterations that it failed at, multiply each by multipliers passed in, then wrap the result so it's in the range 0-255. You can get great coloring from that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:33:42.667",
"Id": "488545",
"Score": "0",
"body": "@Carcigenicate Thank you very much. I was actually thinking about the way in which you did it. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:47:05.760",
"Id": "488548",
"Score": "1",
"body": "Np. My [PHP port](https://codereview.stackexchange.com/q/248895/46840) might be easier to read; Clojure is a bit obscure. And unfortunately, this technique is obviously limited to relatively simple linear equations, but it still leads to a ton of different possible designs. I spent a solid week playing around with coloring. I have several gigabytes of pictures produced from it. Good times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T19:02:51.717",
"Id": "488549",
"Score": "0",
"body": "Wow! I might do it as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T19:26:02.347",
"Id": "488550",
"Score": "0",
"body": "@Carcigenicate Check out the new color palette."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T19:33:03.963",
"Id": "488551",
"Score": "0",
"body": "Oh ya, that one's pretty neat. It reminds me of [this](https://drive.google.com/file/d/1pbukuswRhbg7iKifzG7bp1RXZ787oXA1/view?usp=sharing) one of mine. Also note, you're not supposed to change code once it's been posted; although I'm not sure about adding new code specifically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T19:34:23.920",
"Id": "488552",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112943/discussion-between-carcigenicate-and-khashayar-baghizadeh)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T19:40:01.783",
"Id": "488553",
"Score": "0",
"body": "I think one should not edit after a posted answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T07:38:01.263",
"Id": "488584",
"Score": "0",
"body": "You might want to abstract the createRandomColors behind an interface to allow to easily switch the coloring strategy without modifying other parts of your program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:56:31.197",
"Id": "488643",
"Score": "0",
"body": "@slepic Thank you very much for the great suggestion."
}
] |
[
{
"body": "<p>After experimenting with my program for two days, I found that the use of <code>degree</code> within the methods <code>checkDegreeOfDivergence</code> and <code>createRandomColors</code> does not increase the quality of the pictures and so I removed it.</p>\n<p>Also to increase the variety of colors I changed the following code</p>\n<pre><code>public static Color[] createRandomColors(int degree)\n{\n Color[] colors = new Color[degree+1];\n colors[degree] = new Color(0,0,0);\n double r = Math.random();\n int red = 0, green = 0, blue = 0;\n for (int i = 0; i < degree; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(red,green,blue);\n }\n return colors;\n}\n</code></pre>\n<p>into</p>\n<pre><code>public static Color[] createRandomColors()\n{\n Color[] colors = new Color[256];\n double r = Math.random();\n int red = 0, green = 0, blue = 0;\n if (r < 1.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(red,green,blue);\n }\n }\n else if (r < 2.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(red,blue,green);\n }\n }\n else if (r < 3.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(green,red,blue);\n }\n }\n else if (r < 4.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(green,blue,red);\n }\n }\n else if (r < 5.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(blue,red,green);\n }\n }\n else if (r < 6.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(blue,green,red);\n }\n }\n return colors;\n}\n</code></pre>\n<p>and so there is no need for <code>randomize</code> anymore and the whole program changes as follows</p>\n<pre><code>import java.awt.Color;\n\npublic class MandelbrotSet \n{\n public static int checkDegreeOfDivergence(Complex c)\n {\n Complex nextRecurrence = c;\n for (int i = 0; i < 255; i++)\n {\n if (nextRecurrence.abs() >= 2) return i;\n nextRecurrence = nextRecurrence.times(nextRecurrence).plus(c);\n }\n return 255;\n }\n public static int checkDegreeOfDivergenceForMandelblar(Complex c)\n {\n Complex nextRecurrence = c;\n for (int i = 0; i < 255; i++)\n {\n if (nextRecurrence.abs() >= 2) return i;\n nextRecurrence = (nextRecurrence.conjugate()).times(nextRecurrence.conjugate()).plus(c);\n }\n return 255;\n }\n public static Color[] createRandomColors()\n {\n Color[] colors = new Color[256];\n double r = Math.random();\n int red = 0, green = 0, blue = 0;\n if (r < 1.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(red,green,blue);\n }\n }\n else if (r < 2.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(red,blue,green);\n }\n }\n else if (r < 3.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(green,red,blue);\n }\n }\n else if (r < 4.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(green,blue,red);\n }\n }\n else if (r < 5.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(blue,red,green);\n }\n }\n else if (r < 6.0/6.0) \n {\n for (int i = 0; i < 256; i++)\n {\n red = 13*(256-i) % 256;\n green = 7*(256-i) % 256;\n blue = 11*(256-i) % 256;\n colors[i] = new Color(blue,green,red);\n }\n }\n return colors;\n }\n public static void main(String[] args)\n {\n int width = Integer.parseInt(args[0]);\n int height = Integer.parseInt(args[1]);\n double x = Double.parseDouble(args[2]);\n double y = Double.parseDouble(args[3]);\n double zoom = Double.parseDouble(args[4]);\n Picture mandelbrotSet = new Picture(width,height);\n Color[] colors = createRandomColors();\n for (int j = 0; j < width; j++)\n {\n for (int i = 0; i < height; i++)\n {\n double realPart = x + zoom*j/width;\n double imaginaryPart = y + zoom*i/height;\n Complex c = new Complex(realPart,imaginaryPart);\n int degreeOfDivergence = checkDegreeOfDivergence(c);\n Color color = colors[degreeOfDivergence];\n mandelbrotSet.set(j,i,color); \n }\n }\n mandelbrotSet.show();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T15:40:48.223",
"Id": "249352",
"ParentId": "249273",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T11:55:29.277",
"Id": "249273",
"Score": "11",
"Tags": [
"java",
"performance",
"beginner",
"fractals"
],
"Title": "Generating colorful Mandelbrot and Mandelbar set wallpapers"
}
|
249273
|
<p>I'm trying to code in a Rust a function, that gives the maximum product of adjacent digits.</p>
<p>So given the string <code>123456789</code>, with 3 adjacent digits, the maximum is <code>7 * 8 * 9 = 504</code>.</p>
<p>I've tried to come up with this current functional solution (see previous edit for longer solutions). Could it be shortened? Comments are welcome.</p>
<p>The <code>log</code> is here, and desired, so the code runs quickly.</p>
<pre class="lang-rust prettyprint-override"><code>use std::iter::Map;
use std::str::Chars;
fn iter_log_digits(str: &str) -> Map<Chars<'_>, fn(char) -> f64> {
str.chars().map(|c: char| (c.to_digit(10).unwrap() as f64).ln())
}
/// Returns the maximum log sum of adjacent digit characters.
/// # Arguments
/// - `str`: Assumes there are no 0s.
/// - `adj_count`: The number of adjacent digit characters.
fn max_adj_log_sum_no_zeros(str: &str, adj_count: usize) -> f64 {
if str.len() < adj_count {
return 0.;
}
let log_first: f64 = iter_log_digits(&str[..adj_count]).sum();
iter_log_digits(&str).zip(iter_log_digits(&str[adj_count..])).fold(
(log_first, log_first), // `(log_cur, log_max)`
|(log_cur, log_max), (x_left, x_right)| {
let log_next = log_cur - x_left + x_right;
(log_next, log_max.max(log_next))
}
).1
}
fn max_product_no_zeros(str: &str, adj_count: usize) -> u64 {
max_adj_log_sum_no_zeros(str, adj_count).exp().round() as u64
}
</code></pre>
<p><code>max_product_no_zeros("123456789", 3)</code> should return 504.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T15:53:48.987",
"Id": "488532",
"Score": "0",
"body": "You're returning (approximately) `(504.0).ln()`, that is, roughly 6.222, not `504`. What's the actual spec here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T15:54:33.390",
"Id": "488533",
"Score": "0",
"body": "@trentcl Ah forgot to add `as u64`, that should fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T15:57:37.657",
"Id": "488534",
"Score": "0",
"body": "Not what I was objecting to. `504` is not the same number as `6.222576268071368`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T15:59:36.310",
"Id": "488535",
"Score": "0",
"body": "@trentcl Did you run `max_adj_log_sum_no_zeros(\"123456789\", 3).exp().round() as u64`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T16:08:28.553",
"Id": "488536",
"Score": "1",
"body": "You said: \"I'm trying to code in a Rust a function, that gives the maximum product of adjacent digits.\" But the function you wrote doesn't do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T16:13:01.880",
"Id": "488537",
"Score": "0",
"body": "@trentcl It just takes the log, which is easier. It is trivial to just add `.exp().round() as u64` at the end of the function."
}
] |
[
{
"body": "<p>General observations:</p>\n<ul>\n<li><p>An indentation of two spaces is quite small. The standard formatting uses four spaces.</p>\n</li>\n<li><p>Names like <code>Map</code> and <code>Chars</code> read better with their modules: <code>iter::Map</code>, <code>str::Chars</code>.</p>\n</li>\n<li><p><code>str: &str</code> — don't do that.</p>\n</li>\n<li><p>When <code>str</code> is not entirely made of decimal digits, your function panics by <code>unwrap</code>ping. Reporting an error via <code>Result</code> is generally preferred. Magic also happens when <code>str</code> contains zeros.</p>\n</li>\n<li><p>Using <code>fold</code> here makes the semantics harder to understand. A simple <code>for</code> loop might be more suitable.</p>\n</li>\n</ul>\n<hr />\n<p>Now, my intuition tells me floating point calculations are less efficient than just doing the operations on integers, so I wrote a benchmark. Here's the result that I got:</p>\n<pre class=\"lang-none prettyprint-override\"><code>running 4 tests\ntest l_f::tests::test ... ignored\ntest simonzack::tests::test ... ignored\ntest l_f::tests::bench ... bench: 10,189,230 ns/iter (+/- 278,958)\ntest simonzack::tests::bench ... bench: 16,865,990 ns/iter (+/- 440,350)\n\ntest result: ok. 0 passed; 0 failed; 2 ignored; 2 measured; 0 filtered out\n</code></pre>\n<p>Using integers resulted in a ~1.7x speedup. Do note that this benchmark is very crude, and you might want to measure your own use cases.</p>\n<hr />\n<p>For reference, here's the code for the benchmark. (Error checking is omitted for simplicity.)</p>\n<pre><code>#![feature(test)]\n\nextern crate test;\n\nmod l_f {\n fn to_digits(digits: &str) -> impl Iterator<Item = u64> + '_ {\n digits.chars().map(|c| c.to_digit(10).unwrap().into())\n }\n\n pub fn max_product_no_zeros(digits: &str, length: usize) -> u64 {\n if digits.len() < length {\n return 0;\n }\n\n let mut current_product: u64 = to_digits(&digits[..length]).product();\n let mut max_product = current_product;\n\n for (left, right) in to_digits(digits).zip(to_digits(&digits[length..])) {\n current_product = current_product / left * right;\n max_product = max_product.max(current_product);\n }\n\n max_product\n }\n\n #[cfg(test)]\n mod tests {\n use test::Bencher;\n\n #[test]\n fn test() {\n assert_eq!(super::max_product_no_zeros("31415926", 3), 108);\n }\n\n #[bench]\n fn bench(b: &mut Bencher) {\n let digits = test::black_box("9".repeat(1_000_000));\n\n b.iter(|| super::max_product_no_zeros(&digits, 10));\n }\n }\n}\n\nmod simonzack {\n use std::iter::Map;\n use std::str::Chars;\n\n fn iter_log_digits(str: &str) -> Map<Chars<'_>, fn(char) -> f64> {\n str.chars()\n .map(|c: char| (c.to_digit(10).unwrap() as f64).ln())\n }\n\n /// Returns the maximum log sum of adjacent digit characters.\n /// # Arguments\n /// - `str`: Assumes there are no 0s.\n /// - `adj_count`: The number of adjacent digit characters.\n fn max_adj_log_sum_no_zeros(str: &str, adj_count: usize) -> f64 {\n if str.len() < adj_count {\n return 0.;\n }\n let log_first: f64 = iter_log_digits(&str[..adj_count]).sum();\n iter_log_digits(&str)\n .zip(iter_log_digits(&str[adj_count..]))\n .fold(\n (log_first, log_first), // `(log_cur, log_max)`\n |(log_cur, log_max), (x_left, x_right)| {\n let log_next = log_cur - x_left + x_right;\n (log_next, log_max.max(log_next))\n },\n )\n .1\n }\n\n pub fn max_product_no_zeros(str: &str, adj_count: usize) -> u64 {\n max_adj_log_sum_no_zeros(str, adj_count).exp().round() as u64\n }\n\n #[cfg(test)]\n mod tests {\n use test::Bencher;\n\n #[test]\n fn test() {\n assert_eq!(super::max_product_no_zeros("31415926", 3), 108);\n }\n\n #[bench]\n fn bench(b: &mut Bencher) {\n let digits = test::black_box("9".repeat(1_000_000));\n\n b.iter(|| super::max_product_no_zeros(&digits, 10));\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T10:04:00.447",
"Id": "490090",
"Score": "1",
"body": "Thanks for the benchmark, it helped and I realized there's no point in the logs, as I need to store the result in an `u64` anyway at the end. I ended up just using `.scan()` and `.max()` after discovering the `.scan()` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T10:07:05.743",
"Id": "490091",
"Score": "0",
"body": "@simonzack Indeed, `scan` method seems the most appropriate here. I missed it when writing the benchmark."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T01:11:48.793",
"Id": "249867",
"ParentId": "249275",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249867",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T14:00:54.710",
"Id": "249275",
"Score": "3",
"Tags": [
"rust",
"iterator"
],
"Title": "Rust shortest way to find the maximum product of a fixed length substring"
}
|
249275
|
<p>My programming background is mostly C++/C#. Lately i got interested in writing some C. So i implemented Conway's Game of Life using SDL2 for visualization. This is actually my first program written in C. Since im quite comfortable in writing C++ it's probably not completely awful.</p>
<p>I would like to get some review/feedback/suggestions for improvements about my code.</p>
<p>Upon start you can set up the starting pattern (left-click = alive, right-click = dead) and pressing the Enter key starts the simulation. Here is the code:</p>
<pre><code>#define SDL_MAIN_HANDLED
#include <SDL.h>
#include <time.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
enum State
{
INIT,
RUNNING,
EXIT
};
struct Cell
{
bool alive;
bool next;
};
static const int32_t field_size = 200; // the amount of cells in both dimensions
static const int32_t pixels_per_cell = 6; // size of a displayed cell in pixels
static const Uint32 tickrate = 200; // update frequency in ms
static SDL_Window* window = NULL;
static SDL_Renderer* renderer = NULL;
static struct Cell** cells = NULL;
static enum State state = INIT;
static bool initialize(void)
{
if(SDL_Init(SDL_INIT_VIDEO) != 0)
{
return false;
}
int32_t window_size = field_size * pixels_per_cell;
window = SDL_CreateWindow("Conway's Game of Life", 50, 50, window_size, window_size, SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_ShowWindow(window);
cells = calloc(field_size, sizeof(struct Cell*));
for(int32_t i = 0; i < field_size; i++)
{
cells[i] = calloc(field_size, sizeof(struct Cell));
}
return true;
}
static void cleanup(void)
{
for(int32_t i = 0; i < field_size; i++)
{
free(cells[i]);
}
free(cells);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
static void set_field_from_mousepos(const Sint32 mouse_x, const Sint32 mouse_y, const bool value)
{
uint32_t x = mouse_x / pixels_per_cell;
uint32_t y = mouse_y / pixels_per_cell;
cells[x][y].alive = value;
}
static void on_mouse_down(const SDL_MouseButtonEvent* const event)
{
if(state == INIT)
{
switch(event->button)
{
case SDL_BUTTON_LEFT:
set_field_from_mousepos(event->x, event->y, true);
break;
case SDL_BUTTON_RIGHT:
set_field_from_mousepos(event->x, event->y, false);
break;
}
}
}
static void on_key_down(const SDL_KeyCode key)
{
switch(key)
{
case SDLK_RETURN:
state = RUNNING;
break;
}
}
static void process_messages()
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
state = EXIT;
break;
case SDL_MOUSEBUTTONDOWN:
on_mouse_down(&event.button);
break;
case SDL_KEYDOWN:
on_key_down(event.key.keysym.sym);
break;
}
}
}
static int32_t count_neighbours(const int32_t cell_x, const int32_t cell_y)
{
int32_t count = 0;
for(int32_t x = max(cell_x - 1, 0); x <= min(cell_x + 1, field_size - 1); x++)
{
for(int32_t y = max(cell_y - 1, 0); y <= min(cell_y + 1, field_size - 1); y++)
{
if(!(x == cell_x && y == cell_y) && cells[x][y].alive) // don't count the cell itself
{
count++;
}
}
}
return count;
}
static void update_game(void)
{
// calculate next state for the cells
for(int32_t x = 0; x < field_size; x++)
{
for(int32_t y = 0; y < field_size; y++)
{
int32_t count = count_neighbours(x, y);
if(!cells[x][y].alive && count == 3) // rule 1
{
cells[x][y].next = true;
}
if(cells[x][y].alive && (count < 2 || count > 3)) // rule 2 & 4
{
cells[x][y].next = false;
}
if(cells[x][y].alive && (count == 2 || count == 3)) // rule 3
{
cells[x][y].next = true;
}
}
}
// set alive states for drawing and reset next
for(int32_t x = 0; x < field_size; x++)
{
for(int32_t y = 0; y < field_size; y++)
{
cells[x][y].alive = cells[x][y].next;
cells[x][y].next = false;
}
}
}
static void render_frame()
{
SDL_SetRenderDrawColor(renderer, 50, 50, 50, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
// draw a white rectangle for each living cell
for(int32_t x = 0; x < field_size; x++)
{
for(int32_t y = 0; y < field_size; y++)
{
if (cells[x][y].alive)
{
SDL_Rect rect = {
.x = x * pixels_per_cell,
.y = y * pixels_per_cell,
.w = pixels_per_cell,
.h = pixels_per_cell
};
SDL_RenderFillRect(renderer, &rect);
}
}
}
SDL_RenderPresent(renderer);
}
int main(int argc, char** argv)
{
if(!initialize()) return -1;
Uint32 current_time = SDL_GetTicks(); // ellapsed ms since initialization
while (state != EXIT)
{
process_messages();
if(state == RUNNING)
{
Uint32 delta_time = SDL_GetTicks() - current_time;
if(delta_time >= tickrate)
{
current_time += delta_time;
update_game();
}
}
render_frame();
}
cleanup();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T20:34:19.640",
"Id": "488556",
"Score": "1",
"body": "I would go for a one `[m|c]alloc` for that `cells`, rather than a unique for each cell.\nBesides that, those two `bool`s in `struct Cell` could be hosted with only one `int8` type.(or even better, 4 cells could be hosted with only one `int8`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:34:21.347",
"Id": "488622",
"Score": "0",
"body": "@911992: It's one alloc per *row*, not per Cell. (That would be totally insane; `struct Cell` is smaller than `struct Cell*`). This is just the common sub-optimal choice of using an array of row pointers instead of a single flat array with manual 2D indexing. Like in C++ when people use a vector of vectors. So yes, one single allocation would still be better, but it's not a total disaster like I thought upon seeing your comment."
}
] |
[
{
"body": "<h2>General Observations</h2>\n<p>Initially I was very impressed because the file started with the declaration of 2 enums. All of the functions seem to follow the single responsibility principle and that is great! In <code>main()</code> I might have put the game loop into its own function. I like seeing the <code>cleanup()</code> function.</p>\n<p>I'm really curious about how many classes you would use to implement this program in C++?</p>\n<p>I would separate the game logic from the display logic. That way the game would work with different display mechanisms. It would also be more like some of the object oriented design patterns such as MVC or MVVM.</p>\n<h2>Missing Memory Allocation Check</h2>\n<p>In C++ if new fails it throws an exception that would halt the program unless the exception was handled, this is not true in the C programming language. When memory allocation fails in C the memory allocation function (<code>calloc()</code>, <code>malloc()</code> or <code>realloc()</code>) returns NULL (nullptr in C++). While memory allocation failure is rare these days with the large memories most processors have it can still occur. To prevent a Segmentation Violation or memory corruption the value of the pointer return by the memory allocation function should always be tested before use.</p>\n<p>The example below uses <code>sizeof(**cells)</code> rather than <code>sizeof(struct Cell)</code> because this allows the programmer to make only one edit to the line containing <code>calloc()</code> rather than multiple edits if the type of <code>cells</code> is changed:</p>\n<pre><code>static bool initialize(void)\n{\n if (SDL_Init(SDL_INIT_VIDEO) != 0)\n {\n return false;\n }\n\n int32_t window_size = field_size * pixels_per_cell;\n\n window = SDL_CreateWindow("Conway's Game of Life", 50, 50, window_size, window_size, SDL_WINDOW_OPENGL);\n renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\n SDL_ShowWindow(window);\n\n cells = calloc(field_size, sizeof(*cells));\n if (!cells)\n {\n fprintf(stderr, "The calloc() function returned NULL for the initial allocation of cells\\n");\n return false;\n }\n\n for (int32_t i = 0; i < field_size; i++)\n {\n cells[i] = calloc(field_size, sizeof(**cells));\n if (!cells[i])\n {\n fprintf(stderr, "The calloc() function returned NULL for the allocation of cells[%d]\\n", i);\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n<h2>Prefer <code>size_t</code> Over <code>int</code> for Indexes into Arrays</h2>\n<p>All of the loops in the program seem to utilize <code>int32_t</code> rather than <code>size_t</code>. The type <code>size_t</code> is unsigned and this makes it safer to use as an index because it can't be negative.</p>\n<p>The type <code>Uint32</code> used in <code>main()</code> is not a standard type and doesn't compile on my system, perhaps you meant <code>uint32_t</code> which is part of the C standard.</p>\n<h2>Global Variables</h2>\n<p>I realize the variables aren't quite global because all the variables are static and this is the method for creating private variables in C, but I don't see a good reason why most of the variables aren't declared in <code>main()</code> or as they are needed and passed into the functions that require them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:37:04.357",
"Id": "488573",
"Score": "0",
"body": "using unsigned for never-negative numbers is not always the best case. For example, if a function len(list) returns the length of a list in size_t, then `for(size_t i = 0; i < len(list); i++) {}` will loop quite a few times on a 0-length list, where as if len returned a singed number, this would be work as expected, and iterate through all element except the last."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:11:20.493",
"Id": "488619",
"Score": "1",
"body": "Uint32 comes from SDL and is the type that gets returned by SDL_GetTicks()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:38:52.027",
"Id": "488623",
"Score": "3",
"body": "@CarsonGraham: `0 < 0` is false in the first `i < len(list)` so execution never enters the loop. The danger is when you try to do something like `i < len-1` with unsigned. Perhaps you meant to write that, since you talk about iterating all elements except the last. Yes, you have to be careful to do stuff like `i+1 < len` instead of `i < len-1` if unsigned `len` can be zero."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:48:45.803",
"Id": "249285",
"ParentId": "249279",
"Score": "8"
}
},
{
"body": "<ul>\n<li><p>Reduce number of tests.</p>\n<p>An <code>if</code> in the tight loop is a performance killer. Since you test for <code>cells[x][y].alive</code> in <code>update_game</code> anyway, there is no reason to test for cell equality in <code>count_neighbours</code>. Consider</p>\n<pre><code> static int32_t count_neighbours(const int32_t cell_x, const int32_t cell_y)\n {\n int32_t count = 0;\n\n for(int32_t x = max(cell_x - 1, 0); x <= min(cell_x + 1, field_size - 1); x++) {\n for(int32_t y = max(cell_y - 1, 0); y <= min(cell_y + 1, field_size - 1); y++) {\n if(cells[x][y].alive) {\n count++;\n }\n }\n }\n\n return count;\n }\n</code></pre>\n<p>followed by</p>\n<pre><code> for(int32_t x = 0; x < field_size; x++) {\n for(int32_t y = 0; y < field_size; y++) {\n int32_t count = count_neighbours(x, y);\n\n if(!cells[x][y].alive && count == 3) {\n cells[x][y].next = true;\n }\n\n if(cells[x][y].alive && (count < 3 || count > 4)) {\n cells[x][y].next = false;\n }\n\n if(cells[x][y].alive && (count == 3 || count == 4)) {\n cells[x][y].next = true;\n }\n }\n }\n</code></pre>\n</li>\n<li><p>Simplify logic.</p>\n</li>\n</ul>\n<p>Notice that two last <code>if</code>s are the long way to say</p>\n<pre><code> if (cells[x][y].alive) {\n cells[x][y].next = (count == 3 || count == 4);\n }\n</code></pre>\n<p>and the entire <code>update_game</code> collapses to</p>\n<pre><code> if (cells[x][y].alive) {\n cells[x][y].next = (count == 3 || count == 4);\n } else {\n cells[x][y].next] = (count == 3);\n }\n</code></pre>\n<p>Now, because each branch just assigns a boolean value to the same variable, I would seriously consider a ternary:</p>\n<pre><code> cells[x][y].next = cells[x][y].alive? (count == 3 || count == 4): (count == 3);\n</code></pre>\n<p>Finally, since <code>count == 3</code> makes the cell alive regardless of its previous state,</p>\n<pre><code> cells[x][y].next = (count == 3) || (cells[x][y].alive && count == 4);\n</code></pre>\n<p>seems even cleaner.</p>\n<ul>\n<li><p>Any time you feel obliged to put comments like <code>// calculate next state for the cells</code> and <code>// set alive states for drawing and reset next</code>, consider to factor the commented code into a function. Especially if that piece of code is a loop.</p>\n<p><code>compute_next_state()</code> and <code>set_alive_states()</code> seem like very good names.</p>\n<p>Another argument to factor out <code>set_alive_states()</code> into a function is that it does not depend on the game rules and can be reused.</p>\n</li>\n<li><p>I see no reason to declare <code>cells</code> as an array of pointers.</p>\n<pre><code> static struct Cell * cells;\n</code></pre>\n<p>initialized as</p>\n<pre><code> cells = calloc(field_size, sizeof (struct Cell));\n</code></pre>\n<p>would do as well, with no need to <code>calloc</code> individual cells. As a side note,</p>\n<pre><code> cells = calloc(field_size, sizeof(cells[0]));\n</code></pre>\n<p>is more idiomatic C.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:43:00.390",
"Id": "488624",
"Score": "1",
"body": "*I see no reason to declare cells as an array of pointers.* - yes, but you do need to say something about how to do manual 2D indexing, or cast to a variable-dimension 2D array type. (C99 VLA support makes that legal in C, not C++). The rest of the code does stuff like `cells[x][y]` which will no longer Just Work with `static struct Cell *cells`. An array of pointers to arrays is generally worse for performance but does is easier to write code for when the dimensions are variable. (But the OP has `static const` dimensions so they should just `static struct Call cells[field_size][field_size]`)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:01:11.620",
"Id": "249288",
"ParentId": "249279",
"Score": "8"
}
},
{
"body": "<p>Since this is a standalone program, there is no need to modify functions as <code>static</code></p>\n<p>regarding:</p>\n<pre><code>int main(int argc, char** argv)\n</code></pre>\n<p>Since the parameters <code>argc</code> and <code>argv[]</code> are not used, the compiler (when the warnings are enabled, as they should be) will output two warning messages about unused parameters. Suggest using the other valid signature for <code>main()</code>.</p>\n<pre><code>int main( void )\n</code></pre>\n<p>Several of the functions take no parameters. strongly suggest such functions be declared with <code>( void )</code> as the parameter list. Otherwise the compiler will generate code that can take any number/type of parameters.</p>\n<p>Using the Variable Length Array feature of C, you can avoid the calls to <code>calloc()</code> and <code>free()</code> by simply declaring the 2d array of <code>struct cell</code> types.</p>\n<pre><code>struct cell cells[ field_size ][ field_size ] = {0};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T04:28:50.920",
"Id": "488575",
"Score": "0",
"body": "SDL requires main to always have `argc` and `argv[]` and while not having them could work on some platforms such as linux it will not on some including windows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T08:45:06.733",
"Id": "488593",
"Score": "1",
"body": "I would advice against declaring `cells` as a VLA, since this is a potentially large array, and you might not have enough stack space for it. While Linux, by default, assigns a very generous 8 MiB to the stack of the main thread, so you might get close to a `field_size` of 2048 for a 2-byte `struct cell`, this is not something you should rely on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:45:33.927",
"Id": "488625",
"Score": "1",
"body": "@G.Sliepen: Right, you don't want that to be a local in `main`, you want that to be `static struct Call cells[field_size][field_size]` at global scope so it goes in the BSS. That's how you get it zero-initialized for free like calloc, which automatic storage (a VLA) wouldn't be. Remember that `field_size` is static const so we it doesn't have to be a VLA."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:46:15.853",
"Id": "488626",
"Score": "1",
"body": "Array dimensions are in elements, not bytes, so multiplying by `sizeof( struct cell )` is *not* appropriate inside the array declaration."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:56:03.357",
"Id": "249301",
"ParentId": "249279",
"Score": "1"
}
},
{
"body": "<h2>Use a normal 2D array, not pointers to rows.</h2>\n<p>(Or actually you're doing pointers to columns, since you index as <code>[x][y]</code>, with each vertical column allocated with a separate <code>calloc</code>. Video memory has contiguous rows so it's more normal to draw along each row. Idiomatic C/C++ would normally use <code>[y][x]</code> indexing, looping over <code>y</code> in outer loops and <code>x</code> in inner loops, so you're still looping over contiguous memory of a row-major 2D array. It's basically fine to have the array rows store columns of your image, it's just weird, and maybe makes drawing slower.)</p>\n<p>An array of pointers to arrays is usually less efficient than a single contiguous 2D array; the extra indirection is less efficient for the CPU and harder for the compiler to optimize than scaling by the row width. Especially when the array dimension is a compile-time constant, but even with runtime-variable sizes manual 2D indexing is generally preferable. You could #define a macro like <code>INDEX(x,y,stride)</code> that lets you write <code>cells[INDEX2D(x,y,field_size)]</code>. Or an inline function that returns <code>size_t</code> would also be idiomatic in modern C.</p>\n<p>Or in this case, your simple program has compile-time constant array dimensions.</p>\n<p>In C++ you can use <code>static const</code> integers as array dimensions for global / static variables, like <code>static struct Cell cells[field_size][field_size]</code>. (Implicitly zero-initialized because it's in static storage). But in C, that doesn't work because <a href=\"https://stackoverflow.com/questions/44267827/in-c-why-cant-a-const-variable-be-used-as-an-array-size-initializer/44268234\">a <code>const</code> variable isn't a "constant expression"</a>, unlike in C++ :(</p>\n<p>One of the standard workarounds is to define C constants as preprocessor macros with <code>#define</code>, or as <code>enum</code> constants (examples <a href=\"https://stackoverflow.com/questions/18848537/can-a-const-variable-be-used-to-declare-the-size-of-an-array-in-c/30312817#30312817\">in this SO answer</a>). It's a good idea (and idiomatic for C) to give them all-caps names because they're not variables.</p>\n<p>Instead of keeping just a pointer in static storage, might as well go all-in and use static storage for the whole array. With a zero initializer, it won't take up space in your executable (on normal C implementations that have a BSS).</p>\n<pre><code>enum { FIELD_SIZE = 200 };\nstatic struct Cell cells[FIELD_SIZE][FIELD_SIZE];\n</code></pre>\n<p>If you want to make runtime-variable sizes possible in the future, one large <code>calloc</code> and manual 2D indexing with a macro or helper function is one way. Or you can <a href=\"https://stackoverflow.com/questions/11869056/how-to-cast-simple-pointer-to-a-multidimensional-array-of-fixed-size\">cast</a> to <code>(struct Cell (*)[field_size])</code>, a pointer to an array of <code>struct Cell</code>. A 2D array is an array of arrays, so a pointer to an actual array type is to a 2D array what a pointer to an element is to a 1D array.</p>\n<pre><code> // given void *p; size_t row; size_t col;\n\n struct Cell (*arr)[field_size] = p;\n struct Cell tmp = arr[row][col];\n\n // field_size can even be a variable; C99 VLA support works for casting pointers\n</code></pre>\n<p>You could initialize <code>arr</code> with a <code>calloc()</code> return value to use one calloc as a dynamically allocated 2D array.</p>\n<hr />\n<h2>Use two arrays instead of old/new fields within each element</h2>\n<pre><code> for(x) {\n for(y) {\n cells[x][y].alive = cells[x][y].next;\n cells[x][y].next = false;\n }\n }\n</code></pre>\n<p>That loop over every element would be unnecessary if you instead swapped pointers to whole 2D <code>bool</code> arrays, like <code>prev</code> and <code>curr</code>. You count neighbours in the previous generation then assign a value to the current generation.</p>\n<p>As well as avoiding this work, it's also somewhat better for performance. Same total memory, but only half the cache lines get written in each generation. This is better if it doesn't all fit in L1d cache. Possibly also better cache locality when looking at neighbours in the previous row; it's fewer bytes away.</p>\n<p>If performance and cache footprint were a big deal, you'd try to use less temporary storage, maybe just an extra row at a time. An "old" row is only needed while working on the row immediately below it. (And then maybe you would want an array of row pointers so you could swap out the storage for one row without copying.) And / or you'd use denser storage, like 1 or 2 bits per cell instead of a whole <code>bool</code> which is at least as large as a <code>char</code>. (In practice 1 byte on normal C implementations). Also, just for fun, <a href=\"https://lemire.me/blog/2018/07/18/accelerating-conways-game-of-life-with-simd-instructions/\" rel=\"nofollow noreferrer\">SIMD implementations of Life are possible</a>, giving massive speedups on modern x86.</p>\n<h2>Don't busy-wait, ideally sleep until an event or timeout</h2>\n<p>Your main loop just calls <code>SDL_PollEvent</code> (via your <code>process_messages</code> wrapper) and keeps checking the time until it's time to actually update the field.</p>\n<p>Nowhere does it sleep, not even for like 10 or 20 milliseconds.</p>\n<p>Ideally SDL would have a way to give <code>SDL_WaitEvent</code> a timeout so it can block until an event, or until you want to wake up and update, whichever comes first. Like the POSIX <code>select()</code> function. But unfortunately it seems SDL doesn't have a way to do that easily or maybe at all. So for this toy program, perhaps just put a 10 or 30 ms sleep into your main loop, saving <em>some</em> CPU but still waking it up unnecessarily between times you want to actually draw.</p>\n<p>Actually sleeping for 200ms would delay response to mouse clicks too long.</p>\n<p>Make sure to poll until you empty the message queue before sleeping, if you introduce a sleep. See <a href=\"https://stackoverflow.com/questions/56386995/sdl-2-how-use-the-event-system-and-draw-asynchronously\">https://stackoverflow.com/questions/56386995/sdl-2-how-use-the-event-system-and-draw-asynchronously</a>. I also found <a href=\"https://stackoverflow.com/questions/18860243/sdl-pollevent-vs-sdl-waitevent\">https://stackoverflow.com/questions/18860243/sdl-pollevent-vs-sdl-waitevent</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:19:36.633",
"Id": "249316",
"ParentId": "249279",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249285",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T15:56:39.647",
"Id": "249279",
"Score": "12",
"Tags": [
"c",
"sdl"
],
"Title": "Conway's Game of Life in C"
}
|
249279
|
<p>I have files in a <code>store</code> folder, which I want to trim to a particular length by removing bytes from the beginning. My app uses a <code>temp</code> folder for the files manipulation. All files from the previous operations must be taken out form <code>temp</code>, so I use the folder for temporary storing the trimmed files. I also log the errors.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
set -euo pipefail
data_service='/path/to/data-service'
store="${data_service}/data/store"
temp="${data_service}/data/temp"
log="${data_service}/logs/log.txt"
max_size=$(( 200000 * 24 ))
{
# Checks if there are any files in 'temp'. It should be empty.
if [ "$( ls -A "${temp}" )" ]
then
echo "$( date +"%Y-%m-%d %H:%M:%S" ) [ERROR] Temp folder is not empty!" 1>&2
exit 1
fi
# Loops over all the files in 'store'
for file_path in "${store}/"*
do
# Trim bigger then 'max_size' files from 'store' to 'temp'
if [ "$( wc -c < "${file_path}" )" -gt "${max_size}" ]
then
file_name="$( basename "${file_path}" )"
tail -c "${max_size}" "${file_path}" > "${temp}/${file_name}"
fi
done
# Move all the truncated files back to 'store'
if [ "$( ls -A "${temp}" )" ]
then
mv "${temp}/"* "${store}/"
fi
} 2>> "${log}"
</code></pre>
<p>Any potential problems or ways to improve the code?</p>
<p>Because these are my first steps in writing in bash, the specific things I googled for this code were:</p>
<ul>
<li><p>Multiplication and assigning the result to a variable:</p>
<pre><code>max_size=$(( 200000 * 24 ))
</code></pre>
</li>
<li><p>Check if there are files in a folder:</p>
<pre><code>if [ "$( ls -A "$temp" )" ]; then .... fi
</code></pre>
</li>
<li><p>Get the date and time in a formatted string</p>
<pre><code>$( date +"%Y-%m-%d %H:%M:%S" )
</code></pre>
</li>
<li><p>Get the byte size of a file:</p>
<pre><code>"$( wc -c < "$file_path" )"
</code></pre>
</li>
<li><p>Copy the last N bytes of a file</p>
<pre><code>tail -c "$max_size" "$file_path" > "$temp/$file_name"
</code></pre>
</li>
<li><p>Group commands and redirect STDERR to a log file</p>
<pre><code>{ ... } 2>> log-file
</code></pre>
</li>
<li><p>Echo to STDERR of the group</p>
<pre><code>echo 'Error message' 1>&2
</code></pre>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Some suggestions</h1>\n<h2>Get the byte size of a file</h2>\n<p>Instead of:</p>\n<pre><code>"$( wc -c < "$file_path" )"\n</code></pre>\n<p>use stat:</p>\n<pre><code>stat -c %s "$file_path"\n</code></pre>\n<p>=> better query the file system than count the number of bytes in files, some of which can be pretty large</p>\n<h2>Redirect or copy console output to a file</h2>\n<p>Instead of enclosing the whole block between brackets, I would set up <strong>file redirection</strong> from the beginning eg:</p>\n<pre><code>#!/bin/bash\nLOG_FILE="/tmp/test.log"\nexec > >(tee -a "${LOG_FILE}") 2>&1\n\n# this should show on console AND in the log file\necho "Hello world $(date)"\n</code></pre>\n<p>based on this <a href=\"https://unix.stackexchange.com/a/61936/190343\">example</a></p>\n<p>This is more flexible, because once it's set up you don't have to bother about appending your commands, and you can disable or redefine the behavior on the fly if desired.</p>\n<p>And the benefit is that since we are redirecting both stdout and stderr, any errors will show up in the log file as well.</p>\n<h2>Misc</h2>\n<p>I think parsing the output of ls to count files in the directory is a bit primitive. Let me think but hopefully someone will come up with a better way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T06:42:35.753",
"Id": "488680",
"Score": "0",
"body": "Good idea to use `stat`. I made a very naive benchmark of 'wc' vs 'stat' and found about virtually the same performance. It is possible 'wc --bytes' to use the filesystem stats internally instead fo counting the bytes. `time for file_name in * ; do file_size=\"$( stat --format=%s \"${file_name}\" )\"; done`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:47:16.520",
"Id": "249312",
"ParentId": "249283",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249312",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:40:13.923",
"Id": "249283",
"Score": "2",
"Tags": [
"beginner",
"bash"
],
"Title": "Trim files by removing bytes from the beginning in bash"
}
|
249283
|
<p>I have the following multi thread scenario and the codes. It looks kind of messy and want to know if I can make it better or if there is any flaw to fix.</p>
<p>When a request arrives, one thread downloads it and the remaining operations are dependent on download so it needs to wait for download to finish. But there can be many request coming and download tasks must run at the same time but each process operation need to wait for its own download task. So I did the following.</p>
<p>ProcessCompletedListener</p>
<pre><code>public interface ProcessCompletedListener {
void onComplete(Object object);
}
</code></pre>
<p>RequestListener</p>
<pre><code>public interface RequestListener {
void onRequest(Object request);
}
</code></pre>
<p>Receiver class where I send request for testing purpose.</p>
<pre><code>public class Receiver {
private RequestListener requestListener;
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
public void requestBomb() {
String[] names = new String[]{"a", "b", "c"};
int i = 0;
while (i < 3) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
requestListener.onRequest(names[i]);
i++;
}
}
}
</code></pre>
<p>Custom blocking queue</p>
<pre><code>public class CustomBlockingQueue {
private BlockingQueue<Object> blockingQueue = new LinkedBlockingDeque<>();
private ProcessCompletedListener processCompletedListener;
public boolean offerAndProcess(Object object) {
if (blockingQueue.offer(object)) {
process(object);
return true;
}
return false;
}
public void setProcessCompletedListener(ProcessCompletedListener processCompletedListener) {
this.processCompletedListener = processCompletedListener;
}
private void process(Object object) {
new Thread(() -> {
System.err.println(object + ": Request process started.");
try {
Thread.sleep(6000); // mock for real operation
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println(object + ": Request process completed.");
if (processCompletedListener != null) {
processCompletedListener.onComplete(object);
}
}).start();
}
}
</code></pre>
<p>Demo class</p>
<pre><code>public class Demo {
public CustomBlockingQueue customBlockingQueue;
public void setCustomBlockingQueue(CustomBlockingQueue customBlockingQueue) {
this.customBlockingQueue = customBlockingQueue;
}
public CustomBlockingQueue getCustomBlockingQueue() {
return customBlockingQueue;
}
public static void main(String[] args) {
Demo demo = new Demo();
demo.setCustomBlockingQueue(new CustomBlockingQueue());
Receiver receiver = new Receiver();
Thread t = new Thread(() -> {
receiver.setRequestListener((request) -> {
new Thread(() ->
demo.getCustomBlockingQueue().setProcessCompletedListener((Object object) -> {
System.err.println(object + ": post process started");
try {
Thread.sleep(1500); // mock for real operation
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println(object + ": post process completed");
})).start();
demo.getCustomBlockingQueue().offerAndProcess(request);
});
});
t.start();
receiver.requestBomb();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T20:23:54.160",
"Id": "488554",
"Score": "0",
"body": "You are creating too much threads! Not all ops(like field set) should be done async here.\nI could not find the use-case so clear, so you mean only one download at-a-time? And once it's finished go for next queued download?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T03:46:38.350",
"Id": "488574",
"Score": "0",
"body": "many downloads at the same time but each process should wait for its relative download to finish"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T05:42:12.540",
"Id": "488579",
"Score": "0",
"body": "And a request for file `a` could be asked while, it has been started already? So the process/callback should be queued?"
}
] |
[
{
"body": "<blockquote>\n<p>When a request arrives, one thread downloads it and the remaining operations are dependent on download so it needs to wait for download to finish. But there can be many request coming and download tasks must run at the same time but each process operation need to wait for its own download task.</p>\n</blockquote>\n<p>That does sound like you want it in the same thread, like a "standard" webserver actually. A request is routed to a thread which handles that request from start to finish. No waiting or synchronizing involved. These threads can also easily be pooled.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> int i = 0;\n while (i < 3) {\n</code></pre>\n<p>I find it curios that you've chosen a <code>while</code> over <code>for</code> here.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> try {\n Thread.sleep(6000); // mock for real operation\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n</code></pre>\n<p>AS a note, you most likely want to exit here. The <code>InterruptedException</code> is being thrown when the <code>Thead</code> has been asked to stop doing whatever it does, <a href=\"https://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-#2.1\" rel=\"nofollow noreferrer\">so you don't want to ignore it most of the time</a>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> t.start();\n receiver.requestBomb();\n</code></pre>\n<p>Mind you that the <code>Thread</code> might not have started at this point. <code>start</code> does start the thread, obviously, but whether it has already executed <em>something</em> when your logic reaches the next instruction is undefined. Whether <code>receiver.setRequestListener(...)</code> has been called when you call <code>threadBomb</code> is undefined, might not have been.</p>\n<hr />\n<p>Your code looks and reads fine, actually. It's well written, however, it is unnecessarily complicated, or at least I'm failing to see why you need to do it this way.</p>\n<p>What would make sense is to have a single thread pool for processing, which is being fed by a single queue. A little pseudo-code for that:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Queue processingQueue = new BlockingQueue();\n\nclass RequestReceiver {\n public void onRequestReceived(Reqquest request) {\n processingQueue.add(request);\n }\n}\n\nclass ProcessingThread {\n public void run() {\n while (aliveCondition) {\n Request request = processingQueue.poll();\n download(request);\n process(request);\n }\n }\n}\n\n</code></pre>\n<p>This scheme is in, some form or another (rather another), also used by servers and webservers to process requests. You spin up multiple <code>ProcessingThread</code>s and have them wait for something to do, and after being done, they go back into the idle state.</p>\n<p>If you now require different threads for download and processing, you're just adding a another queue, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Queue downloadingQueue = new BlockingQueue();\nQueue processingQueue = new BlockingQueue();\n\nclass RequestReceiver {\n public void onRequestReceived(Reqquest request) {\n downloadingQueue.add(request);\n }\n}\n\nclass DownloadingThread {\n public void run() {\n while (aliveCondition) {\n Request request = downlaodingQueue.poll();\n download(request);\n processingQueue.add(request);\n }\n }\n}\n\nclass ProcessingThread {\n public void run() {\n while (aliveCondition) {\n Request request = processingQueue.poll();\n process(request);\n }\n }\n}\n\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> t.start();\n receiver.requestBomb();\n</code></pre>\n<p>Mind you that the <code>Thread</code> might not have started at this point. <code>start</code> does start the thread, obviously, but whether it has already executed <em>something</em> is undefined. The</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T15:08:37.973",
"Id": "488729",
"Score": "0",
"body": "This does not download async? Should I do sth like new Thread(()->{download(request); processingQueue.add(request);}).start(); wrapping them in new thread?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T17:15:00.813",
"Id": "488744",
"Score": "0",
"body": "This does not download on the main thread, which pretty much means it is asynchronous. The download runs in a separate thread. What exactly do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T18:45:47.037",
"Id": "488751",
"Score": "0",
"body": "each download run async from each other. Downloads should block each other. But each process needs to wait relative download operation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T19:36:34.107",
"Id": "488753",
"Score": "0",
"body": "They don't block each other as long as the thread pool is not exhausted. What your confusion most likely is, is that I\"m talking about a *thread **pool***, not a single instance of `DownloadingThread`, but multiple running in parallel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T17:09:29.663",
"Id": "488858",
"Score": "0",
"body": "Can I just use CompletionService instead of these? I think it can provide the same logic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:11:27.180",
"Id": "488867",
"Score": "0",
"body": "Sounds like it, didn't know about it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:49:22.323",
"Id": "249328",
"ParentId": "249286",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249328",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T18:54:15.963",
"Id": "249286",
"Score": "4",
"Tags": [
"java",
"multithreading"
],
"Title": "Java 2 grouped thread scenario"
}
|
249286
|
<p>This is my first program code ever, and it actually works.
My goal is to scrape information from the website and store it in a database.
It is a site that has historical data on sporting events and odds.</p>
<p><a href="https://www.oddsportal.com/hockey/sweden/shl-2019-2020/results/" rel="nofollow noreferrer">https://www.oddsportal.com/hockey/sweden/shl-2019-2020/results/</a></p>
<p>For example, there are 50 matches on this page and the program enters each of them and scrapes this data.</p>
<p>However, I don't think it really looks like the real code.
I'm interested in what I can do to improve and optimize it.
What do I pay the most attention to, what things do I do wrong?</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.common.keys import Keys
import sqlite3 as sql
import time
# I disable image display to get up to speed
options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=options)
# Database connection
conn = sql.connect('Hockey_data.db')
c = conn.cursor()
driver.get("https://www.oddsportal.com/hockey/sweden/shl-2019-2020/results/")
driver.maximize_window()
cur_win = driver.current_window_handle
list_of_links = driver.find_elements_by_xpath("//td[2]/a")[0:-2] # because 2 more elements have the same xpath and they are always at the end
for index, link in enumerate(list_of_links):
link.send_keys(Keys.CONTROL + Keys.RETURN)
driver.switch_to.window([win for win in driver.window_handles if win !=cur_win][0])
# Basic game info
league = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div/div[2]/div[6]/div[1]/div/div[1]/div[1]/a[4]"))).text
game = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div/div[2]/div[6]/div[1]/div/div[1]/div[2]/div[1]/h1"))).text
game_split = game.split('- ')
home_team, away_team = game_split[0], game_split[1]
time = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div/div[2]/div[6]/div[1]/div/div[1]/div[2]/div[1]/p[1]"))).text
time_split = time.split(', ')
day_in_week = time_split[0]
date = time_split[1]
day = int(date[0:2])
month = date[3:7]
year = int(date[7:11])
hour = time_split[2]
# Result and goals by periods
try:
result = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "event-status"))).text
except NoSuchElementException:
result = "0000000000000000000000000000000000000000000000000000000000000000000000"
if len(result) == 32:
home_goals = int(result[13:14])
home_first = int(result[18:19])
home_second = int(result[23:24])
home_third = int(result[28:29])
home_overtime = 0
home_penalties = 0
away_goals = int(result[15:16])
away_first = int(result[20:21])
away_second = int(result[25:26])
away_third = int(result[30:31])
away_overtime = 0
away_penalties = 0
elif len(result) == 33:
home_goals = int(result[13:15])
home_first = int(result[19:20])
home_second = int(result[24:25])
home_third = int(result[29:30])
home_overtime = 0
home_penalties = 0
away_goals = int(result[16:17])
away_first = int(result[21:22])
away_second = int(result[26:27])
away_third = int(result[31:32])
away_overtime = 0
elif len(result) == 40:
home_goals = int(result[13:14])
home_first = int(result[21:22])
home_second = int(result[26:27])
home_third = int(result[31:32])
home_overtime = int(result[36:37])
home_penalties = 0
away_goals = int(result[15:16])
away_first = int(result[23:24])
away_second = int(result[28:29])
away_third = int(result[33:34])
away_overtime = int(result[38:39])
away_penalties = 0
elif len(result) == 52:
home_goals = int(result[13:14])
home_first = int(result[28:29])
home_second = int(result[33:34])
home_third = int(result[38:39])
home_overtime = int(result[43:44])
home_penalties = int(result[48:49])
away_goals = int(result[15:16])
away_first = int(result[30:31])
away_second = int(result[35:36])
away_third = int(result[40:41])
away_overtime = int(result[45:46])
away_penalties = int(result[50:51])
else:
home_goals = 0
home_first = 0
home_second = 0
home_third = 0
home_overtime = 0
home_penalties = 0
away_goals = 0
away_first = 0
away_second = 0
away_third = 0
away_overtime = 0
away_penalties = 0
# 1x2 odds
pinnacle = "Pinnacle"
try:
pinnacle_home = driver.find_element_by_xpath("//div[a[contains(text(), 'Pinnacle')]]/following::td[1]")
hov_pinnacle_home = ActionChains(driver).move_to_element(pinnacle_home)
hov_pinnacle_home.perform()
pinnacle_home_closing = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[1]").text
try:
pinnacle_home_opening = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[2]").text
except (NoSuchElementException, TimeoutException):
pinnacle_home_opening = pinnacle_home_closing
except (NoSuchElementException, TimeoutException):
pinnacle_home = "0000000000"
pinnacle_home_closing = 0.00
pinnacle_home_opening = 0.00
try:
pinnacle_draw = driver.find_element_by_xpath("//div[a[contains(text(), 'Pinnacle')]]/following::td[2]")
hov_pinnacle_draw = ActionChains(driver).move_to_element(pinnacle_draw)
hov_pinnacle_draw.perform()
pinnacle_draw_closing = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[1]").text
try:
pinnacle_draw_opening = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[2]").text
except (NoSuchElementException, TimeoutException):
pinnacle_draw_opening = pinnacle_draw_closing
except (NoSuchElementException, TimeoutException):
pinnacle_draw = "0000000000"
pinnacle_draw_closing = 0.00
pinnacle_draw_opening = 0.00
try:
pinnacle_away = driver.find_element_by_xpath("//div[a[contains(text(), 'Pinnacle')]]/following::td[3]")
hov_pinnacle_away = ActionChains(driver).move_to_element(pinnacle_away)
hov_pinnacle_away.perform()
pinnacle_away_closing = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[1]").text
try:
pinnacle_away_opening = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[2]").text
except (NoSuchElementException, TimeoutException):
pinnacle_away_opening = pinnacle_away_closing
except (NoSuchElementException, TimeoutException):
pinnacle_away = "0000000000"
pinnacle_away_closing = 0.00
pinnacle_away_opening = 0.00
average = "Average"
try:
average_home = driver.find_element_by_xpath("//td[strong[contains(text(), 'Average')]]/following::td[1]").text
except NoSuchElementException:
average_home = 0.00
try:
average_draw = driver.find_element_by_xpath("//td[strong[contains(text(), 'Average')]]/following::td[2]").text
except NoSuchElementException:
average_draw = 0.00
try:
average_away = driver.find_element_by_xpath("//td[strong[contains(text(), 'Average')]]/following::td[3]").text
except NoSuchElementException:
average_away = 0.00
highest = "Highest"
try:
highest_home = driver.find_element_by_xpath("//td[strong[contains(text(), 'Highest')]]/following::td[1]").text
except NoSuchElementException:
highest_home = 0.00
try:
highest_draw = driver.find_element_by_xpath("//td[strong[contains(text(), 'Highest')]]/following::td[2]").text
except NoSuchElementException:
highest_draw = 0.00
try:
highest_away = driver.find_element_by_xpath("//td[strong[contains(text(), 'Highest')]]/following::td[3]").text
except NoSuchElementException:
highest_away = 0.00
# Over-Under tab
OU_link = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div/div[2]/div[6]/div[1]/div/div[1]/div[2]/div[1]/div[5]/div[1]/ul/li[5]/a/span"))).click()
pinnacle_over_under = "Pinnacle 5.5"
# 5.5 over-under tab
try:
OU_55 = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "//div/div/strong/a[contains(text(), 'Over/Under +5.5')]"))).click()
try:
pinnacle_over = driver.find_element_by_xpath("//div[a[contains(text(), 'Pinnacle')]]/following::td[2]")
hov_pinnacle_over = ActionChains(driver).move_to_element(pinnacle_over)
hov_pinnacle_over.perform()
pinnacle_over_closing = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[1]").text
try:
pinnacle_over_opening = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[2]").text
except (NoSuchElementException, TimeoutException):
pinnacle_over_opening = pinnacle_over_closing
except (NoSuchElementException, TimeoutException):
pinnacle_over = "0000000000"
pinnacle_over_opening = 0.00
pinnacle_over_closing = 0.00
try:
pinnacle_under = driver.find_element_by_xpath("//div[a[contains(text(), 'Pinnacle')]]/following::td[3]")
hov_pinnacle_under = ActionChains(driver).move_to_element(pinnacle_under)
hov_pinnacle_under.perform()
pinnacle_under_closing = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[1]").text
try:
pinnacle_under_opening = driver.find_element_by_xpath("//*[@id='tooltiptext']/strong[2]").text
except (NoSuchElementException, TimeoutException):
pinnacle_under_opening = pinnacle_over_closing
except (NoSuchElementException, TimeoutException):
pinnacle_under = "0000000000"
pinnacle_under_opening = 0.00
pinnacle_under_closing = 0.00
except (NoSuchElementException, TimeoutException):
OU_55 = "0000000000"
pinnacle_under_opening = 0.00
pinnacle_under_closing = 0.00
average_over_under = "Average 5.5"
try:
average_over = driver.find_element_by_xpath("//td[strong[contains(text(), 'Average')]]/following::td[2]").text
except NoSuchElementException:
average_over = 0.00
try:
average_under = driver.find_element_by_xpath("//td[strong[contains(text(), 'Average')]]/following::td[3]").text
except NoSuchElementException:
average_under = 0.00
highest_over_under = "Highest 5.5"
try:
highest_over = driver.find_element_by_xpath("//td[strong[contains(text(), 'Highest')]]/following::td[2]").text
except NoSuchElementException:
highest_over = 0.00
try:
highest_under = driver.find_element_by_xpath("//td[strong[contains(text(), 'Highest')]]/following::td[3]").text
except NoSuchElementException:
highest_under = 0.00
c.execute('insert into Model values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
(league, home_team, away_team, day_in_week, day, month, year, hour,
home_goals, away_goals, home_first, away_first, home_second,away_second, home_third, away_third,home_overtime, away_overtime, home_penalties, away_penalties,
pinnacle, pinnacle_home_closing, pinnacle_draw_closing, pinnacle_away_closing, pinnacle_home_opening, pinnacle_draw_opening, pinnacle_away_opening,
average, average_home, average_draw, average_away, highest, highest_home, highest_draw, highest_away,
pinnacle_over_under, pinnacle_over_closing, pinnacle_under_closing, pinnacle_over_opening, pinnacle_under_opening,
average_over_under, average_over, average_under, highest_over_under, highest_over, highest_under,))
conn.commit()
print("Number: ", index)
driver.close()
driver.switch_to.window(cur_win)
</code></pre>
|
[] |
[
{
"body": "<h2>Repetition 1</h2>\n<p>You have several XPATHs which are largely the same. Especially when they share a common prefix, like these</p>\n<p><code>"/html/body/div[1]/div/div[2]/div[6]/div[1]/div/div[1]/div[1]/a[4]"</code></p>\n<p>I would declare a variable</p>\n<p><code>xpath_base = "/html/body/div[1]/div/div[2]/div[6]/div[1]/div/div[1]"</code></p>\n<p>and then reuse that for every xpath that has the same base.\nThis makes the code more readable and easier to modify in case the base changes.</p>\n<p>Your first xpath then becomes <code>xpath_base + "/div[1]/a[4]"</code> , your second becomes <code>xpath_base + "/div[2]/div[1]/h1"</code> and so on.</p>\n<h2>Reptition 2 / Mapping</h2>\n<p>I would prefer to use some more compact structure for the goals reading. Not sure if you find it more readable, but it is shorter.</p>\n<p>You could put your indexes in a combination of dict and arrays like this.</p>\n<p>In this case I'm only using the indexes for home and away <code>goals, first, second, third</code> since they are used with indexes in all 4 cases.</p>\n<pre><code>result_mapping = {\n 32: [13, 14, 18, 19, 23, 24, 28, 29, 15, 16, 20, 21, 25, 26, 30, 31],\n 33: [13, 15, 19, 20, 24, 25, 29, 39, 16, 17, 21, 22, 26, 27, 31, 32],\n 40: [...],\n 52: [...]\n}\n</code></pre>\n<p>With this mapping you can then do</p>\n<pre><code>if len(result) in result_mapping.keys():\n indexes = result_mapping[len(result)]\n home_goals = int(result[indexes[0] : indexes[1]])\n home_first = int(result[indexes[2] : indexes[3]])\n home_second = int(result[indexes[4] : indexes[5]])\n</code></pre>\n<p>and so on.\nThere is more room for making this code shorter, like making a function for <code>int(result[])</code> since that is repeated on each line.</p>\n<p>Also, the indexes are always <code>n</code> and <code>n+1</code> except for <code>home_goals = int(result[13:15])</code> (is that an error in the indexing?). If the <code>13:15</code> is an error and supposed to be <code>13:14</code> then you can remove all the end indexes in the arrays above, so</p>\n<p><code>32: [13, 14, 18, 19, 23, 24, 28, 29, 15, 16, 20, 21, 25, 26, 30, 31]</code></p>\n<p>becomes</p>\n<p><code>32: [13, 18, 23, 28, 15, 20, 25, 30]</code></p>\n<p>and you just add <code>+1</code> instead of the end index, in each case.</p>\n<h2>Repetition 3 / Aliasing</h2>\n<p>Things that you repeat a lot, I would prefer to make a shorter alias for. You could define something like <code>xpath = driver.find_element_by_xpath</code> early in the code and then use the new name to call that function.</p>\n<h2>Repetition 4 / Default cases</h2>\n<p>In the long if-elif-else piece, you have your default case last after the <code>else</code>.</p>\n<p>But some of the cases here are shared with several of the cases in the if-else.\nFor that reason, it would make more sense to define your defaults first, before the if-else.\nSince they are all zero, you can also make them a bit shorter like this.</p>\n<pre><code>home_goals = home_first = home_second = home_third = home_overtime = home_penalties = 0\n</code></pre>\n<p>Now by doing this before the if-else, you don't need to mention these variables again in the cases that they should still be <code>0</code> such as <code>home_penalties</code> in 3 out of 4 cases.</p>\n<h2>Final comment</h2>\n<blockquote>\n<p>I don't think it really looks like the real code</p>\n</blockquote>\n<p>I think one reason it doesn't look like "real code" is that it has so many try - except and special cases and so on. But that is hard to avoid when writing a scraper for a particular website. You need to write custom code for the structure of that website, and you can't do a lot of the refactorings / shortcuts and reuse of things that you normally can when writing a normal program. So I think most of the code looks fine for this use case.</p>\n<h2>One more addition after posting</h2>\n<p>You have plenty of cases following the same pattern, like this</p>\n<pre><code>try:\n average_under = driver.find_element_by_xpath("//td[strong[contains(text(), 'Average')]]/following::td[3]").text\nexcept NoSuchElementException:\n average_under = 0.00\n</code></pre>\n<p>You can refactor this and make it a lot less repetitive by creating a function.</p>\n<pre><code>average_under = try_or_default("//td[strong[contains(text(), 'Average')]]/following::td[3]", 0.00)\n\n</code></pre>\n<p>and your function will be</p>\n<pre><code>def try_or_default(xpath, default_value):\n try:\n return driver.find_element_by_xpath(xpath).text\n except NoSuchElementException:\n return default_value \n</code></pre>\n<p>(I haven't tried running it so there may be some syntax error).</p>\n<p>You can make it further shorter by setting a default for the default_value</p>\n<pre><code>def try_or_default(xpath, default_value=0.00):\n</code></pre>\n<p>Which allows you to leave out the <code>0.00</code> when calling the function in most cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T10:51:29.300",
"Id": "488605",
"Score": "1",
"body": "First, thank you so much for your effort and response.\n\n**Repetition 1** / Declaring variables with the same base - Clear.\n\n**Reptition 2** / Mapping - I'll try to do this, it looks interesting.\n\n `home_goals = int(result[13:15])`\n\nThis is not a mistake, but refers to rare situations where the home team \nscores a double-digit number of goals (if the guest scores a double-digit number, \nthen I'm in trouble :))\n\n**Repetition 3** / Aliasing - Sounds very reasonable, I will try to respect this in the future.\n\n**Repetition 4** / Default cases - Clear.\n\nThanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T11:11:16.943",
"Id": "488606",
"Score": "0",
"body": "added one more suggestion, please see the edited answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:44:24.780",
"Id": "488638",
"Score": "0",
"body": "Great recommendation, works without problem! Thank you, I learned a lot"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T23:41:16.137",
"Id": "249294",
"ParentId": "249287",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249294",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T21:21:52.000",
"Id": "249287",
"Score": "4",
"Tags": [
"python",
"selenium"
],
"Title": "Web Scraping using Selenium and Python"
}
|
249287
|
<p>This was for a school project in my Data Structures class (I am still a very very young programmer). The purpose was to pass an interger and a base into a function and print out the result of changing that integer into that base. The project guidelines state that we can only pass an integer that is >= 0 and <= 1000000000.</p>
<p>The Main Function uses <code>ifstream</code> to stream a text document with the input into the main function.</p>
<p>I would like to know if there is anyway I can improve upon the <code>BaseConverter</code> function or anything else in the program before I submit it for grading.</p>
<p>I will put the full program below:</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
/****************************************************************************************************
Function Name: BaseConverter
Description: The purpose of this function is to take the user decimal number and base that are passed
to it and use them to recursively convert the decimal number into the base. The function
prints the correct result to the problem onto the screen and returns void.
*****************************************************************************************************/
void BaseConverter(int num, int base)
{
if (num == 0)
{
cout << "";
}
if (num >= base)
{
BaseConverter(num / base, base);
if (num % base > 9)
{
cout << char(num % base + 55);
}
else
{
cout << num % base;
}
}
else
{
cout << num % base;
}
}
/*****************************************************************************************************
MAIN PROGRAM
******************************************************************************************************/
int main()
{
ifstream fin("numbers.txt");
int userNum, base;
//sentinel control loop
fin >> userNum >> base;
while (userNum >= 0)
{
//display for input to ensure that correct input is being passed
cout << userNum << " " << base << endl;
if (userNum > 1000000000)
{
cout << "Decimal number too large for this program" << endl;
cout << endl;
}
else
{
// call for function and output display
cout << userNum << " in base " << base << " is ";
BaseConverter(userNum, base);
cout << endl;
cout << endl;
}
fin >> userNum >> base;
}
fin.close();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>1.</strong> Names/Magic numbers</p>\n<p>What is the magic number 55 in your base converter function?</p>\n<p>I suggest giving it a name.</p>\n<p><strong>2.</strong> Bounds / Magic numbers / validation</p>\n<p>Also, what are the upper and lower bounds on which bases are allowed? Only 2-9 since you are comparing with 9? That should also be specified and checked when reading the input.</p>\n<p><strong>3.</strong> Code formatting / style</p>\n<p>Your code has a lot of space (empty lines and unnecessarily many newlines).\nUnless your school requires you to follow that particular style, I suggest reformatting it into a more readable style. You can for example paste it into this formatter to get a more concise and readable code.</p>\n<p><a href=\"https://codebeautify.org/cpp-formatter-beautifier\" rel=\"nofollow noreferrer\">https://codebeautify.org/cpp-formatter-beautifier</a></p>\n<p>For example, this is the output of reformatting part of your code.</p>\n<pre><code>void BaseConverter(int num, int base) {\n if (num == 0) {\n cout << "";\n }\n\n if (num >= base) {\n BaseConverter(num / base, base);\n\n if (num % base > 9) {\n cout << char(num % base + 55);\n } else {\n cout << num % base;\n }\n } else {\n cout << num % base;\n }\n}\n</code></pre>\n<p><strong>4.</strong> cout multiple inputs</p>\n<p>You can chain inputs to <code>cout</code> so you don't need to do this</p>\n<pre><code>cout << endl;\ncout << endl;\n</code></pre>\n<p>But rather\n<code>cout << endl << endl;</code></p>\n<p><strong>5.</strong> File reading</p>\n<p>It doesn't seem that the requirements for the assignment are to read from a file. If that is correct, I think you should skip the file reading and read from <code>cin</code> or a similar terminal input instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:58:34.337",
"Id": "249292",
"ParentId": "249291",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T22:30:45.617",
"Id": "249291",
"Score": "2",
"Tags": [
"c++",
"recursion"
],
"Title": "Take an Integer and print it in a Different Base Recursively (c++)"
}
|
249291
|
<p>Can I make this code somehow faster and is this readable? I'm a beginner and in later I'll make another class with Decimal to Binary conversion, but first I've to know how to do that.</p>
<pre><code>package convert.console.binaryToDecimal;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConversionProgram {
//check if number is actually binary
public static boolean isBin(int numb){
int inputNumb = numb;
while(inputNumb > 0){
if(inputNumb % 10 > 1){
return false;
}
inputNumb /= 10;
}
return true;
}
public static int binaryToDecimal(int input){
int number = input;
int decimalNumber = 0;
int baseNumber = 1;
int lastDigit;
//check if provided number is binary
if(isBin(number)){
while(number != 0){
//takes last digit from input
lastDigit = number % 10;
//counts decimal number
decimalNumber += lastDigit * baseNumber;
/*every time increase baseNumber by 2
(base number is 1 ,because when u start from right 2pow0 is always 1)
*/
baseNumber *= 2;
//removes last digit from input
number /= 10;
}
}
else if(!isBin(number)){
System.out.println("Wrong!\nProvide binary number - contains only 0 and 1");
}
return decimalNumber;
}
//check if output is correct
public static void isCorrect(int bin, int conv){
if (conv == 0) {
System.out.println("Try again");
} else {
System.out.println("Converted number from binary " + bin + " to decimal is " + conv);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input binary number :");
try {
int binaryNumb = input.nextInt();
int convertedNumb = binaryToDecimal(binaryNumb);
isCorrect(binaryNumb, convertedNumb);
}catch(InputMismatchException e){
System.out.println("Wrong input!");
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>There are good things to point out in your solution apart from the code formatting. If you use eclipse you could press ctrl+shift+f and that will make your code more redable.</p>\n<hr />\n<p><strong>Is Binary Method</strong></p>\n<ul>\n<li>In Java, the values you send as parameters aren't affected in other functions (there are some exceptions as with data structures nodes). Hence you can save the <code>inputNumb</code> variable</li>\n<li>Make the name of your variables, methods and classes descriptive for all possible reader of your code. In the future you won't work alone.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> public static boolean isBinary(int number) {\n while (number > 0) {\n if(number % 10 > 1)\n return false;\n number /= 10;\n }\n return true;\n }\n</code></pre>\n<hr />\n<p><strong>Binary To Decimal Method</strong></p>\n<ul>\n<li>If a variable is declared an only used once (as <code>lastDigit</code>), then substitute the value assigned to it where such variable appears.</li>\n<li>Make comments when needed</li>\n<li>Throw exceptions when you find an inconsistency which will interfere with the correct workflow of your program</li>\n<li>Don't check twice a boolean condition, if an <code>if else</code> statement depends on only one condition you haven't to check if that wasn't true in the <code>else</code> block, it is redundant, an <code>else</code> is executed when the condition in the <code>if</code> fails</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> public static int binaryToDecimal(int number) {\n int decimalNumber = 0;\n int powerOfTwo = 1; //renamed, gives more context\n if (isBinary(number)) {\n while (number != 0) {\n decimalNumber += (number % 10) * powerOfTwo;\n powerOfTwo *= 2;\n number /= 10; //removes the last digit\n }\n } else throw new InvalidParameterException("Not a binary number");\n return decimalNumber;\n }\n</code></pre>\n<hr />\n<p>The <code>isCorrect</code> method could be omitted since it's used once.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n System.out.print("Enter a binary number: ");\n try {\n int binaryNumb = input.nextInt();\n int convertedNumb = binaryToDecimal(binaryNumb);\n System.out.println("The number "+ binaryNumb + " was converted to decimal," +\n "\\nthe result was: " + convertedNumb);\n } catch (InputMismatchException e) {\n System.out.println("Wrong input!");\n }\n }\n</code></pre>\n<p>I wish it were of help to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:52:12.210",
"Id": "488655",
"Score": "1",
"body": "I always like to mention that `a += b` is not shorthand for `a = a + b`, but for `a = (TYPE_A)(a+b)`. It doesn't matter in this case, but it's something to keep in mind as it might silently truncate data."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T02:31:55.287",
"Id": "249298",
"ParentId": "249293",
"Score": "2"
}
},
{
"body": "<p>One thing, I noticed. To my mind a binary number is usually represented by a collection of digits(string,char[],byte[],etc) not an integer with only 0's and 1's. Not only would this approach be more typical it would simplify your algorithm significantly since the digits are already separated.</p>\n<p>Another aspect to consider, an integer is restricted to the number of digits, whereas a binary number can typically have 32, 64 or even 128 bits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:46:26.813",
"Id": "488663",
"Score": "0",
"body": "So I guess ,I should use BigInteger right? While long holds only 64 bits and it'd be not enough"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:56:02.000",
"Id": "488664",
"Score": "2",
"body": "I would suggest using string, char and byte array overloads Instead of integers. Biginteger would work but I don't think it would have any practical value"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:36:42.363",
"Id": "249311",
"ParentId": "249293",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249298",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T23:20:57.247",
"Id": "249293",
"Score": "3",
"Tags": [
"java",
"beginner",
"converting"
],
"Title": "Binary to decimal"
}
|
249293
|
<p>Given a sorted array consisting 0’s and 1’s. The task is to find the index of first ‘1’ in the given array. I submitted the below code in geeks for geeks and the execution time is 5.77. Need help in optimizing the below code.</p>
<pre><code>class FindIndex {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
int noOfTestCase = scanner.nextInt();
while (noOfTestCase-- > 0) {
int n = scanner.nextInt();
int[] array = new int[n];
int index = -1;
for (int i = 0 ; i < n ; i++) {
array[i] = scanner.nextInt();
if (array[i] == 1 && index == -1) {
index = i;
}
}
System.out.println(index);
}
}
}
</code></pre>
<p><a href="https://practice.geeksforgeeks.org/problems/index-of-first-1-in-a-sorted-array-of-0s-and-1s/0" rel="nofollow noreferrer">Source</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T05:33:06.553",
"Id": "488577",
"Score": "1",
"body": "Right now you're walking down the entire array one element at a time. You know the array is sorted, you know where it begins, where it ends, and where the middle is. Can you think of a way to keep track of those three pointers (low, mid, high) and work them towards each other until they meet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T06:13:40.440",
"Id": "488581",
"Score": "0",
"body": "but anyway you have to traverse n times to get the input right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T06:23:55.030",
"Id": "488582",
"Score": "2",
"body": "For the outer While loop? Yeah, you read every element of that once.\nFor the inner loop no. This type of problem is called a binary search (the most basic example of which is guessing a number and getting high/low as a response) but a slightly more complicated variation where instead of one guess you're sliding three guesses back and forth until they meet. The solution will be O(log(n)) complexity. If you don't know what that means Google Big-O complexity. Walking a list is O(n). Walking a nested lists is O(n^2). etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T07:53:20.560",
"Id": "488585",
"Score": "0",
"body": "Got your point. Thanks :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T12:20:37.077",
"Id": "488611",
"Score": "0",
"body": "@Coupcoup Hmm, why would you suggest binary searching an array in a problem where they clearly shouldn't store the array in the first place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:57:29.513",
"Id": "488627",
"Score": "0",
"body": "@Coupcoup And how would you replace their reading the input in the inner loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:32:22.007",
"Id": "488629",
"Score": "0",
"body": "The first improvement I think it should be not reading the whole array, if you read a '1', just end and return the index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:46:17.327",
"Id": "488630",
"Score": "0",
"body": "@Norhther How would the test program behave in this case? It probably doesn't wait for a cue to stop inputting numbers, so the code would end up producing wrong output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T09:48:19.357",
"Id": "488698",
"Score": "0",
"body": "Can you edit the exact problem description into the question? The implementation efficiency and review in general depends completely on how the input is formatted and what the expected output is."
}
] |
[
{
"body": "<h2>Trying to outsmart the challenge defeats the purpose</h2>\n<p>While there is value in learning how to do the bare minimum needed (as you try to detect the number as soon as it is inputted instead of performing a search), there is only so much you can learn by trying to outsmart the challenge and not practice the knowledge this challenge is supposed to help you practice (which in this case is binary search).</p>\n<h2>Input reading</h2>\n<p>You can read the input faster using <code>BufferedReader</code>, see <a href=\"https://stackoverflow.com/a/36618213/2194661\">this answer</a>'s "Reading Data" section for example. You can read a whole line at once and then perform a search.</p>\n<h2>Binary search</h2>\n<p>Binary search is a very fast way to find an item in a sorted array where by looking at any element you know if what you're looking for is on the left or right of the current position.</p>\n<p>You can perform the search on the string, converting the string to an array of numbers is unnecessary and therefore a waste of time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:25:20.087",
"Id": "249310",
"ParentId": "249302",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249310",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T04:40:21.470",
"Id": "249302",
"Score": "4",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "Find first index of 1"
}
|
249302
|
<p><a href="https://i.stack.imgur.com/FoKbO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FoKbO.png" alt="enter image description here" /></a>
I have written a code for my purpose to send bulk email dynamically (Name,Document,Expiry date,email address will be changed dynamically)..Everything is working fine but it take a approximately ( 4 Second/Mail sent for without using array and 2 sec / mail sent using array)...Any one know another way around to make it a little bit fast?.. Before running the macro please edit .To = "Your email id", and password..Thanks. For Sending 1000 mail it will take approximately 67 & 33 minute.. If possible i want to make it 67 & 33 Second..Is it possible?? Email is sent if expired day is after 30/7/0 day from today.</p>
<p>PROCESS 1 : Without Using array.</p>
<pre><code>Public Sub SentRemainder()
Dim RemainingDay As Long, L As Integer, t1 As Long, t2 As Long
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
t1 = Timer()
Dim lastrow As Long, i As Long
lastrow = Sheets("Personal").Cells(1048576, 2).End(xlUp).Row
With Sheets("Personal")
For i = 3 To lastrow
If .Cells(i, 4).Value <> "" Then
RemainingDay = .Cells(i, 4).Value - Now() + 1
ElseIf .Cells(i, 4).Value = "" Then
Exit For
End If
If RemainingDay = 30 Or RemainingDay = 7 Or RemainingDay = 0 Then
SendEmailUsingGmail .Cells(i, 1).Value, .Cells(i, 2).Value, Format(.Cells(i, 4).Value, "DD-MMM-YYYY"), .Cells(i, 5).Value, RemainingDay
L = L + 1
' ElseIf RemainingDay < 0 Then
' .Range(.Cells(i, "A"), .Cells(i, "E")).ClearContents
' .Range(.Cells(i, "A"), .Cells(lastrow - 1, "E")).Value = .Range(.Cells(i + 1, "A"), .Cells(lastrow, "E")).Value
' .Range(.Cells(lastrow, "A"), .Cells(lastrow, "E")).ClearContents
End If
Next i
End With
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Email sent : " & L & "Nos."
t2 = Timer()
MsgBox "Time taken to run this code: " & t2 - t1
End Sub
'Enable Tools > References > Microsoft CDO for Windows 2000 Library
Public Sub SendEmailUsingGmail(Name As String, Document As String, ExpiryDate As String, EmailAddress As String, RemainingDay As Long)
Dim NewMail As CDO.Message 'For Creating email collaboration.
Dim mailConfiguration As CDO.Configuration 'For mail configuration
Dim fields As Variant 'For email field data.
Dim msConfigurationURL As String 'For storing the server URL (CDO).
On Error GoTo Err:
'early binding
Set NewMail = New CDO.Message 'Create the collaboration.
Set mailConfiguration = New CDO.Configuration 'Create configuration.
mailConfiguration.Load -1 'Load all default configurations
Set fields = mailConfiguration.fields 'Set configuration field to previous field.
'Set All Email Properties
With NewMail
.From = "Your gmail address" 'From which email address email will be sent.
.To = EmailAddress 'Where to send the email.
.CC = "" 'If you need to use CC then add email address.
.BCC = "" 'If you need to use BCC then add email address.
.Subject = Document & " Expired in " & RemainingDay & " Day." 'Subject of Email..Dynamically it will change for every recepient.
'For increasing readibility use _ .Here textbody is written.
.TextBody = "Hi " & Name & "," & vbNewLine & _
"Your " & Document & " will expire on " & ExpiryDate & _
".You have " & RemainingDay & " day to renew your " & Document & "." & "Please renew your " & Document & "." & _
vbNewLine & "Thank You." & vbNewLine & "Md.Ismail Hosen"
'.AddAttachment 'Here i need to edit.
End With
msConfigurationURL = "http://schemas.microsoft.com/cdo/configuration" 'For decrease word in below line.
With fields
.Item(msConfigurationURL & "/smtpusessl") = True 'Enable SSL Authentication
.Item(msConfigurationURL & "/smtpauthenticate") = 1 'SMTP authentication Enabled
.Item(msConfigurationURL & "/smtpserver") = "smtp.gmail.com" 'Set the SMTP server details
.Item(msConfigurationURL & "/smtpserverport") = 465 'Set the SMTP port Details....Check it in Gmail. Port may be 25/465/587
.Item(msConfigurationURL & "/sendusing") = 2 'Send using default setting
.Item(msConfigurationURL & "/sendusername") = "Your gmail address" 'Your gmail address
.Item(msConfigurationURL & "/sendpassword") = "Your gmail password" 'Your password or App Password(If 2F is on).
.Update 'Update the configuration fields
End With
With NewMail
.Configuration = mailConfiguration 'Set NewMail configuration to updated configuration.
.Send
End With
'MsgBox "Your email has been sent", vbInformation
Exit_Err:
'Release object memory
Set NewMail = Nothing
Set mailConfiguration = Nothing
Exit Sub 'This is so much important if you want to run the sub multiple times.
Err:
Select Case Err.Number
Case -2147220973 'Could be because of Internet Connection
MsgBox "Check your internet connection." & vbNewLine & Err.Number & ": " & Err.Description
Case -2147220975 'Incorrect credentials User ID or password
MsgBox "Check your login credentials and try again." & vbNewLine & Err.Number & ": " & Err.Description
Case 0 'Case 0 means code run smoothly and you need to exit this sub.
GoTo Exit_Err:
Case Else 'Report other errors
MsgBox "Error encountered while sending email." & vbNewLine & Err.Number & ": " & Err.Description
End Select
Resume Exit_Err
End Sub
</code></pre>
<p>PROCESS 2: With Using array.</p>
<pre><code>Public Sub SentRemainder2()
Dim RemainingDay As Long, L As Integer, t1 As Long, t2 As Long
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
t1 = Timer()
Dim i As Long
Dim arr As Variant
With Sheets("Personal")
arr = .Range(.Cells(3, 1), .Cells(.Cells(1048576, 2).End(xlUp).Row, 5)).Value
End With
Dim NewMail As CDO.Message 'For Creating email collaboration.
Dim mailConfiguration As CDO.Configuration 'For mail configuration
Dim fields As Variant 'For email field data.
Dim msConfigurationURL As String 'For storing the server URL (CDO).
On Error GoTo Err:
'early binding
Set NewMail = New CDO.Message 'Create the collaboration.
Set mailConfiguration = New CDO.Configuration 'Create configuration.
mailConfiguration.Load -1 'Load all default configurations
Set fields = mailConfiguration.fields 'Set configuration field to previous field.
msConfigurationURL = "http://schemas.microsoft.com/cdo/configuration" 'For decrease word in below line.
With fields
.Item(msConfigurationURL & "/smtpusessl") = True 'Enable SSL Authentication
.Item(msConfigurationURL & "/smtpauthenticate") = 1 'SMTP authentication Enabled
.Item(msConfigurationURL & "/smtpserver") = "smtp.gmail.com" 'Set the SMTP server details
.Item(msConfigurationURL & "/smtpserverport") = 465 'Set the SMTP port Details....Check it in Gmail. Port may be 25/465/587
.Item(msConfigurationURL & "/sendusing") = 2 'Send using default setting
.Item(msConfigurationURL & "/sendusername") = "Your Gmail Address" 'Your gmail address
.Item(msConfigurationURL & "/sendpassword") = "Your Gmail Password" 'Your password or App Password(If 2F is on).
.Update 'Update the configuration fields
End With
For i = LBound(arr, 1) To UBound(arr, 1)
RemainingDay = arr(i, 4) - Now() + 1
If RemainingDay = 30 Or RemainingDay = 7 Or RemainingDay = 0 Then
With NewMail
.Configuration = mailConfiguration
.From = "Your Gmail Address" 'From which email address email will be sent.
.To = arr(i, 5) 'Where to send the email.
.CC = "" 'If you need to use CC then add email address.
.BCC = "" 'If you need to use BCC then add email address.
.Subject = arr(i, 2) & " Expired in " & RemainingDay & " Day." 'Subject of Email..Dynamically it will change for every recepient.
'For increasing readibility use _ .Here textbody is written.
.TextBody = "Hi " & arr(i, 1) & "," & vbNewLine & _
"Your " & arr(i, 2) & " will expire on " & arr(i, 4) & _
".You have " & RemainingDay & " day to renew your " & arr(i, 2) & "." & "Please renew your " & arr(i, 2) & "." & _
vbNewLine & "Thank You." & vbNewLine & "Md.Ismail Hosen"
'.AddAttachment 'Here i need to edit.
.Send
End With
L = L + 1
End If
Next i
Err:
Select Case Err.Number
Case -2147220973 'Could be because of Internet Connection
MsgBox "Check your internet connection." & vbNewLine & Err.Number & ": " & Err.Description
Case -2147220975 'Incorrect credentials User ID or password
MsgBox "Check your login credentials and try again." & vbNewLine & Err.Number & ": " & Err.Description
Case 0 'Case 0 means code run smoothly and you need to exit this sub.
GoTo Exit_Err:
Case Else 'Report other errors
MsgBox "Error encountered while sending email." & vbNewLine & Err.Number & ": " & Err.Description
End Select
Resume Exit_Err
Exit_Err:
'Release object memory
Set NewMail = Nothing
Set mailConfiguration = Nothing
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Email sent : " & L & " Nos."
t2 = Timer()
MsgBox "Time taken to run this code: " & t2 - t1
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T11:35:33.933",
"Id": "488707",
"Score": "0",
"body": "Is there any particular reason that `SendEmailUsingGmail` is inlined in the 2nd test routine? Have you considered the possibility that 2 seconds per email may be the best you can do since you're accessing the Gmail API to send the messages? Remember that, while I'm sure you messages are 100% legit, there are lots of people who would love to send 1000s of spam messages per second via Gmail if Google would allow them to do so. Wrap a timer around the actual send code to see how long _that_ part takes. It may well be that you're now at the minimum time reasonably possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T12:51:08.840",
"Id": "488715",
"Score": "0",
"body": "No ..Yes i check it..Just \".Send\" statement take approximately 2 sec due to gmail integration..It is best i can do..I think there is no other way around to lower the run time...For 32 email sent Complete task done within 61 sec but send statement take 59~60 sec..Thanks for your reply."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T07:18:31.627",
"Id": "491307",
"Score": "0",
"body": "Is it possible to save all distribution emails in `Outbox`, don't `.send` yet, then after all emails are prepared, only bulk send all emails in `Outbox`? I never try CDO, hence just making a suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T15:03:05.757",
"Id": "491430",
"Score": "0",
"body": "@Rosetta that's a good idea..I will take a look at that and let you know.."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T07:27:18.177",
"Id": "249305",
"Score": "2",
"Tags": [
"vba"
],
"Title": "Bulk Email Sending Using VBA Run Time Concern"
}
|
249305
|
<p>The Sequences & Series involved are Arithmetic and Geometric.
stores and allows you to calculate using these given formulas
and import fractions into micropython</p>
<p>Support for micropython! Micropython, however, only has a subset of functions of pythons, and it's standard library is very limited, so i had to reinvent the wheel on some things.</p>
<p>I'd like advice on efficiency, math, optimization, compactness, design, and general information about improving my program (it was designed for micropython).</p>
<p>Arithmetic:</p>
<ol>
<li><p>An = a1 + (n-1)d</p>
</li>
<li><p>Sn = n/2 x (2a1 + (n-1)d) OR Sn = n/2(a + L)</p>
</li>
</ol>
<p>Geometric:</p>
<ol start="3">
<li><p>An = a1(r)^(n-1)</p>
</li>
<li><p>Sn = (a(1-(r)^n)/(1-r)</p>
</li>
<li><p>S_infinity = a/(1-r)</p>
</li>
</ol>
<p>Both:</p>
<ol start="6">
<li>ability to find the first nth to exceed a value</li>
</ol>
<pre><code>from math import sqrt, log
def take_inputs(*args):
"""
takes a list of variable names, and sets it up so that that input is carried out, and
a list is returned with the numerical values, to be used for unpacking into their variables
Ex:
take_inputs('a', 'b', 'c')
a = 4
b = 2
c = 3
- [4, 2, 3] -
"""
values = []
for prompt in args:
values.append(eval(str(input(prompt + " = "))))
return values
def check_for_L():
"""
checks if an 'x' was inputted at L.
if 'x', then return None (L wasn't inputted)
if any other value, then return the float form of that value
Ex:
check_for_L()
Enter x if L not present!
Enter L: 5
- 5.0 -
"""
L = input("Enter x if L not present!\nEnter L: ")
if L == 'x':
return None
return float(L)
class Arithmetic:
def a_nth(self):
print("An = a1 + (n-1)d")
a1, n, d = take_inputs('a1', 'n', 'd')
print(round(a1 + (n - 1) * d, 5))
def sum(self):
print("Sn = n/2(2a1+(n-1)d)", "Sn = n/2(a1+L)", sep="\n")
L = check_for_L()
if not L:
a1, n, d = take_inputs('a1', 'n', 'd')
print(round((n/2) * (2 * a1 + (n - 1) * d), 5))
else:
a1, n = take_inputs('a1', 'n')
print(round((n/2) * (a1 + L), 5))
def exceed_nth(self):
print("a+(n-1)d > Value")
a1, d, value = take_inputs('a1', 'd', 'value')
n = round(( (value - a1) / d ) + 1, 5)
print("n to exceed = " + str(n))
def exceed_sum_to_nth(self):
print("n/2(2a1+(n-1)d)>Value", "n/2(a1+L)>Value", sep="\n")
L = check_for_L()
if L:
a1, value = take_inputs('a1', 'value')
n = round((2 * value) / (a1 + L), 5)
print("n to exceed = " + str(n))
else:
a1, d, value = take_inputs('a1', 'd', 'value')
n = round((-2*a1 + d + sqrt(4*(a1**2) - 4*a1*d + d**2 + 8*d*value))/(2*d), 5)
print("n to exceed = " + str(n))
class Geometric:
def a_nth(self):
print("An = ar^(n-1)")
a1, r, n = take_inputs('a1', 'r', 'n')
print(round(a1 * r ** (n - 1), 5))
def sum(self):
print("Sn = a(1-r^n)/(1-r)")
a1, r, n = take_inputs('a1', 'r', 'n')
print( round((a1 * (1 - r**n) )/(1 - r), 5))
def sum_to_infinity(self):
print("S(inf) = a/(1-r)")
a1, r = take_inputs('a1', 'r')
print(round(a1/(1-r), 5))
def exceed_nth(self):
print("ar^(n-1) > Value")
a1, r, value = take_inputs('a1', 'r', 'value')
n = round(log( r*(value/a1) ) / log(r), 5)
print("n to exceed = " + str(n))
def exceed_sum_to_nth(self):
print("a(1-r^n)/(1-r)>Value")
a1, r, value = take_inputs('a1', 'r', 'value')
n = round(log( (a1 + r*value - value) / a1) / log(r), 5)
print("n to exceed = " + str(n))
class BIOS:
choices_prompt = "a for arithmetic\nb for geometric\n>> "
def __init__(self):
"""
responsible for handling basic input and output, for the terminal, and options/choices.
"""
self.running = True
self.arithmetic = Arithmetic()
self.geometric = Geometric()
self.choices = {'a': self.arithmetic_sequences, 'b': self.geometric_sequences}
self.arithmetic_choices = {'a': self.arithmetic.a_nth, 'b': self.arithmetic.sum, 'c': self.arithmetic_exceed}
self.geometric_choices = {'a': self.geometric.a_nth, 'b': self.geometric.sum, 'c': self.geometric.sum_to_infinity, 'd': self.geometric_exceed}
self.arithmetic_exceed_choices = {'a': self.arithmetic.exceed_nth, 'b': self.arithmetic.exceed_sum_to_nth}
self.geometric_exceed_choices = {'a': self.geometric.exceed_nth, 'b': self.geometric.exceed_sum_to_nth}
@staticmethod
def menu(*args):
"""
a list of prompts is given as arguments,
and a menu like input system is made.
Ex:
menu('a for apple', 'b for bye', 'c for cat')
a for apple
b for bye
c for cat
>> a
- a -
"""
return input("\n".join(list(args) + [">> "]))
def stop_decorator(func):
"""
Decorator for stopping certain functions, after they're done by asking with a prompt
"""
def wrapper(self):
func(self)
command = input("Enter nothing to stop: ")
if command == '':
self.running = False
return wrapper
@stop_decorator
def arithmetic_sequences(self):
sub_choice = self.menu("Arithmetic:", "a for a_nth term", "b for sum", "c for min_term_exceed")
self.arithmetic_choices.get(sub_choice, lambda: None)()
@stop_decorator
def geometric_sequences(self):
sub_choice = self.menu("Geometric:", "a for a_nth term", "b for sum", "c for sum to infinity", "d for min terms exceed")
self.geometric_choices.get(sub_choice, lambda: None)()
def arithmetic_exceed(self):
sub_choice = self.menu("Exceed Arithmetic:", "a for nth", "b for sum_to_nth")
self.arithmetic_exceed_choices.get(sub_choice, lambda: None)()
def geometric_exceed(self):
sub_choice = self.menu("Exceed Geometric:", "a for nth", "b for sum_to_nth")
self.geometric_exceed_choices.get(sub_choice, lambda: None)()
def main(self):
"""
runs the program indefinitely as long as the user wants.
"""
while self.running:
self.choices.get(input(self.choices_prompt), lambda: None)()
print()
program = BIOS()
program.main()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:41:38.857",
"Id": "488661",
"Score": "0",
"body": "yes, so that i can input values like 3/2, which is a fraction, and possibly pi, in the near future. I am aware this is a vulnerability/security issue, but this is just a math program lol for a calculator nonetheless. I'm pretty much gonna be the only one using it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T09:19:48.213",
"Id": "249307",
"Score": "5",
"Tags": [
"python-3.x",
"object-oriented",
"reinventing-the-wheel",
"mathematics"
],
"Title": "Sequence and Series Calculator"
}
|
249307
|
<p>Here's one way to solve the serialization problem in c++20, using a <a href="https://github.com/nlohmann/json" rel="nofollow noreferrer">json</a> library:</p>
<pre><code>#include <functional>
#include <unordered_map>
#include "json.hpp"
namespace nlm = nlohmann;
class properties
{
struct property_info
{
std::function<void(nlm::json const&)> deserializor;
std::function<nlm::json()> serializor;
};
std::unordered_map<std::string_view, property_info> reg_;
public:
//
nlm::json state() const;
void state(nlm::json const&);
//
template <typename U, typename ...A>
auto register_property(std::string_view const& k, U& v, A&& ...a)
{
static_assert(!(sizeof...(a) % 2));
static_assert(!(std::is_const_v<U>));
reg_.try_emplace(k,
[&v](nlm::json const& j){v = j.get<U>();},
[&v]{return nlm::json(v);}
);
if constexpr (sizeof...(a))
{
register_property(std::forward<A>(a)...);
}
return [this](auto&& ...a)
{
return register_property(std::forward<decltype(a)>(a)...);
};
}
auto get(std::string_view const& k)
{
return reg_.find(k)->second.serializor();
}
template <typename U>
void set(std::string_view const& k, U&& v)
{
reg_.find(k)->second.deserializor(std::forward<U>(v));
}
};
nlm::json properties::state() const
{
nlm::json r(nlm::json::object());
for (auto i(reg_.cbegin()), cend(reg_.cend()); cend != i; i = std::next(i))
{
r.emplace(i->first, i->second.serializor());
}
return r;
}
void properties::state(nlm::json const& e)
{
assert(e.is_object());
auto const cend(reg_.cend());
for (auto i(e.cbegin()), ecend(e.cend()); ecend != i; i = std::next(i))
{
auto& key(i.key());
if (auto const j(std::as_const(reg_).find(key)); cend != j)
{
j->second.deserializor(i.value());
}
}
}
</code></pre>
<p>Example:</p>
<pre><code>int main()
{
struct S: properties
{
bool b{};
int i{};
S()
{
register_property("b", b)("i", i);
}
} s;
s.set("b", true);
s.set("i", 11.1);
std::cout << s.get("b") << std::endl;
std::cout << s.state() << std::endl;
}
</code></pre>
<p>2 functors for (de)serializing are generated for each registered property. If state is requested or set, these are executed accordingly. Obvious improvements are certain checks, getters/setters, instead of references. I think this is a nice quick solution for simple cases.</p>
<p><a href="https://wandbox.org/permlink/J0vdLOTp5x6xvF9s" rel="nofollow noreferrer">https://wandbox.org/permlink/J0vdLOTp5x6xvF9s</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T12:26:43.703",
"Id": "488613",
"Score": "0",
"body": "The text says C++17, which contradicts with the C++20 tag. Which one is intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:12:38.870",
"Id": "488660",
"Score": "0",
"body": "Please do not add new solutions to your question, 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. As such I have rolled back your latest edit. 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-09-14T20:32:12.797",
"Id": "488768",
"Score": "0",
"body": "https://github.com/user1095108/properties"
}
] |
[
{
"body": "<h1>Avoid creating namespace aliases in header files</h1>\n<p>I assume that at least the declaration of <code>class properties</code> would be put in a header file. In that case, consider that users of that header file might not expect <code>namespace nlm</code> to be declared, so I recommend just writing out <code>nlohmann</code> fully.</p>\n<h1>Spelling</h1>\n<p>A minor issue: it is <code>serializer</code>, not <code>serializor</code>.</p>\n<h1>Function names</h1>\n<p>Avoid overloading <code>state()</code> to mean either setting the state or getting the state. While related, these are different operations, and it is much better to make that explicit by giving them different function names. An obvious modification is to name them <code>get_state()</code> and <code>set_state()</code>, but that sounds quite generic. I would also make it explicit that you are converting to or from JSON, so consider naming them <code>to_json()</code> and <code>from_json()</code>.</p>\n<h1>Overhead</h1>\n<p>Your serialization method introduces a huge overhead. Every instance of a serializable struct now has to contain a <code>std::unordered_map</code>, which is filled in in the constructor. So this costs time and memory. It would be much nicer if you could build this only once per type that derives from <code>properties</code>. Perhaps it can be done using static variables and <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">CRTP</a>, something like:</p>\n<pre><code>template<typename T>\nstruct properties\n{\n struct registry\n {\n // keeps the actual mapping\n ...\n };\n \n template <typename U>\n void set(str::string_view const& k, U&& v) {\n // forward it to the registry object, along with a pointer to the object\n auto self = static_cast<T *>(this);\n self->registry.set(self, k, v);\n }\n\n ...\n};\n\nstruct S: properties<S>\n{\n bool b{};\n int i{};\n \n static properties::registry reg_;\n\npublic:\n ...\n};\n\nS::properties::registry S::reg_ = {{"b", &S::b}, {"i", &S::i}};\n</code></pre>\n<p>But I struggle myself with how to create a constructor for <code>properties::registry</code> that would allow the above code (especially the last line) to work.</p>\n<h1>Make <code>get()</code> <code>const</code></h1>\n<p>You should make the <code>get()</code> member function <code>const</code>, as it should not modify the state, and this will allow that functions to be used on <code>const</code> instances of classes that inherit from <code>properties</code>.</p>\n<h1>Use range-<code>for</code> where possible</h1>\n<p>You can simplify the code in some places by using range-<code>for</code>. For example, in <code>properties::state()</code>, where you can also combine it with structured binding:</p>\n<pre><code>for (auto &[name, variable]: reg_)\n{\n r.emplace(name, variable.serializer());\n}\n</code></pre>\n<p>It is unfortunate that the iterator of <code>nlm::json</code> doesn't work the same way; you can only access the value in a range-<code>for</code>, not the key.</p>\n<h1>Crash at runtime when accessing a non-existing property</h1>\n<p>If in <code>main()</code>, you call <code>s.get("x")</code>, the program crashes with a segmentation fault. Even if you never expect this function to be called with a user-supplied name, it still makes it hard to debug programming errors. Check the return value of calls to <code>find()</code> before trying to dereference the result. You could throw a <code>std::runtime_error</code> if <code>find()</code> return <code>nulltpr</code>, or if you don't want to use exceptions or pay for the performance cost in production builds, at least use <code>assert()</code> to help with debug builds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:31:25.817",
"Id": "488636",
"Score": "0",
"body": "The \"or\" not \"er\" is there because we're dealing with functors. Yeah, `const`s can be placed to. even more places, as far as the constructor goes, no, that's not possible like you've had in mind. The overhead is huge, but the approach is also very convenient, for a gui it might be ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:03:21.707",
"Id": "488640",
"Score": "1",
"body": "@user1095108 Neither `set()` nor `get()` are `const` functions in the code you posted. And `set()` should of course not be `const` at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T16:59:57.740",
"Id": "488645",
"Score": "0",
"body": "`set()` could be qualified as `const`, that was my point. It just looks up a functor and forwards into it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:19:04.417",
"Id": "249313",
"ParentId": "249308",
"Score": "3"
}
},
{
"body": "<p>Now without a map:</p>\n<pre><code>#include <cassert>\n\n#include <functional>\n\nnamespace nlm = nlohmann;\n\nclass properties\n{\n using serializor_t = std::function<nlm::json()>;\n using deserializor_t = std::function<void(nlm::json)>;\n\n struct property_info\n {\n std::string_view k;\n serializor_t serializor;\n deserializor_t deserializor;\n };\n\n std::function<property_info const*(\n std::function<bool(property_info const&)>\n )> visitor_;\n\npublic:\n virtual ~properties() = default;\n\n //\n nlm::json state() const;\n void state(nlm::json const&) const;\n\n //\n template <std::size_t I = 0, typename A = std::array<property_info, I>, typename U>\n auto register_property(std::string_view k, U&& u, A&& a = {})\n {\n std::array<property_info, I + 1> b;\n std::move(a.begin(), a.end(), b.begin());\n\n if constexpr (std::is_invocable_v<U>)\n {\n *b.rbegin() = {\n std::move(k),\n [=]()noexcept(noexcept(u()))->decltype(auto){return u();},\n {}\n };\n }\n else if constexpr (std::is_lvalue_reference_v<U>)\n {\n if constexpr (std::is_const_v<std::remove_reference_t<U>>)\n {\n *b.rbegin() = {\n std::move(k),\n [&]()noexcept->decltype(auto){return u;},\n {}\n };\n }\n else\n {\n *b.rbegin() = {\n std::move(k),\n [&]()noexcept->decltype(auto){return u;},\n [&](auto&& j){u = j.template get<std::remove_cvref_t<U>>();}\n };\n }\n }\n\n return [this, b(std::move(b))](auto&& ...a) mutable\n {\n if constexpr (bool(sizeof...(a)))\n {\n return register_property<I + 1>(std::forward<decltype(a)>(a)...,\n std::move(b));\n }\n else\n {\n visitor_ = [b(std::move(b)), c(std::move(visitor_))](auto f)\n noexcept(noexcept(f({})))\n {\n for (auto& i: b)\n {\n if (f(i))\n {\n return &i;\n }\n }\n\n return c ? c(std::move(f)) : typename A::const_pointer{};\n };\n }\n };\n }\n\n template <std::size_t I = 0, typename A = std::array<property_info, I>,\n typename U, typename V,\n std::enable_if_t<\n std::is_invocable_v<U> &&\n std::is_invocable_v<V, decltype(std::declval<U>()())>,\n int\n > = 0\n >\n auto register_property(std::string_view k, U&& u, V&& v, A&& a = {})\n {\n std::array<property_info, I + 1> b;\n std::move(a.begin(), a.end(), b.begin());\n\n *b.rbegin() = {\n std::move(k),\n [=]()noexcept(noexcept(u()))->decltype(auto){return u();},\n [=](auto&& j){v(std::forward<decltype(j)>(j));}\n };\n\n return [this, b(std::move(b))](auto&& ...a) mutable\n {\n if constexpr (bool(sizeof...(a)))\n {\n return register_property<I + 1>(std::forward<decltype(a)>(a)...,\n std::move(b));\n }\n else\n {\n visitor_ = [b(std::move(b)), c(std::move(visitor_))](auto f)\n noexcept(noexcept(f({})))\n {\n for (auto& i: b)\n {\n if (f(i))\n {\n return &i;\n }\n }\n\n return c ? c(std::move(f)) : typename A::const_pointer{};\n };\n }\n };\n }\n\n //\n nlm::json get(std::string_view const&) const;\n\n template <typename U>\n auto set(std::string_view const& k, U&& u) const\n {\n if (auto const pi(visitor_([&](auto& pi) noexcept\n {\n return pi.k == k;\n })); pi && pi->deserializor)\n {\n pi->deserializor(std::forward<U>(u));\n }\n\n return [&](auto&& ...a)\n {\n return set(std::forward<decltype(a)>(a)...);\n };\n }\n};\n\nnlm::json properties::get(std::string_view const& k) const\n{\n if (auto const pi(visitor_([&](auto& pi) noexcept\n {\n return pi.k == k;\n })); pi)\n {\n return pi->serializor();\n }\n else\n {\n return nlm::json();\n }\n}\n\nnlm::json properties::state() const\n{\n nlm::json r(nlm::json::object());\n\n visitor_([&](auto& pi)\n {\n r.emplace(pi.k, pi.serializor());\n\n return false;\n }\n );\n\n return r;\n}\n\nvoid properties::state(nlm::json const& e) const\n{\n assert(e.is_object());\n for (auto i(e.cbegin()), ecend(e.cend()); ecend != i; i = std::next(i))\n {\n auto&& k(i.key());\n\n if (auto const pi(visitor_([&](auto& pi) noexcept\n {\n return pi.k == k;\n })); pi && pi->deserializor)\n {\n pi->deserializor(i.value());\n }\n }\n}\n\nint main()\n{\n struct S: properties\n {\n bool b{};\n int i{};\n\n S()\n {\n register_property("b", b)("i", i)("joke",[]{return "just a joke";})();\n }\n } s;\n\n s.set("b", true)("i", 11.1);\n\n std::cout << s.get("b") << std::endl;\n std::cout << s.state() << std::endl;\n}\n</code></pre>\n<p>This is generative programming in action. We generate a lambda for traversing over all property infos. We could just as well have generated a data structure (such as an array, a tuple, ...), but the type of these is unknown in advance, so we would need some type-erasure approach to interpret and store this data. This means we would not be able to avoid generating a functor, that would "know", what the generated data-structure was and how/where it was stored.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:44:51.397",
"Id": "249331",
"ParentId": "249308",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T11:43:54.823",
"Id": "249308",
"Score": "5",
"Tags": [
"c++",
"serialization",
"properties",
"c++20"
],
"Title": "(de)serializing c++ object almost automagically"
}
|
249308
|
<p>I'm doing a Coursera assignment on an HTML-CSS course. The assignment is to do a simple responsive page, which can be found <a href="https://github.com/jhu-ep-coursera/fullstack-course4/blob/master/assignments/assignment2/Assignment-2.md" rel="nofollow noreferrer">here</a>.</p>
<p>I think I came up with a solution, but I ended up having around 100 lines for the stylesheet, so I suppose that there is some ways to achieve the desired layouts in a more intuitive and easy way. I want a little bit of feedback on what I can improve here.</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>* {
font-family: "Comic Sans MS", cursive, sans-serif;
box-sizing: border-box;
}
h1{
text-align: center;
}
.sign_fs{
position: relative;
width: 50%;
min-width: fit-content;
padding: 5px 10px 5px 10px;
border: 5px solid black;
float: right;
font-size: 20px;
text-align: center;
margin-top: -2px;
margin-right: -2px;
}
#chicken {
background-color: pink;
}
#beef {
background-color: slateblue;
}
#sushi{
background-color: skyblue;
}
@media (min-width: 992px) {
.text_fs {
font-size: 15px;
clear: both;
margin: 1%;
padding: 1%;
}
.div_fs {
background-color: grey;
border: 2px solid black;
width: 31.2%;
margin: 1%;
float: left;
}
}
@media(max-width: 992px) and (min-width:768px) {
.text_fs {
font-size: 15px;
clear: both;
margin: 1%;
padding: 1%;
}
.div_tablet_top {
background-color: grey;
border: 2px solid black;
width: 48%;
margin: 1%;
float: left;
}
.div_tablet_bot {
background-color: grey;
border: 2px solid black;
width: 98%;
margin: 1%;
float: left;
}
#sushi{
width: 20%;
}
}
@media (max-width: 768px) {
section {
margin: 10px;
padding-top: 0px;
}
.div_mobile{
background-color: grey;
border: 2px solid black;
margin: 1%;
margin-top: 20px;
padding: 10px;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Module 2 solution</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Our Menu</h1>
<section>
<div class="div_fs div_tablet_top div_mobile">
<div class="sign_fs" id="chicken">Chicken</div>
<div class="text_fs" >
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="div_fs div_tablet_top div_mobile">
<div class="sign_fs" id="beef">Beef</div>
<div class="text_fs" >
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="div_fs div_tablet_bot div_mobile">
<div class="sign_fs" id="sushi">Sushi</div>
<div class="text_fs">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
</section>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T20:03:50.817",
"Id": "488875",
"Score": "0",
"body": "(suggestion) try to use relative units, over absolute(like pixel) units, specially as responsiveness is a case.\n1 pixel may be too big, or too SMALL, depending on device screen density. But usually an inch is an inch. Hope it helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T23:09:49.993",
"Id": "488890",
"Score": "0",
"body": "@911992 I know your advice may seem brief but please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:03:44.480",
"Id": "489232",
"Score": "0",
"body": "Comic Sans!! They will fail you instantly ;) https://designforhackers.com/blog/comic-sans-hate/"
}
] |
[
{
"body": "<h1>Simplifying overall layout</h1>\n<p>While I haven't gone through the coursera videos I did look at the syllabus. I see that the next assignment does involve using Bootstrap framework. Since this assignment requires no frameworks to be used, one option to consider looking at is <a href=\"https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox\" rel=\"nofollow noreferrer\">flexbox</a>. It was designed to eliminate the need for floating elements. One important thing to consider is <a href=\"https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox#Cross-browser_compatibility\" rel=\"nofollow noreferrer\">browser compatibility</a>. From a cursory search I don't see any requirement about browser compatibility in the Module 2 Coding Assignment but it is something to consider in other projects.</p>\n<h1>Simplifying current rules</h1>\n<p>Here are some suggestions to simplify the current rules in the stylesheet, without introducing flex styles.</p>\n<h3>Simplifying padding</h3>\n<p>The ruleset for <code>.sign_fs</code> contains this padding rule:</p>\n<blockquote>\n<pre><code> padding: 5px 10px 5px 10px;\n</code></pre>\n</blockquote>\n<p>This can be simplified to</p>\n<pre><code>padding: 5px 10px\n</code></pre>\n<p>because "When <strong>two</strong> values are specified, the first padding applies to the <strong>top and bottom</strong>, the second to the <strong>left and right</strong>."<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/padding#Syntax\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<h3>redundant styles can be combined</h3>\n<p>Within <code>@media(max-width: 992px) and (min-width:768px) { </code> the rulesets for <code>.div_tablet_top</code> and <code>.div_tablet_bot</code> are nearly identical except for the <code>width</code> rules, so all other rules could be abstracted to a common ruleset:</p>\n<pre><code>.div_tablet_top,\n.div_table_bottom {\n background-color: grey;\n border: 2px solid black;\n margin: 1%;\n float: left;\n}\n</code></pre>\n<h3>Excess class names</h3>\n<p>The class names <code>div_fs</code> and <code>div_mobile</code> are shared by all the <code><div></code> elements that are direct descendants of the <code><section></code> element. Because of this, those class names could be removed and the selectors could merely use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator\" rel=\"nofollow noreferrer\">child combinator</a>: <code>section > div</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T21:28:06.503",
"Id": "249515",
"ParentId": "249309",
"Score": "5"
}
},
{
"body": "<p>From a short review, 2 items;</p>\n<ul>\n<li><p><a href=\"https://designforhackers.com/blog/comic-sans-hate\" rel=\"nofollow noreferrer\">Comic Sans.. I would look for another font</a></p>\n</li>\n<li><p>Hardcoding your food items (beef, chicken, sushi) will not age well over time, since I cant see a link between the food and the color. I would suggest you just give a color to the first, second, and third item. For example the below will make the first sign pink;</p>\n<pre><code> section>div:nth-child(1)>.sign_fs{\n background-color: pink;\n }\n</code></pre>\n</li>\n</ul>\n<p>I am no CSS guru, so I had to play a while with it to make <code>nth-child</code> selector work;</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>* {\n font-family: \"Comic Sans MS\", cursive, sans-serif;\n box-sizing: border-box;\n}\n\nh1{\n text-align: center;\n}\n\n\n.sign_fs{\n position: relative;\n width: 50%;\n min-width: fit-content;\n padding: 5px 10px 5px 10px;\n border: 5px solid black;\n float: right;\n font-size: 20px;\n text-align: center;\n margin-top: -2px;\n margin-right: -2px;\n}\n\n/* pink, cornflowerblue, skyblue*/\n\nsection>div:nth-child(1)>.sign_fs{\n background-color: pink;\n}\n\nsection>div:nth-child(2)>.sign_fs{\n background-color: cornflowerblue;\n}\n\nsection>div:nth-child(3)>.sign_fs{\n background-color: skyblue;\n}\n\n\n@media (min-width: 992px) {\n .text_fs {\n font-size: 15px;\n clear: both;\n margin: 1%;\n padding: 1%;\n }\n\n .div_fs {\n background-color: grey;\n border: 2px solid black;\n width: 31.2%;\n margin: 1%;\n float: left;\n }\n\n}\n\n@media(max-width: 992px) and (min-width:768px) {\n .text_fs {\n font-size: 15px;\n clear: both;\n margin: 1%;\n padding: 1%;\n }\n\n .div_tablet_top {\n background-color: grey;\n border: 2px solid black;\n width: 48%;\n margin: 1%;\n float: left;\n }\n\n .div_tablet_bot {\n background-color: grey;\n border: 2px solid black;\n width: 98%;\n margin: 1%;\n float: left;\n }\n\n #sushi{\n width: 20%;\n }\n}\n\n@media (max-width: 768px) {\n section {\n margin: 10px;\n padding-top: 0px;\n }\n\n .div_mobile{\n background-color: grey;\n border: 2px solid black;\n margin: 1%;\n margin-top: 20px;\n padding: 10px;\n\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Module 2 solution</title>\n <link rel=\"stylesheet\" href=\"styles.css\">\n</head>\n<body>\n <h1>Our Menu</h1>\n <section>\n <div class=\"div_fs div_tablet_top div_mobile\">\n <div class=\"sign_fs\" id=\"chicken\">Chicken</div>\n <div class=\"text_fs\" >\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"div_fs div_tablet_top div_mobile\">\n <div class=\"sign_fs\" id=\"beef\">Beef</div>\n <div class=\"text_fs\" >\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div> \n <div class=\"div_fs div_tablet_bot div_mobile\">\n <div class=\"sign_fs\" id=\"sushi\">Sushi</div>\n <div class=\"text_fs\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n </section>\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-09-18T14:36:11.050",
"Id": "489269",
"Score": "0",
"body": "I believe I know the reason based on past experiences but for the sake of the OP and posterity you might want to explain why a font other than Comic Sans should be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T19:24:43.390",
"Id": "489292",
"Score": "0",
"body": "Put a link to a balanced review of Comic Sans"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:43:31.033",
"Id": "249538",
"ParentId": "249309",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249515",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T14:12:40.180",
"Id": "249309",
"Score": "7",
"Tags": [
"html",
"css",
"html5"
],
"Title": "Example of responsive webpage"
}
|
249309
|
<p>here below a working implementation that finds the minimal distance between k(set <code>=4</code> below) clusters in a graph.
I have doubts mainly on the implementation of the Disjoint Set structure: instead of using STL containers, I went along with an array of pointers as data structure hosting the leader nodes, in order to have some practice with C-style pointers.</p>
<p>Here is the Graph structure:
Graph.h</p>
<pre><code>// creates and manages a graph data structure
#ifndef GRAPH_H_INCLUDED
#define GRAPH_H_INCLUDED
#include <array>
#include <vector>
#include <list>
#include <fstream>
#include <string>
#include <iostream>
class Edge
{
public:
// constructors
Edge();
Edge(int, int, int);
std::array<int, 2> getNodes() const;
void setNodes(const int, const int);
int getCost() const;
void setCost(const int);
void swapNodes();
// a get() that allows writing:
int operator[](const int);
bool operator==(const Edge&) const;
bool operator!=(const Edge&) const;
private:
int node1, node2; // nodes are just indices of the nodes in the graph
int cost;
};
class Node
{
friend class Graph; // friendship needed by printing routine in Graph
public:
// constructors
Node();
Node(const Edge&);
int getLabel() const {return label;}
Edge getEdge(const int) const;
void setLabel(const int in) {label = in;}
void addEdge(const Edge in) {edges.push_back(in);}
void addManyEdges(const std::vector<Edge>);
int getScore() const {return score;}
void setScore(const int in) {score = in;}
std::list<Edge>::size_type size() const {return edges.size();} // size of list 'edges'
// iterators
typedef std::list<Edge>::iterator iterator;
typedef std::list<Edge>::const_iterator const_iterator;
std::list<Edge>::iterator begin() {return edges.begin();}
std::list<Edge>::iterator end() {return edges.end();}
std::list<Edge>::const_iterator cbegin() const {return edges.begin();}
std::list<Edge>::const_iterator begin() const {return edges.begin();}
std::list<Edge>::const_iterator cend() const {return edges.end();}
std::list<Edge>::const_iterator end() const {return edges.end();}
// inserts group of edges to the end of a edges vector
std::list<Edge>::iterator insertEdges(const std::list<Edge>::iterator beg_in,
const std::list<Edge>::iterator end_in)
{
return edges.insert(end(), beg_in, end_in);
}
// erase node
std::list<Edge>::iterator erase(int);
bool operator==(const Node&) const;
bool operator!=(const Node&) const;
private:
int label;
std::list<Edge> edges;
int score; // new, starts at 10000000, is equal to lowest cost Edge in 'edges'
};
class Graph
{
public:
Graph();
// constructor from txt file
Graph(const std::string&);
Node getNode(const int index) const {return nodes[index];}
void addNode(const Node in) {nodes.push_back(in);}
std::vector<Node>::size_type size() {return nodes.size();} // size of vector 'nodes'
std::vector<Node>::size_type size() const {return nodes.size();} // size of vector 'nodes'
void output() const; // prints graph
void output(const int) const;
// iterators
typedef std::vector<Node>::iterator iterator;
typedef std::vector<Node>::const_iterator const_iterator;
std::vector<Node>::iterator begin() {return nodes.begin();}
std::vector<Node>::iterator end() {return nodes.end();}
std::vector<Node>::const_iterator begin() const {return nodes.begin();}
std::vector<Node>::const_iterator end() const {return nodes.end();}
Node& operator[](const int index)
{
return nodes[index];
}
std::vector<Node>::iterator erase(const int index)
{
return nodes.erase(nodes.begin() + index);
}
private:
std::vector<Node> nodes;
};
bool compareCosts(const Edge&, const Edge&);
bool compareScores(const Node&, const Node&);
bool compareLabels(const Node&, const Node&);
#endif // GRAPH_H_INCLUDED
</code></pre>
<p>Graph.cpp:</p>
<pre><code>#include <iostream>
#include <fstream>
#include <array>
#include <list>
#include <string>
#include <algorithm>
#include "Graph.h"
using std::array; using std::ifstream;
using std::string; using std::endl;
using std::cout; using std::list;
using std::equal;
// Edge
// constructors
Edge::Edge():node1(0), node2(0), cost(0) {}
Edge::Edge(int node_1, int node_2, int len): node1(node_1), node2(node_2), cost(len) {}
array<int, 2> Edge::getNodes() const
{
array<int, 2> ret = {node1, node2};
return ret;
}
void Edge::setNodes(const int in1, const int in2)
{
node1 = in1;
node2 = in2;
}
int Edge::getCost() const
{
return cost;
}
void Edge::setCost(const int len)
{
cost = len;
}
void Edge::swapNodes()
{
node1 = node1 - node2;
node2 += node1;
node1 = node2 - node1;
}
// same as getNodes() above
int Edge::operator[](const int index)
{
if (index == 0) return node1;
else if (index == 1) return node2;
else {
try {throw;}
catch(...) {cout << "edge index must be either 0 or 1" << endl;}
return 1;
}
}
bool Edge::operator==(const Edge& rhs) const
{
if ( (node1 == rhs.getNodes()[0]) && (node2 == rhs.getNodes()[1]) && cost == rhs.getCost() )
return true;
else
return false;
}
bool Edge::operator!=(const Edge& rhs) const
{
if ( !(*this == rhs) )
return true;
else
return false;
}
// Node
//constructors
Node::Node(): label(0), edges(0), score(10000000) {}
Node::Node(const Edge& edg): label(edg.getNodes()[0]), edges(0), score(10000000)
{
edges.push_back(edg);
}
Edge Node::getEdge(const int index) const
{
Edge ret;
list<Edge>::const_iterator iter = edges.begin();
advance(iter, index);
return *iter;
}
void Node::addManyEdges(const vector<Edge> input)
{
for (size_t i = 0; i != input.size(); i++)
{
edges.push_back(input[i]);
}
}
list<Edge>::iterator Node::erase(int index)
{
list<Edge>::iterator iter = edges.begin();
advance(iter, index);
return edges.erase(iter);
}
bool Node::operator==(const Node& rhs) const
{
return label == rhs.getLabel() && equal( edges.begin(), edges.end(), rhs.begin() ); // no need to equate scores
}
bool Node::operator!=(const Node& rhs) const
{
return !(*this == rhs);
}
// Graph
// constructors
Graph::Graph(): nodes(0) {}
Graph::Graph(const string& file_input): nodes(0) // constructor from file
{
string filename(file_input + ".txt");
string line;
ifstream is;
is.open(filename);
int number_nodes; //, number_edges;
is >> number_nodes; // >> number_edges;
nodes.resize(number_nodes); // reserve the Node vector of size 'number_nodes'
int node1, node2, cost;
while (is >> node1 >> node2 >> cost)
{
int nodes_array[2] = {node1, node2};
for (int& node_i : nodes_array) {
if (nodes[node_i - 1].size() == 1)
nodes[node_i - 1].setLabel(node_i);
}
Edge current_edge(node1, node2, cost);
nodes[node1 - 1].addEdge(current_edge);
if (node1 != node2) {
current_edge.swapNodes();
nodes[node2 - 1].addEdge(current_edge);
}
}
is.close();
}
// prints all input nodes
void Graph::output() const
{
for (size_t i = 0; i != nodes.size(); ++i)
{
cout << "Node " << nodes[i].getLabel() << ", size = " << nodes[i].edges.size() << " with edges: ";
for (size_t j = 0; j != nodes[i].edges.size(); ++j)
{
int node_left = nodes[i].getEdge(j).getNodes()[0];
int node_right = nodes[i].getEdge(j).getNodes()[1];
int cost = nodes[i].getEdge(j).getCost();
cout << "[" << node_left << "-" << node_right << ", " << cost << "] ";
}
cout << endl;
}
}
// prints 10 neighbours around picked node
void Graph::output(const int picked_node) const
{
for (int i = picked_node - 5; i != picked_node + 5; ++i)
{
cout << "Node " << nodes[i].getLabel() << ", with edges: ";
for (size_t j = 0; j != nodes[i].edges.size(); ++j)
{
int node_left = nodes[i].getEdge(j).getNodes()[0];
int node_right = nodes[i].getEdge(j).getNodes()[1];
int cost = nodes[i].getEdge(j).getCost();
int score = nodes[node_right - 1].getScore();
cout << "[" << node_left << "-" << node_right << ", " << cost << ", " << score << "] ";
}
cout << endl;
}
}
bool compareCosts(const Edge& a, const Edge& b)
{
return a.getCost() < b.getCost();
}
bool compareScores(const Node& a, const Node& b)
{
return a.getScore() > b.getScore();
}
bool compareLabels(const Node& a, const Node& b)
{
return a.getLabel() > b.getLabel();
}
</code></pre>
<p>BFS implementation for Kruskal (alternative to Disjoint Set Kruskal implementation)
BreadthFirstSearch.h</p>
<pre><code>#ifndef BREADTHFIRSTSEARCH_H_INCLUDED
#define BREADTHFIRSTSEARCH_H_INCLUDED
#include <limits>
#include "Graph.h"
int const infinity = std::numeric_limits<int>::infinity();
bool breadthFirstSearch(const Graph&, const int, const int);
#endif // BREADTHFIRSTSEARCH_H_INCLUDED
</code></pre>
<p>BreadthFirstSearch.cpp</p>
<pre><code>#include <iostream>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include "BreadthFirstSearch.h"
using std::cout; using std::endl;
using std::cin; using std::find_if;
using std::vector; using std::queue;
using std::map;
bool breadthFirstSearch(const Graph& G, const int start_node_label, const int target_node_label)
{
// define type for explored/unexplored Nodes
enum is_visited {not_visited, visited};
map<int, is_visited> node_is_visited;
for (Graph::const_iterator iter = G.begin(); iter != G.end(); ++iter)
node_is_visited[iter->getLabel()] = not_visited;
Graph::const_iterator start_node_iter =
find_if(G.begin(), G.end(), [=](const Node& i){return i.getLabel() == start_node_label;});
if ( start_node_iter == G.end() )
return false;
node_is_visited[start_node_label] = visited;
Node next_node;
next_node = *start_node_iter;
// breadth-first algorithm runs based on queue structure
queue<Node> Q;
Q.push(next_node);
// BFS algorithm
while (Q.size() != 0) { // out of main loop if all nodes searched->means no path is present
Node current_node = Q.front();
Node linked_node; // variable hosting node on other end
for (size_t i = 0; i != current_node.size(); ++i) { // explore nodes linked to current_node by an edge
int linked_node_label = current_node.getEdge(i).getNodes()[1];
Graph::const_iterator is_linked_node_in_G =
find_if(G.begin(), G.end(), [=](const Node& a){return a.getLabel() == linked_node_label;});
if ( is_linked_node_in_G != G.end() ) { // check linked_node is in G
linked_node = *is_linked_node_in_G; //G_tot.getNode(linked_node_label - 1);
if (node_is_visited[linked_node_label] == not_visited) { // check if linked_node is already in the queue
node_is_visited[linked_node_label] = visited;
Q.push(linked_node); // if not, add it to the queue
// cout << "current " << current_node.getLabel() // for debug
// << " | linked = " << linked_node_label + 1
// << " | path length = " << dist[linked_node_label] << endl;
if (linked_node_label == target_node_label) // end search once target node is explored
return true;
}
} else {
if (linked_node_label == target_node_label) // end search once target node is explored
return false;
}
}
Q.pop();
}
return false;
}
</code></pre>
<p>DisjointSet.h</p>
<pre><code>#ifndef DISJOINTSET_H_INCLUDED
#define DISJOINTSET_H_INCLUDED
#include "Graph.h"
class DisjointSet
{
public:
DisjointSet(const size_t);
~DisjointSet();
DisjointSet& operator= (const DisjointSet&);
int find(const Node&);
void unionNodes(const Node&, const Node&);
int get(int index) {return *leaders[index];}
private:
size_t size; // graph size needed for allocation of pointer data members below
int* base; // array of int each Node of the graph has its leader
int** leaders; // array of pointers to int, allows to reassign leaders to Nodes after unions
int find_int(int); // auxiliary to 'find' above
DisjointSet(const DisjointSet&); // copy constructor forbidden
};
#endif // DISJOINTSET_H_INCLUDED
</code></pre>
<p>DisjointSet.cpp (here is where advice would be most appreciated)</p>
<pre><code>// Union-find structure (lazy unions)
#include "DisjointSet.h"
DisjointSet::DisjointSet(size_t in): size(in), base(new int[in]), leaders(new int*[in])
{
for (size_t i = 1; i != in + 1; ++i) {
base[i - 1] = i;
leaders[i - 1] = &base[i - 1];
}
}
DisjointSet::~DisjointSet()
{
delete[] base;
delete[] leaders;
}
DisjointSet& DisjointSet::operator= (const DisjointSet& rhs)
{
if (this == &rhs)
return *this; // make sure you aren't self-assigning
if (base != NULL) {
delete[] leaders; // get rid of the old data
delete[] base;
}
// "copy constructor" from here
size = rhs.size;
base = new int[size];
leaders = new int*[size];
base = rhs.base;
for (size_t i = 0; i != size; ++i)
leaders[i] = &base[i];
return *this;
}
// auxiliary to find: implements the recursion
int DisjointSet::find_int(int leader_pos)
{
int parent(leader_pos);
if (leader_pos != *leaders[leader_pos - 1])
parent = find_int(*leaders[leader_pos - 1]);
return parent;
}
// returns leader to input Node
int DisjointSet::find(const Node& input)
{
int parent( input.getLabel() );
if (input.getLabel() != *leaders[input.getLabel() - 1])
parent = find_int(*leaders[input.getLabel() - 1]);
return parent;
}
// merges sets by assigning same leader (the lesser of the two Nodes)
void DisjointSet::unionNodes(const Node& a, const Node& b)
{
if (find(a) != find(b)) {
if (find(a) < find(b))
leaders[find(b) - 1] = &base[find(a) - 1];
else
leaders[find(a) - 1] = &base[find(b) - 1];
}
}
</code></pre>
<p>KruskalClustering.h</p>
<pre><code>#ifndef KRUSKALCLUSTERING_H_INCLUDED
#define KRUSKALCLUSTERING_H_INCLUDED
#include <vector>
#include "Graph.h"
#include "DisjointSet.h"
int clusteringKruskalNaive(const Graph&, const std::vector<Edge>&, int);
int clusteringKruskalDisjointSet(const Graph& graph0, const std::vector<Edge>& edges, int);
#endif // KRUSKALCLUSTERING_H_INCLUDED
</code></pre>
<p>KruskalClustering.cpp</p>
<pre><code>// Kruskal MST algorithm. Implementation specific to (k=4)-clustering
// -naive (with breadth-first-search to check whether new edge creates a cycle); cost: O(#_edges * #_nodes)
// -and union-find implementations. Cost: O(#_edges*log2(#_nodes))
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> //std::find_if
#include "BreadthFirstSearch.h"
#include "KruskalClustering.h"
using std::cout; using std::endl;
using std::string; using std::vector;
using std::find_if;
int clusteringKruskalNaive(const Graph& graph0, const vector<Edge>& edges, int k)
{
Graph T; // Minimum Spanning Tree
vector<Edge>::const_iterator edges_iter = edges.begin();
int sum_costs(0), number_of_clusters( graph0.size() ); // keep track of overall cost of edges in T, and of clusters
while (number_of_clusters >= k) {
// find out if first node of edge is already in T
Graph::iterator is1_in_T = find_if(T.begin(), T.end(),
[=] (Node& a) {return a.getLabel() == graph0.getNode(edges_iter->getNodes()[0] - 1).getLabel();});
bool is1_in_T_flag; // needed because T gets increased and thus invalidates iterator is1_in_T
Node* node_1 = new Node(*edges_iter); // no use of pointer here, it creates a new Node anyway, can't move Nodes to T
if ( is1_in_T == T.end() ) { // node_1 not in T so we add it
T.addNode(*node_1);
number_of_clusters--; // node_1 is not its own cluster any more
delete node_1; // node_1 copied to T so ...
node_1 = &(T[T.size() - 1]); // ... it now points there
sum_costs += (*edges_iter).getCost();
is1_in_T_flag = false;
} else { // node_1 is in T already
delete node_1; // if so, just update the pointer
node_1 = &(*is1_in_T);
is1_in_T_flag = true;
}
// perform BFS to check for cycles
bool check_cycles = breadthFirstSearch(T, edges_iter->getNodes()[0], edges_iter->getNodes()[1]);
// create an identical edge, but with nodes positions swapped
Edge swapped_edge = *edges_iter;
swapped_edge.swapNodes();
// find out if second node of edge is already in T
Graph::iterator is2_in_T = find_if( T.begin(), T.end(),
[=] (Node& a) {return a.getLabel() == graph0.getNode(edges_iter->getNodes()[1] - 1).getLabel();});
// (either node1 or 2 not in T, or both, or both present but in different clusters of T)
if (!check_cycles) { // if edges_iter creates no cycle when added to T
if (is1_in_T_flag){ // if node_1 was already present in T
(*node_1).addEdge(*edges_iter); // just add new edge to node_1 list of edges
sum_costs += (*edges_iter).getCost();
} else
number_of_clusters++; // if node_1 not present, it means number_of_cl was decreased above ...
number_of_clusters--; // ... and number_of_cl can decrease just by one, if adding an edge to T
if ( is2_in_T != T.end() ) // node_2 already in T: just update its list of edges
(*is2_in_T).addEdge(swapped_edge);
else { // node_2 not in T, so add it
Node node_2(swapped_edge);
T.addNode(node_2);
}
} else { // cycle created by *edges_iter
if (!is1_in_T_flag) // in case the cycle happened just after adding node_1:
(*is2_in_T).addEdge(swapped_edge); // add edge to node_2, num_clusters already updated by node_1
}
if (number_of_clusters >= k) // advance to next Edge if num_clusters > k
edges_iter++;
// debug
// T.output();
// cout << "next edge: (" << (*edges_iter).getNodes()[0] << "-"
// << (*edges_iter).getNodes()[1] << ") " << endl;
// cout << "clustering: " << number_of_clusters << endl;
}
cout << "Sum of MST lengths is: " << sum_costs << endl;
return (*edges_iter).getCost();
}
// same algorithm, implemented with Union-find structure
int clusteringKruskalDisjointSet(const Graph& graph0, const vector<Edge>& edges, int k)
{
DisjointSet disjoint_set_graph0( graph0.size() ); // create Union-find structure
Graph T;
vector<Edge>::const_iterator edges_iter = edges.begin();
int sum_costs(0), number_of_clusters( graph0.size() );
while ( number_of_clusters >= k ) {
// if nodes in Edge have not the same leader in the disjoint set, then no loop is created, and T can add the edge
if ( disjoint_set_graph0.find(graph0.getNode(edges_iter->getNodes()[0] - 1)) !=
disjoint_set_graph0.find(graph0.getNode(edges_iter->getNodes()[1] - 1)) ) {
sum_costs += (*edges_iter).getCost();
number_of_clusters--; // no cycle created so the edge will be added to T
// look for node_1 in T
Graph::iterator is1_in_T = find_if(T.begin(), T.end(),
[=] (Node& a) {return a.getLabel() == graph0.getNode(edges_iter->getNodes()[0] - 1).getLabel();});
if ( is1_in_T == T.end() ) { // if node_1 not in T add it
Node node1(*edges_iter);
T.addNode(node1);
} else // if node_1 already in T only add to it this edge
(*is1_in_T).addEdge(*edges_iter);
Edge swapped_edge = *edges_iter;
swapped_edge.swapNodes();
// look for node_2 in T
Graph::iterator is2_in_T = find_if(T.begin(), T.end(),
[=] (Node& a) {return a.getLabel() == graph0.getNode(edges_iter->getNodes()[1] - 1).getLabel();});
if ( is2_in_T == T.end() ) { // same as for node_1
Node node2(swapped_edge);
T.addNode(node2);
} else
(*is2_in_T).addEdge(swapped_edge);
// merge the 2 nodes' sets: update their disjointed set leaders
disjoint_set_graph0.unionNodes( graph0.getNode(edges_iter->getNodes()[0] - 1),
graph0.getNode(edges_iter->getNodes()[1] - 1) );
}
if (number_of_clusters >= 4)
edges_iter++;
//debug
// T.output();
// cout << "next edge: (" << (*edges_iter).getNodes()[0] << "-"
// << (*edges_iter).getNodes()[1] << ") " << endl;
// cout << "clustering: " << number_of_clusters << endl;
// for (size_t i = 0; i != graph0.size(); ++i)
// cout << disjoint_set_graph0.get(i) << " ";
// cout << endl;
}
cout << "Sum of MST lengths is: " << sum_costs << endl;
return (*edges_iter).getCost();
}
</code></pre>
<p>Lastly, main.cpp :</p>
<pre><code>/* A max-spacing k-clustering program based on Kruskal MST algorithm.
The input file lists a complete graph with edge costs.
clusters k = 4 assumed.*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm> // std::sort;
#include "Graph.h"
#include "KruskalClustering.h"
using std::cout; using std::endl;
using std::string; using std::ifstream;
using std::vector; using std::sort;
int main(int argc, char** argv)
{
cout << "Reading list of edges from input file ...\n" << endl;
// read graph0 from input file
string filename(argv[1]);
Graph graph0(filename);
// graph0.output(); // debug
cout << endl;
// re-read input file and create a list of all edges in graph0
ifstream is(filename + ".txt");
int nodes_size;
is >> nodes_size;
vector<Edge> edges;
int node1, node2, cost;
while (is >> node1 >> node2 >> cost) {
Edge current_edge(node1, node2, cost);
edges.push_back(current_edge);
}
is.close();
// sort the edge list by increasing cost
cout << "Sorting edges ...\n" << endl;
sort(edges.begin(), edges.end(), compareCosts);
// for (vector<Edge>::iterator iter = edges.begin(); iter != edges.end(); ++iter) // debug
// cout << (*iter).getNodes()[0] << " " << (*iter).getNodes()[1] << " " << (*iter).getCost() << endl;
cout << "Kruskal algorithm: Computing minimal distance between clusters when they are reduced to 4 ...\n" << endl;
int k = 4; // number of clusters desired
// pick implementation, comment the other
//int clustering_min_dist = clusteringKruskalNaive(graph0, edges, k);
int clustering_min_dist = clusteringKruskalDisjointSet(graph0, edges, k);
cout << "k = " << k << " clusters minimal distance is: " << clustering_min_dist << endl;
return 0;
}
</code></pre>
<hr />
<h2>Edit: added input .txt file</h2>
<p>For completeness, here below an input file in the format accepted by the program. The file contains an undirected Graph, first line is the number of Nodes, the others are Edges(node1, node2, distance). The file should be a .txt .</p>
<pre><code>8
1 2 50
1 3 5
1 4 8
1 5 47
1 6 3
1 7 42
1 8 36
2 3 60
2 4 34
2 5 6
2 6 27
2 7 62
2 8 61
3 4 58
3 5 53
3 6 37
3 7 54
3 8 12
4 5 63
4 6 29
4 7 52
4 8 44
5 6 1
5 7 16
5 8 6
6 7 45
6 8 52
7 8 60
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T19:28:22.107",
"Id": "488650",
"Score": "0",
"body": "...perhaps looking a bit messy, too many comments and debugging, commented-out \"print\" statements scattered around the files?"
}
] |
[
{
"body": "<h1>Use your own <code>typedef</code>s</h1>\n<p>I see this code:</p>\n<pre><code>typedef std::list<Edge>::iterator iterator;\n...\nstd::list<Edge>::iterator begin() {return edges.begin();}\n</code></pre>\n<p>You should use your own <code>typedef</code>s, so the second line becomes:</p>\n<pre><code>iterator begin() {return edges.begin();}\n</code></pre>\n<p>Apart for less typing for yourself, it also avoids possible mistakes where you return a different type than the one you <code>typedef</code>'ed, and if you ever want to change the type you only have to do it in one place.</p>\n<h1>Simplify your classes</h1>\n<p>Looking at <code>class Edge</code>, I see that most member functions allow trivial getting and setting the <code>private</code> member variables. Why not make those member variables <code>public</code>, and allow them to be accessed directly?</p>\n<p>Also, if you have a <code>getNodes()</code> that returns an array and an <code>operator[]</code> to access the nodes as an array, maybe you should have store <code>node1</code> and <code>node2</code> as a <code>std::array<int, 2> nodes</code> to begin with. Although if you want edges to be directed, I would keep them separate and name them <code>from</code> and <code>to</code>.</p>\n<p>Furthermore, use default member initializers to void having to write any constructor:</p>\n<pre><code>class Edge {\npublic:\n bool operator==(const Edge &) const;\n bool operator!=(const Edge &) const;\n\n std::array<int, 2> nodes{};\n int cost{};\n};\n</code></pre>\n<p>Now you can do:</p>\n<pre><code>Edge e{1, 2, 3};\ne.nodes = {4, 5};\ne.cost = 6;\ne.nodes[0] = 7;\n</code></pre>\n<p>You can still add some convenience functions as needed, such as <code>swapNodes()</code>. Also, note that in C++20, with the above class, you can let the compiler generate <a href=\"https://en.cppreference.com/w/cpp/language/default_comparisons\" rel=\"nofollow noreferrer\">default comparison operators</a> for you in one line, like so:</p>\n<pre><code>class Edge {\npublic:\n ...\n auto operator<=>(const Node&) const = default;\n};\n</code></pre>\n<p>The same goes for <code>class Node</code> and <code>class Graph</code>: avoid making member variables <code>private</code> to then just write lots of wrapper functions to allow them to be accessed anyway.</p>\n<h1>Avoid unnecessary temporary variables</h1>\n<p>In <code>Edge::getNodes()</code>, there is no need to use a temporary variable, just write:</p>\n<pre><code>array<int, 2> Edge::getNodes() const\n{\n return {node1, node2};\n}\n</code></pre>\n<p>Of course this function is not necessary at all if you just store them as a public array to begin with.</p>\n<h1>Use <code>std::swap()</code> instead of writing your own</h1>\n<p>Instead of using the hand-written trick to swap two variables (did you check that you don't run in to undefined behaviour due to signed integer overflow?), there's a function in the standard library to do that for you:</p>\n<pre><code>void Edge::swapNodes() {\n std::swap(node1, node2);\n}\n</code></pre>\n<h1>Don't <code>try {throw;}</code></h1>\n<p>If you want to signal an error using an exception, just <code>throw</code> an <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"nofollow noreferrer\">exception of the proper type</a> that contains the error message, like so:</p>\n<pre><code>int Edge::operator[](const int index) {\n if (index == 0) return node1;\n else if (index == 1) return node2;\n else throw std::runtime_error("edge index must be either 0 or 1");\n}\n</code></pre>\n<p>What you are doing is too complicated (5 statements on 3 lines of code instead of a single statement), doesn't allow the caller to handle the error, and is illegal: you are only allowed to use <a href=\"https://en.cppreference.com/w/cpp/language/throw\" rel=\"nofollow noreferrer\"><code>throw</code></a> without an argument if you are already in exception handling code.</p>\n<h1>Don't <code>if (x) return true else return false;</code></h1>\n<p>If you already have a boolean expression, you don't have to use an <code>if-then-else</code> statement to return exactly the same boolean value, just write:</p>\n<pre><code>bool Edge::operator==(const Edge& rhs) const {\n return node1 == rhs.node1 && node2 == rhs.node2 && cost == rhs.const;\n}\n</code></pre>\n<h1>You can use initializer lists in member value initializers</h1>\n<p>Ok that sounds like nonsense, but what I mean is that you can construct a <code>std::list</code> with an initializer list to set the initial list members, and do that when doing member variable initialization in a constructor. For example:</p>\n<pre><code>Node::Node(const Edge& edg): label(edg.getNodes()[0]),\n score(10000000), // up to now, same as before\n edges{edg} // initializer list passed to constructor of edges\n{\n}\n</code></pre>\n<p>Note that you should combine this with default member initializers, so it becomes:</p>\n<pre><code>class Node {\n ...\n int label{};\n std::list<Edge> edges;\n int score{10000000};\n};\n\n...\n\nNode::Node() = default;\nNode::Node(const Edge &edg): label(edg.getNodes[0]), edges{edg} {}\n</code></pre>\n<h1>Iterating over the list of edges</h1>\n<p>A <code>std::list</code> does not have a random access iterator. You have noticed that already, and that is why in <code>Node::getEdge()</code>, you are using <code>std::advance()</code> to iterate to the element at the given index. You should know that this is quite slow, since it has to follow pointers. If you really need random access, it would be much faster to store the list of edges in a <code>std::vector</code> instead. But, in most cases you are iterating over the list of edges, and do some operation on each of them. In that case, don't use <code>getEdge()</code>, as it will get slower and slower the bigger the index is, but use list iterators directly, or even beter use range-<code>for</code> if possible. For example:</p>\n<pre><code>void Graph::output() const {\n for (auto node: nodes) {\n std::cout << "Node " << node.getLabel() << ", size = " << node.edges.size() << " with edges:";\n\n for (auto edge: node.edges) {\n std::cout << " [" << edge[0] << "-" << edge[1] << ", " << edge.getCost() << "]";\n }\n\n std::cout << "\\n";\n }\n}\n</code></pre>\n<h1>Use <code>"\\n"</code> instead of <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>"\\n"</code> instead of <code>std::endl</code></a>; the latter is equivalent to the former, except that it also forces a flush of the output buffer, which is often unnecessary and can slow down your program.</p>\n<h1>Writing generic output functions</h1>\n<p>Don't hard-code the use of <code>std::cout</code> in your output functions, but instead take a parameter that tells it what output stream to use, like so:</p>\n<pre><code>void Graph::output(std::ostream &out) const {\n for (auto node: nodes) {\n out << "Node " << node.getLabel() << ", size = " << node.edges.size() << " with edges:";\n ...\n</code></pre>\n<p>Also consider creating an <code>operator<<()</code>, like so:</p>\n<pre><code>class Graph {\n ...\n void output(std::ostream &out) const;\n\n friend std::ostream &operator<<(std::ostream &out, const Graph &graph) {\n graph.output(out);\n }\n}:\n</code></pre>\n<p>Now that you have overloaded <code>operator<<()</code> for your class, you can just write:</p>\n<pre><code>Graph graph;\n...\nstd::cout << graph;\n</code></pre>\n<h1>Writing generic input functions</h1>\n<p>The same goes for functions reading input as well. You have a constructor that takes a filename as an argument, but what if I have my graph stored in memory instead of in a file? Use a <code>std::istream</code> parameter, so that anything that can act as an input stream can be used to read the graph from:</p>\n<pre><code>class Graph {\n...\n Graph(std::istream &is);\n};\n\n...\n\nGraph::Graph(std::istream &is) {\n int number_nodes;\n is >> number_nodes;\n ...\n}\n</code></pre>\n<p>And then you just use it like so:</p>\n<pre><code>std::ifstream is(argv[1]);\nGraph graph0(is);\n</code></pre>\n<h1>Do proper error checking when reading and writing</h1>\n<p>Always be prepared that something can happen while reading and writing files. Maybe the disk is corrupt, you have run out of disk space, the permissions are incorrect, the file is on a network drive and the network is down, and so on. Also be prepared that the file might contain unexpected data.</p>\n<p>Your <code>while</code>-loop in the constructor of <code>Graph</code> that reads from a stream will exit either if it reached the end of the stream, or if there was an error. To ensure that it read everything correctly, check if <code>is.eof()</code> returns <code>true</code>. If not, I suggest you <code>throw</code> a <code>std::runtime_error</code>.</p>\n<p>When writing to a stream, whether it is a file or <code>std::cout</code>, check at the end of writing everything if <code>out.good()</code> returns <code>true</code>. If not, throw an exception again.</p>\n<h1>About using C-style pointer arrays</h1>\n<p>Yes, you can use those, but now you have to manually allocate and free the arrays. It's fine as an excercise, but an even better excercise is to convert those into <code>std::vector</code>s :)</p>\n<h1>Avoid <code>new</code> and <code>delete</code> in general</h1>\n<p>Manually calling <code>new</code> and <code>delete</code> is hardly ever necessary anymore, and is often a sign something should be managed by an appropriate container, or should not be a pointer in the first place. As an example of the latter, in <code>clusteringKruskalNaive()</code>, there is no need to use <code>new</code> to create the temporary <code>node_1</code>. It is deleted immediately afterwards, possibly without even having been used. Instead write:</p>\n<pre><code>bool is1_in_T_flag = is1_in_T != T.end();\nNode *node_1;\n\nif (is1_in_T_flag) {\n T.addNode(Node(*node_1));\n number_of_clusters--;\n node_1 = ...\n} else {\n node_1 = &*is1_in_T;\n}\n</code></pre>\n<h1>Try to make the code more readable</h1>\n<p>Especially in KruskalClustering.cpp, the code is very hard to read. Try to shorten the lines, by using <code>auto</code> where possible, simplifying expressions, giving clear and concise names to things, splitting off complex code into their own functions, and so on. Be consistent in how you initialize variables, I see both <code>int x = 1</code> and <code>int x(1)</code>. Also remove commented out code; you should use a revision control system like Git to store previous versions of you code in. Here is how it might look:</p>\n<pre><code>int clusteringKruskalDisjointSet(const Graph& graph, const vector<Edge>& edges, int k)\n{\n // Start with every node being in its own cluster\n auto number_of_clusters = graph.size();\n DisjointSet disjoint_set(number_of_clusters);\n\n int min_cost = INT_MAX;\n int sum_costs = 0;\n\n // Iterate over the given edges until only k distinct clusters are left\n for (auto edge_iter = edges.begin; number_of_clusters >= k; ++edge_iter) {\n auto &edge = *edge_iter;\n\n // Skip the edge if it is within a single cluster\n if (disjoint_set.find(graph.nodes[edge.nodes[0] - 1]) ==\n disjoint_set.find(graph.nodes[edge.nodes[1] - 1]))\n {\n continue;\n }\n\n // This edge joins two clusters\n min_cost = std::min(min_cost, edge.cost);\n sum_costs += edge.cost;\n number_of_clusters--;\n\n disjoint_set.unionNodes(graph.nodes[edge.nodes[0] - 1],\n graph.nodes[edge.nodes[1] - 1]);\n }\n\n std::cout << "Sum of MST lengths is: " << sum_costs << "\\n";\n return min_cost;\n}\n</code></pre>\n<p>I am left wondering: why keep track of <code>Graph T</code> in this function? It didn't do anything, so I could remove all code related to it. And why subtract <code>1</code> from the node indices here? Why loop while <code>number_of_clusters >= k</code>? That will result in <code>k - 1</code> clusters at the end of the algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T11:28:33.253",
"Id": "488706",
"Score": "0",
"body": "Brilliant answer, I have learned a good deal from it on how to improve my classes, thank you! Of course I was too lazy to go through the code and modify names after defining my own `typedef`s, once code works there is a certain tendency in programmers towards inertia ...\nAlso it seems obvious to me now that my Graph.h `class`es should really be `struct`s, too many awkward getters as they are now. And how you stripped down the Kruskal routine to its essentials really blew my mind! Overall, I have learned a lot about my shortcomings against good practices, this is exactly what I needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T11:44:31.993",
"Id": "488708",
"Score": "0",
"body": "your question: I needed the maximum spacing between clusters when they are reduced to k, that is, the next Edge in the sorted `vector<Edge>`, after the Minimum Spanning Tree T is reduced to k clusters. This is why I get k - 1 clusters on exit. \n`Graph T` is the MST; that Kruskal function really should calculate the MST of input `Graph`. In this context was not really needed and you intuition has greatly streamlined the code.\nNode indices -1 because in the input file they are labelled starting from 1, which would be `vector[0]` in C++, I had to litter indices with -1 everywhere"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:40:46.343",
"Id": "249327",
"ParentId": "249314",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249327",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:38:25.470",
"Id": "249314",
"Score": "4",
"Tags": [
"c++",
"breadth-first-search",
"clustering",
"union-find"
],
"Title": "K-clustering algorithm using Kruskal MST with Disjoint Set in place to check for cycles"
}
|
249314
|
<p>I have this tiny function that expects an <code>int</code> and returns an <code>int</code> with the bytes swapped:</p>
<pre><code>public class Main {
public static void main(String[] args) {
int cafeBabe = 0xcafebabe;
System.out.println(Integer.toHexString(cafeBabe));
System.out.println(Integer.toHexString(byteSwap(cafeBabe)));
System.out.println(Integer.toHexString(byteSwap(byteSwap(cafeBabe))));
}
public static int byteSwap(int a) {
return ((a & 0xff000000) >>> 24) |
((a & 0x00ff0000) >>> 8) |
((a & 0x0000ff00) << 8) |
((a & 0x000000ff) << 24);
}
}
</code></pre>
<p>Basically, we are switching between endianess. Now, is there a better/more efficient way of accomplishing the task?</p>
|
[] |
[
{
"body": "<p>I like it, simple to read.</p>\n<hr />\n<p>Personally, I prefer to keep operators on the new line, makes it easier to see how the lines belong together:</p>\n<pre class=\"lang-java prettyprint-override\"><code>return ((a & 0xff000000) >>> 24)\n | ((a & 0x00ff0000) >>> 8)\n | ((a & 0x0000ff00) << 8)\n | ((a & 0x000000ff) << 24);\n</code></pre>\n<p>To follow your formatting convention.</p>\n<hr />\n<p>You could putt the first and last byte underneath each other, to make the pattern even better visible:</p>\n<pre class=\"lang-java prettyprint-override\"><code>return ((a & 0xff000000) >>> 24)\n | ((a & 0x000000ff) << 24)\n | ((a & 0x00ff0000) >>> 8)\n | ((a & 0x0000ff00) << 8);\n</code></pre>\n<p>That removes the pattern from the masks, but allows to easier deduce how the bytes are being moved.</p>\n<hr />\n<p>You could also convert the <code>int</code> to a <code>byte</code> array (for example with the help of a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html\" rel=\"noreferrer\"><code>ByteBuffer</code></a>), and reverse that array before converting it back. But as far as effectiveness goes, I think this should be the one with the least operations, as basically any operation on a <code>byte</code> array would have to do the same thing and more.</p>\n<hr />\n<p>As already pointed out, there is already <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#reverseBytes-int-\" rel=\"noreferrer\"><code>Integer.reverseBytes(int)</code></a> which is available since 1.5.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T14:47:04.803",
"Id": "488728",
"Score": "0",
"body": "With `ByteBuffer` you can simply reverse the endianess and then read back the `int`, no need to do that manually (always look at the methods of a class :) )."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:25:54.363",
"Id": "249325",
"ParentId": "249317",
"Score": "6"
}
},
{
"body": "<h1>Historical Note</h1>\n<p>The very first comment on the OP's question -- long before any answers were posted -- was a question asked by myself, and it very pointedly asked:</p>\n<blockquote>\n<p>Without using <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Integer.html#reverseBytes(int)\" rel=\"nofollow noreferrer\">Integer.reverseBytes(cafeBabe)</a>?</p>\n</blockquote>\n<p>The question was two-fold:</p>\n<ol>\n<li>Point out to the OP that a built-in method exists, and is likely the most optimal way of doing this.</li>\n<li>Ask if they are trying to <a href=\"/questions/tagged/reinvent-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinvent-the-wheel'\" rel=\"tag\">reinvent-the-wheel</a>.</li>\n</ol>\n<p>That comment/question has been removed. If the OP responded to it, the response has been deleted as well and I never saw it.</p>\n<p>This answer is not advocating the OP <a href=\"/questions/tagged/reinvent-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinvent-the-wheel'\" rel=\"tag\">reinvent-the-wheel</a>. The Java JVM / JIT will have implemented the most efficient way of performing the operation, using internal features (such as <code>@HotSpotIntrinsicCandidate</code>) that are not necessarily available to the end-user.</p>\n<h1>Reinventing the wheel</h1>\n<pre><code>public static int byteSwap(int a) {\n return ((a & 0xff000000) >>> 24) |\n ((a & 0x00ff0000) >>> 8) |\n ((a & 0x0000ff00) << 8) |\n ((a & 0x000000ff) << 24);\n}\n</code></pre>\n<p>This function uses 6 distinct constants, 4 AND operations, 4 shifts, and 3 OR operations.</p>\n<p>There is no point with the AND operation in <code>((a & 0xff000000) >>> 24)</code> or in <code>((a & 0x000000ff) << 24)</code> since the 24 bits which are being masked are immediately shifted out anyway. This removes 2 constants, and 2 AND operations, which reduces the code to:</p>\n<pre><code>public static int byteSwap(int a) {\n return (a >>> 24) |\n ((a & 0x00ff0000) >>> 8) |\n ((a & 0x0000ff00) << 8) |\n (a << 24);\n}\n</code></pre>\n<p>By reworking the order of second operation, we can remove another constant, the <code>0x00ff0000</code>, and instead reuse the <code>0xff00</code> constant. This eliminates the loading of the third bit mask constant, saving additional JVM byte code instructions:</p>\n<pre><code>public static int byteSwap(int a) {\n return (a >>> 24) |\n ((a >>> 8) & 0xff00) |\n ((a & 0xff00) << 8) |\n (a << 24);\n}\n</code></pre>\n<p>This reworked version is very similar to the built-in <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Integer.html#reverseBytes(int)\" rel=\"nofollow noreferrer\"><code>Integer.reverseBytes()</code></a> code in the system library:</p>\n<pre><code>@HotSpotIntrinsicCandidate\npublic static int reverseBytes(int i) {\n return (i << 24) |\n ((i & 0xff00) << 8) |\n ((i >>> 8) & 0xff00) |\n (i >>> 24);\n}\n</code></pre>\n<p>I don't know if the difference in ordering gains any additional speed, but (dollars to donuts) the <code>@HotSpotIntrinsicCandidate</code> annotation probably does - so just use the built-in function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T10:47:26.910",
"Id": "488700",
"Score": "3",
"body": "While the masking in `(a & 0x000000FF) << 24` has no effect in this case, it sure adds its fair portion to readability. Since OP was asking for a _more efficient way_ I'd at least mention that this kind of optimization is in the most obvious realms of _micro optimizations_, Also there is a builtin function `reverseBytes(int)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T03:47:43.837",
"Id": "249336",
"ParentId": "249317",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "249336",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T17:20:08.140",
"Id": "249317",
"Score": "8",
"Tags": [
"java",
"integer"
],
"Title": "Swapping bytes of an integer in Java"
}
|
249317
|
<p>I've written an API that unlocks some serious MVVM capabilities with VBA's <code>MSForms</code> UI framework.</p>
<p>This is the complete code-behind for an example <code>UserForm</code> "view" - it's not the code under review, but since I'm 99% sure I won't have enough room to fit everything here I figure it gives a nice idea of what <em>Model-View-ViewModel</em> looks like in VBA - note that a more complex view implementation would only need more bindings, the only other code is just boilerplate to support cancellation:</p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Example
'@ModuleDescription "An example implementation of a View."
Implements IView
Implements ICancellable
Option Explicit
Private Type TView
'IView state:
ViewModel As ExampleViewModel
'ICancellable state:
IsCancelled As Boolean
'Data binding helper dependency:
Bindings As IBindingManager
End Type
Private this As TView
'@Description "A factory method to create new instances of this View, already wired-up to a ViewModel."
Public Function Create(ByVal ViewModel As ExampleViewModel, ByVal Bindings As IBindingManager) As IView
GuardClauses.GuardNonDefaultInstance Me, ExampleView, TypeName(Me)
GuardClauses.GuardNullReference ViewModel, TypeName(Me)
GuardClauses.GuardNullReference Bindings, TypeName(Me)
Dim result As ExampleView
Set result = New ExampleView
Set result.Bindings = Bindings
Set result.ViewModel = ViewModel
Set Create = result
End Function
Private Property Get IsDefaultInstance() As Boolean
IsDefaultInstance = Me Is ExampleView
End Property
'@Description "Gets/sets the ViewModel to use as a context for property and command bindings."
Public Property Get ViewModel() As ExampleViewModel
Set ViewModel = this.ViewModel
End Property
Public Property Set ViewModel(ByVal RHS As ExampleViewModel)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me)
GuardClauses.GuardNullReference RHS
Set this.ViewModel = RHS
InitializeBindings
End Property
'@Description "Gets/sets the binding manager implementation."
Public Property Get Bindings() As IBindingManager
Set Bindings = this.Bindings
End Property
Public Property Set Bindings(ByVal RHS As IBindingManager)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me)
GuardClauses.GuardDoubleInitialization this.Bindings, TypeName(Me)
GuardClauses.GuardNullReference RHS
Set this.Bindings = RHS
End Property
Private Sub BindViewModelCommands()
With Bindings
.BindCommand ViewModel, Me.OkButton, AcceptCommand.Create(Me)
.BindCommand ViewModel, Me.CancelButton, CancelCommand.Create(Me)
.BindCommand ViewModel, Me.BrowseButton, ViewModel.SomeCommand
'...
End With
End Sub
Private Sub BindViewModelProperties()
With Bindings
.BindPropertyPath ViewModel, "SourcePath", Me.PathBox, _
Validator:=New RequiredStringValidator, _
ErrorFormat:=AggregateErrorFormatter.Create(ViewModel, _
ValidationErrorFormatter.Create(Me.PathBox).WithErrorBackgroundColor.WithErrorBorderColor, _
ValidationErrorFormatter.Create(Me.InvalidPathIcon).WithTargetOnlyVisibleOnError("SourcePath"), _
ValidationErrorFormatter.Create(Me.ValidationMessage1).WithTargetOnlyVisibleOnError("SourcePath"))
.BindPropertyPath ViewModel, "Instructions", Me.InstructionsLabel
.BindPropertyPath ViewModel, "SomeOption", Me.OptionButton1
.BindPropertyPath ViewModel, "SomeOtherOption", Me.OptionButton2
.BindPropertyPath ViewModel, "SomeOptionName", Me.OptionButton1, "Caption", OneTimeBinding
.BindPropertyPath ViewModel, "SomeOtherOptionName", Me.OptionButton2, "Caption", OneTimeBinding
'...
End With
End Sub
Private Sub InitializeBindings()
If ViewModel Is Nothing Then Exit Sub
BindViewModelProperties
BindViewModelCommands
Bindings.ApplyBindings ViewModel
End Sub
Private Sub OnCancel()
this.IsCancelled = True
Me.Hide
End Sub
Private Property Get ICancellable_IsCancelled() As Boolean
ICancellable_IsCancelled = this.IsCancelled
End Property
Private Sub ICancellable_OnCancel()
OnCancel
End Sub
Private Sub IView_Hide()
Me.Hide
End Sub
Private Sub IView_Show()
Me.Show vbModal
End Sub
Private Function IView_ShowDialog() As Boolean
Me.Show vbModal
IView_ShowDialog = Not this.IsCancelled
End Function
Private Property Get IView_ViewModel() As Object
Set IView_ViewModel = this.ViewModel
End Property
</code></pre>
<p><img src="https://i.stack.imgur.com/2pW5N.png" alt="screenshot of the example View showing the bindings in action" /></p>
<p>The <em>lorem ipsum</em> title comes from the binding to the <code>Instructions</code> ViewModel property; the OK button is disabled because the command it's bound to cannot be executed.. because the ViewModel has more than 0 validation errors. The input field has an error icon, a pink background and a red border thanks to the <code>AggregateErrorFormatter</code> linked to the binding. If we selected other option button, the <code>BrowseCommand</code> would be executable and the associated button would have a tooltip - all without manually handling a single event.</p>
<h3>Property Bindings</h3>
<p>At the core of everything is the <code>IPropertyBinding</code> interface, defined as follows:</p>
<p><strong>IPropertyBinding</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Bindings
'@ModuleDescription "An object responsible for binding a ViewModel property path to a UI element."
'@Interface
'@Exposed
Option Explicit
Public Enum BindingMode
TwoWayBinding
OneWayBinding
OneWayToSource
OneTimeBinding
End Enum
Public Enum BindingUpdateSourceTrigger
OnPropertyChanged
OnKeyPress
OnExit
End Enum
'@Description "Gets a value indicating the binding mode/direction."
Public Property Get Mode() As BindingMode
End Property
'@Description "Gets a value indicating the binding update trigger."
Public Property Get UpdateSourceTrigger() As BindingUpdateSourceTrigger
End Property
'@Description "Gets the ViewModel object that is the binding source."
Public Property Get Source() As Object
End Property
'@Description "Gets a path to a Public Property Get procedure resolvable from the binding source."
Public Property Get SourcePropertyPath() As String
End Property
'@Description "Gets the UI element that is the binding target."
Public Property Get Target() As Object
End Property
'@Description "Gets the name of the bound property on the target object."
Public Property Get TargetProperty() As String
End Property
'@Description "Gets the converter to use (if any) when applying the binding."
Public Property Get Converter() As IValueConverter
End Property
'@Description "Applies the binding."
Public Sub Apply()
End Sub
</code></pre>
<p>The implementation is over 550 lines of code, mostly because it's being too many things at once, but I'm not sure how criminal it is to have the <code>PropertyBinding</code> class be self-contained like this. On the other hand all flags are raised and the bells are ringing, the interface needs separate implementations per control type, and suddenly it doesn't seem like a lot of code anymore. Worth splitting it up?</p>
<p>The class implements <code>IHandlePropertyChanged</code> and registers ViewModel <code>INotifyPropertyChanged</code> events in the <code>Create</code> factory method, like this:</p>
<pre class="lang-vb prettyprint-override"><code> If Mode <> OneWayToSource And TypeOf Source Is INotifyPropertyChanged Then
Dim notifier As INotifyPropertyChanged
Set notifier = Source
notifier.RegisterHandler result
End If
</code></pre>
<p>The class also implements the <code>INotifyPropertyChanged</code> interface, and its callback is registered in the <code>BindingManager</code> class, in the <code>BindPropertyPath</code> method; the <code>BindingManager</code> handles property changes by re-evaluating the commands' <code>CanExecute</code> method, which completes binding loop and makes commands responsive to property changes, just like property bindings.</p>
<p><strong>PropertyBinding</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Bindings
'@ModuleDescription "An object responsible for binding a ViewModel property path to a UI element."
'@PredeclaredId
'@Exposed
Implements IPropertyBinding
Implements IHandlePropertyChanged
Implements INotifyPropertyChanged
Option Explicit
Private Type TState
Handlers As Collection
Manager As IBindingManager
Mode As BindingMode
UpdateSourceTrigger As BindingUpdateSourceTrigger
Source As Object
SourcePropertyPath As String
Target As Object
TargetProperty As String
Converter As IValueConverter
Validator As IValueValidator
ValidationErrorHandler As IHandleValidationError
ValidationErrorFormatter As IValidationErrorFormatter
Applied As Boolean
End Type
Private WithEvents ControlEventSource As MSForms.Control
Private WithEvents TextBoxEventSource As MSForms.TextBox
Private WithEvents CheckBoxEventSource As MSForms.CheckBox
Private WithEvents OptionButtonEventSource As MSForms.OptionButton
Private WithEvents ComboBoxEventSource As MSForms.ComboBox
Private WithEvents ListBoxEventSource As MSForms.ListBox
Private this As TState
Public Function ForTextBox(ByVal Manager As IBindingManager, ByVal Target As MSForms.TextBox, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.TwoWayBinding, _
Optional ByVal UpdateSource As BindingUpdateSourceTrigger = OnPropertyChanged, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Set ForTextBox = Create(Manager, Target, "Text", Source, SourceProperty, Mode, UpdateSource, Validator, Converter, ErrorFormat)
End Function
Public Function ForCheckBox(ByVal Manager As IBindingManager, ByVal Target As MSForms.CheckBox, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.TwoWayBinding, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Set ForCheckBox = Create(Manager, Target, "Value", Source, SourceProperty, Mode, OnPropertyChanged, Validator, Converter, ErrorFormat)
End Function
Public Function ForOptionButton(ByVal Manager As IBindingManager, ByVal Target As MSForms.OptionButton, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.TwoWayBinding, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Set ForOptionButton = Create(Manager, Target, "Value", Source, SourceProperty, Mode, OnPropertyChanged, Validator, Converter, ErrorFormat)
End Function
Public Function ForLabel(ByVal Manager As IBindingManager, ByVal Target As MSForms.Label, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.OneWayBinding, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Set ForLabel = Create(Manager, Target, "Caption", Source, SourceProperty, Mode, OnPropertyChanged, Validator, Converter, ErrorFormat)
End Function
Public Function ForFrame(ByVal Manager As IBindingManager, ByVal Target As MSForms.Frame, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.OneWayBinding, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Set ForFrame = Create(Manager, Target, "Caption", Source, SourceProperty, Mode, OnPropertyChanged, Validator, Converter, ErrorFormat)
End Function
Public Function ForComboBoxValue(ByVal Manager As IBindingManager, ByVal Target As MSForms.ComboBox, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.TwoWayBinding, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Set ForComboBoxValue = Create(Manager, Target, "Value", Source, SourceProperty, Mode, OnPropertyChanged, Validator, Converter, ErrorFormat)
End Function
Public Function ForListBoxValue(ByVal Manager As IBindingManager, ByVal Target As MSForms.ListBox, ByVal Source As Object, ByVal SourceProperty As String, Optional ByVal Mode As BindingMode = BindingMode.TwoWayBinding, Optional ByVal Validator As IValueValidator, Optional ByVal Converter As IValueConverter) As IPropertyBinding
Set ForListBoxValue = Create(Manager, Target, "Value", Source, SourceProperty, Mode, OnPropertyChanged, Validator, Converter)
End Function
Public Function Create(ByVal Manager As IBindingManager, ByVal Target As Object, ByVal TargetProperty As String, ByVal Source As Object, ByVal SourceProperty As String, _
Optional ByVal Mode As BindingMode = BindingMode.TwoWayBinding, _
Optional ByVal UpdateSource As BindingUpdateSourceTrigger = BindingUpdateSourceTrigger.OnPropertyChanged, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter) As IPropertyBinding
Dim result As PropertyBinding
Set result = New PropertyBinding
Set result.Target = Target
result.TargetProperty = TargetProperty
Set result.Source = Source
result.SourcePropertyPath = SourceProperty
Set result.Manager = Manager
Set result.Converter = Converter
Set result.Validator = Validator
Set result.ValidationErrorFormatter = ErrorFormat
result.Mode = Mode
result.UpdateSourceTrigger = UpdateSource
If Mode <> OneWayToSource And TypeOf Source Is INotifyPropertyChanged Then
Dim notifier As INotifyPropertyChanged
Set notifier = Source
notifier.RegisterHandler result
End If
Set Create = result
End Function
Public Property Get Source() As Object
Set Source = this.Source
End Property
Public Property Set Source(ByVal RHS As Object)
GuardClauses.GuardDoubleInitialization this.Manager, TypeName(Me)
GuardClauses.GuardNullReference RHS, TypeName(Me)
Set this.Source = RHS
If TypeOf RHS Is IViewModel Then
Dim ViewModel As IViewModel
Set ViewModel = RHS
Set this.ValidationErrorHandler = ViewModel.Validation
End If
End Property
Public Property Get Target() As Object
Set Target = this.Target
End Property
Public Property Set Target(ByVal RHS As Object)
GuardClauses.GuardDoubleInitialization this.Target, TypeName(Me)
GuardClauses.GuardNullReference RHS, TypeName(Me)
Set this.Target = RHS
Set ControlEventSource = Nothing
Set TextBoxEventSource = Nothing
Set CheckBoxEventSource = Nothing
Set ComboBoxEventSource = Nothing
Set ListBoxEventSource = Nothing
Set OptionButtonEventSource = Nothing
If TypeOf this.Target Is MSForms.Control And this.UpdateSourceTrigger = OnExit Then Set ControlEventSource = this.Target
Select Case True
Case TypeOf this.Target Is MSForms.TextBox
Set TextBoxEventSource = this.Target
Case TypeOf this.Target Is MSForms.CheckBox And TypeName(this.Target) = "CheckBox" 'OptionButton matches the interface criteria
Set CheckBoxEventSource = this.Target
Case TypeOf this.Target Is MSForms.ComboBox
Set ComboBoxEventSource = this.Target
Case TypeOf this.Target Is MSForms.ListBox
Set ListBoxEventSource = this.Target
Case TypeOf this.Target Is MSForms.OptionButton
Set OptionButtonEventSource = this.Target
End Select
End Property
Public Property Get SourcePropertyPath() As String
SourcePropertyPath = this.SourcePropertyPath
End Property
Public Property Let SourcePropertyPath(ByVal RHS As String)
this.SourcePropertyPath = RHS
End Property
Public Property Get TargetProperty() As String
TargetProperty = this.TargetProperty
End Property
Public Property Let TargetProperty(ByVal RHS As String)
this.TargetProperty = RHS
End Property
Public Property Get Mode() As BindingMode
Mode = this.Mode
End Property
Public Property Let Mode(ByVal RHS As BindingMode)
this.Mode = RHS
End Property
Public Property Get UpdateSourceTrigger() As BindingUpdateSourceTrigger
UpdateSourceTrigger = this.UpdateSourceTrigger
End Property
Public Property Let UpdateSourceTrigger(ByVal RHS As BindingUpdateSourceTrigger)
this.UpdateSourceTrigger = RHS
End Property
Public Property Get Validator() As IValueValidator
Set Validator = this.Validator
End Property
Public Property Set Validator(ByVal RHS As IValueValidator)
Set this.Validator = RHS
End Property
Public Property Get ValidationErrorFormatter() As IValidationErrorFormatter
Set ValidationErrorFormatter = this.ValidationErrorFormatter
End Property
Public Property Set ValidationErrorFormatter(ByVal RHS As IValidationErrorFormatter)
Set this.ValidationErrorFormatter = RHS
End Property
Public Property Get Converter() As IValueConverter
Set Converter = this.Converter
End Property
Public Property Set Converter(ByVal RHS As IValueConverter)
Set this.Converter = RHS
End Property
Public Property Get Manager() As IBindingManager
Set Manager = this.Manager
End Property
Public Property Set Manager(ByVal RHS As IBindingManager)
GuardClauses.GuardDoubleInitialization this.Manager, TypeName(Me)
GuardClauses.GuardNullReference RHS, TypeName(Me)
Set this.Manager = RHS
End Property
Private Function TryReadPropertyValue(ByVal Instance As Object, ByVal PropertyName As String, ByRef outValue As Variant) As Boolean
On Error Resume Next
outValue = CallByName(Instance, PropertyName, VbGet)
TryReadPropertyValue = (Err.Number = 0)
On Error GoTo 0
End Function
Private Function TryWritePropertyValue(ByVal Instance As Object, ByVal PropertyName As String, ByVal Value As Variant) As Boolean
On Error Resume Next
CallByName Instance, PropertyName, VbLet, Value
TryWritePropertyValue = (Err.Number = 0)
On Error GoTo 0
End Function
Private Sub ApplyToSource()
'reads from the target and writes to the source.
'one-time and one-way binding modes do not write values to the binding source (ViewModel).
If this.Mode = OneTimeBinding Or this.Mode = OneWayBinding Then Exit Sub
Dim Target As Object
Set Target = ResolvePropertyPath(this.Target, this.TargetProperty)
Dim TargetPropertyName As String
TargetPropertyName = ResolvePropertyName(this.TargetProperty)
Dim TargetValue As Variant
If Not TryReadPropertyValue(Target, TargetPropertyName, outValue:=TargetValue) Then
Debug.Print TypeName(Me) & ":[" & ToString & "] failed to read target property value."
Exit Sub
End If
If Not this.Converter Is Nothing Then TargetValue = this.Converter.ConvertBack(TargetValue)
Validate TargetValue
Dim Source As Object
Set Source = ResolvePropertyPath(this.Source, this.SourcePropertyPath)
Dim SourcePropertyName As String
SourcePropertyName = ResolvePropertyName(this.SourcePropertyPath)
Dim CurrentValue As Variant
If Not TryReadPropertyValue(Source, SourcePropertyName, outValue:=CurrentValue) Then
Debug.Print TypeName(Me) & ":[" & ToString & "] failed to read current source property value."
Exit Sub
End If
If TargetValue <> CurrentValue Then
If Not this.ValidationErrorHandler Is Nothing Then this.ValidationErrorHandler.ClearValidationErrors SourcePropertyName
If Not TryWritePropertyValue(Source, SourcePropertyName, TargetValue) Then
Debug.Print TypeName(Me) & ":[" & ToString & "] failed to write to source property."
Exit Sub
End If
Debug.Print TypeName(Me) & ":[" & ToString & "] was successfully applied to source."
this.Manager.OnEvaluateCanExecute this.Source
End If
End Sub
Private Function ResolvePropertyPath(ByVal Source As Object, ByVal PropertyPath As String) As Object
Dim Parts As Variant
Parts = Strings.Split(PropertyPath, ".")
If UBound(Parts) = LBound(Parts) Then
Set ResolvePropertyPath = Source
Else
Dim RecursiveProperty As Object
Set RecursiveProperty = CallByName(Source, Parts(0), VbGet)
If RecursiveProperty Is Nothing Then Exit Function
Set ResolvePropertyPath = ResolvePropertyPath(RecursiveProperty, Right$(PropertyPath, Len(PropertyPath) - Len(Parts(0)) - 1))
End If
End Function
Private Function ResolvePropertyName(ByVal PropertyPath As String) As String
Dim Parts As Variant
Parts = Strings.Split(PropertyPath, ".")
ResolvePropertyName = Parts(UBound(Parts))
End Function
Private Sub Apply()
'reads from the source and writes to the target.
'one-way to source and already-applied one-time binding modes do not apply to target
If this.Mode = OneWayToSource Or (this.Mode = OneTimeBinding And this.Applied) Then Exit Sub
Dim Source As Object
Set Source = ResolvePropertyPath(this.Source, this.SourcePropertyPath)
Dim SourceValue As Variant
Dim UseFallbackDefault As Boolean
If Source Is Nothing Then
UseFallbackDefault = TryGetDefaultBindingValue(outValue:=SourceValue)
End If
If Source Is Nothing And Not UseFallbackDefault Then
Debug.Print "Cannot bind target property '" & this.TargetProperty & "' (" & TypeName(this.Target) & ": '" & this.Target.Name & "'); source object in path '" & this.SourcePropertyPath & "' is Nothing"
Exit Sub
ElseIf UseFallbackDefault Then
Debug.Print "Source object in path '" & this.SourcePropertyPath & "' is Nothing; binding target property '" & this.TargetProperty & "' to default/fallback value."
End If
Dim SourcePropertyName As String
SourcePropertyName = ResolvePropertyName(this.SourcePropertyPath)
On Error Resume Next
If Not UseFallbackDefault Then
SourceValue = CallByName(Source, SourcePropertyName, VbGet)
If Err.Number <> 0 Then
Debug.Print "Failed to apply binding for target property '" & this.TargetProperty & "' (" & TypeName(this.Target) & ": '" & this.Target.Name & "'); source path: '" & this.SourcePropertyPath & "'; " & Err.Description
On Error GoTo 0
Err.Clear
Exit Sub
End If
End If
On Error GoTo 0
Validate SourceValue
Dim Target As Object
Set Target = ResolvePropertyPath(this.Target, this.TargetProperty)
Debug.Assert Not Target Is Nothing
If Not this.Converter Is Nothing Then
SourceValue = this.Converter.Convert(SourceValue)
'TODO: handle converter errors?
End If
Dim TargetPropertyName As String
TargetPropertyName = ResolvePropertyName(this.TargetProperty)
Dim CurrentValue As Variant
CurrentValue = CallByName(Target, TargetPropertyName, VbGet)
If SourceValue <> CurrentValue Then
On Error Resume Next
CallByName Target, TargetPropertyName, VbLet, SourceValue
If Err.Number <> 0 Then
Debug.Print "Failed to apply binding for target property '" & this.TargetProperty & "' (source path: " & this.SourcePropertyPath & "): " & Err.Description
Err.Clear
Else
Debug.Print "Successfully updated binding for target property '" & this.TargetProperty & "' (source path: " & this.SourcePropertyPath & ")"
If Not this.ValidationErrorHandler Is Nothing Then this.ValidationErrorHandler.ClearValidationErrors SourcePropertyName
this.Manager.OnEvaluateCanExecute this.Source
End If
On Error GoTo 0
End If
End Sub
Private Function TryGetDefaultBindingValue(ByRef outValue As Variant) As Boolean
'Gets a default value for certain specific target properties, used when source path cannot be fully resolved,
'e.g. when target binds to "SomeObjectProperty.SomeProperty" and "SomeObjectProperty" is Nothing.
Select Case ResolvePropertyName(this.TargetProperty)
Case "Text", "Caption"
outValue = vbNullString
TryGetDefaultBindingValue = True
Case "Enabled", "Visible"
outValue = False
TryGetDefaultBindingValue = True
Case "Value"
If TypeOf this.Target Is MSForms.CheckBox _
Or TypeOf this.Target Is MSForms.OptionButton _
Then
outValue = False
TryGetDefaultBindingValue = True
End If
End Select
End Function
Private Sub Validate(ByVal TargetValue As Variant)
If this.Validator Is Nothing Then Exit Sub
If this.Validator.IsValid(TargetValue, this.Source, this.Target) Then
Debug.Print TypeName(Me) & ":[" & ToString & "] value passed validation."
If Not this.ValidationErrorFormatter Is Nothing Then
this.ValidationErrorFormatter.Restore
End If
Exit Sub
End If
Debug.Print TypeName(Me) & ":[" & ToString & "] value failed validation and will not be applied. A validation error will be propagated."
If Not this.ValidationErrorFormatter Is Nothing Then
this.ValidationErrorFormatter.Apply ResolvePropertyName(this.SourcePropertyPath), ValidationErrorMessage
End If
NotifyValidationError
'Err.Raise ValidationError, TypeName(Me), ValidationErrorMessage
End Sub
Private Property Get ValidationErrorMessage() As String
If Not this.Validator Is Nothing Then
ValidationErrorMessage = this.Validator.Message
'Else: no validator -> value is always valid -> no need for a validation error message
End If
End Property
Private Sub NotifyValidationError()
If this.ValidationErrorHandler Is Nothing Then Exit Sub
this.ValidationErrorHandler.OnValidationError Me, ValidationErrorMessage
End Sub
Private Sub NotifyPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
Dim Handler As IHandlePropertyChanged
For Each Handler In this.Handlers
Handler.OnPropertyChanged Source, PropertyName
Next
End Sub
Private Sub Class_Initialize()
If Not Me Is PropertyBinding Then Set this.Handlers = New Collection
End Sub
Private Sub IHandlePropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
If PropertyName = ResolvePropertyName(this.SourcePropertyPath) Then Apply
NotifyPropertyChanged Source, PropertyName
End Sub
Private Sub INotifyPropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
NotifyPropertyChanged Source, PropertyName
End Sub
Private Sub INotifyPropertyChanged_RegisterHandler(ByVal Handler As IHandlePropertyChanged)
this.Handlers.Add Handler
End Sub
Private Sub IPropertyBinding_Apply()
On Error GoTo ValidationFailed
Apply
Exit Sub
ValidationFailed:
Debug.Print TypeName(Me) & ": validation failed, binding was not applied."
End Sub
Private Property Get IPropertyBinding_Converter() As IValueConverter
Set IPropertyBinding_Converter = this.Converter
End Property
Private Property Get IPropertyBinding_Source() As Object
Set IPropertyBinding_Source = this.Source
End Property
Private Property Get IPropertyBinding_SourcePropertyPath() As String
IPropertyBinding_SourcePropertyPath = this.SourcePropertyPath
End Property
Private Property Get IPropertyBinding_Target() As Object
Set IPropertyBinding_Target = this.Target
End Property
Private Property Get IPropertyBinding_TargetProperty() As String
IPropertyBinding_TargetProperty = this.TargetProperty
End Property
Private Property Get IPropertyBinding_Mode() As BindingMode
IPropertyBinding_Mode = this.Mode
End Property
Private Property Get IPropertyBinding_UpdateSourceTrigger() As BindingUpdateSourceTrigger
IPropertyBinding_UpdateSourceTrigger = this.UpdateSourceTrigger
End Property
Private Sub CheckBoxEventSource_Change()
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnPropertyChanged Then ApplyToSource
Exit Sub
FailedValidation:
On Error GoTo 0
End Sub
Private Sub ComboBoxEventSource_Change()
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnPropertyChanged Then ApplyToSource
Exit Sub
FailedValidation:
On Error GoTo 0
End Sub
Private Sub ListBoxEventSource_Change()
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnPropertyChanged Then ApplyToSource
Exit Sub
FailedValidation:
On Error GoTo 0
End Sub
Private Sub OptionButtonEventSource_Change()
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnPropertyChanged Then ApplyToSource
Exit Sub
FailedValidation:
On Error GoTo 0
End Sub
Private Sub TextBoxEventSource_Change()
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnPropertyChanged Then ApplyToSource
Exit Sub
FailedValidation:
On Error GoTo 0
End Sub
Private Sub TextBoxEventSource_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnKeyPress Then ApplyToSource
Exit Sub
FailedValidation:
KeyCode.Value = 0 'swallow invalid keypress
On Error GoTo 0
End Sub
Private Sub ControlEventSource_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo FailedValidation
If this.UpdateSourceTrigger = OnExit Then ApplyToSource
Exit Sub
FailedValidation:
Cancel.Value = True 'keep target control focused
On Error GoTo 0
End Sub
Private Function ToString() As String
ToString = "source path '" & this.SourcePropertyPath & "' (" & TypeName(this.Source) & "), target property '" & this.TargetProperty & "' (" & TypeName(this.Target) & ")"
End Function
</code></pre>
<h3>Command Bindings</h3>
<p>Command bindings also have a simple interface:</p>
<p><strong>ICommandBinding</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Bindings
'@ModuleDescription "An object responsible for binding a command to a UI element."
'@Interface
'@Exposed
Option Explicit
'@Description "Gets the event source object bound to the command."
Public Property Get Target() As Object
End Property
'@Description "Gets the command bound to the event source."
Public Property Get Command() As ICommand
End Property
'@Description "Evaluates whether the command can execute given the binding context."
Public Sub EvaluateCanExecute(ByVal Context As Object)
End Sub
</code></pre>
<p>...but the implementation feels much simpler here, with 150 lines - but I'm pretty sure I'm only leveraging the simplest binding scenarios, and there should be a way to make this adhere to the <em>Open-Closed Principle</em> (OCP), such that extending it doesn't systematically involve modifying working code:</p>
<p><strong>CommandBinding</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Bindings
'@ModuleDescription "An object responsible for binding a command to a UI element."
'@PredeclaredId
'@Exposed
Implements ICommandBinding
Option Explicit
Private Type TCommandBinding
ViewModel As Object
Target As Object
Command As ICommand
End Type
Private WithEvents CommandButtonEvents As MSForms.CommandButton
Private WithEvents CheckBoxEvents As MSForms.CheckBox
Private WithEvents ImageEvents As MSForms.Image
Private WithEvents LabelEvents As MSForms.Label
Private this As TCommandBinding
'@Description "Creates and returns an ICommandBinding implementation binding the specified ICommand to the specified MSForms.CommandButton target."
Public Function ForCommandButton(ByVal Target As MSForms.CommandButton, ByVal Command As ICommand, ByVal ViewModel As Object) As ICommandBinding
GuardClauses.GuardNonDefaultInstance Me, CommandBinding
Set ForCommandButton = Create(Target, Command, ViewModel)
End Function
'@Description "Creates and returns an ICommandBinding implementation binding the specified ICommand to the specified MSForms.CheckBox target."
Public Function ForCheckBox(ByVal Target As MSForms.CheckBox, ByVal Command As ICommand, ByVal ViewModel As Object) As ICommandBinding
GuardClauses.GuardNonDefaultInstance Me, CommandBinding
Set ForCheckBox = Create(Target, Command, ViewModel)
End Function
'@Description "Creates and returns an ICommandBinding implementation binding the specified ICommand to the specified MSForms.Image target."
Public Function ForImage(ByVal Target As MSForms.Image, ByVal Command As ICommand, ByVal ViewModel As Object) As ICommandBinding
GuardClauses.GuardNonDefaultInstance Me, CommandBinding
Set ForImage = Create(Target, Command, ViewModel)
End Function
'@Description "Creates and returns an ICommandBinding implementation binding the specified ICommand to the specified MSForms.Label target."
Public Function ForLabel(ByVal Target As MSForms.Label, ByVal Command As ICommand, ByVal ViewModel As Object) As ICommandBinding
GuardClauses.GuardNonDefaultInstance Me, CommandBinding
Set ForLabel = Create(Target, Command, ViewModel)
End Function
'@Description "Creates and returns an ICommandBinding implementation binding the specified ICommand to the specified Target."
Public Function Create(ByVal Target As Object, ByVal Command As ICommand, ByVal ViewModel As Object) As ICommandBinding
GuardClauses.GuardNonDefaultInstance Me, CommandBinding
Dim result As CommandBinding
Set result = New CommandBinding
Set result.ViewModel = ViewModel
Set result.Target = Target
Set result.Command = Command
Set Create = result
End Function
Public Property Get ViewModel() As Object
Set ViewModel = this.ViewModel
End Property
Public Property Set ViewModel(ByVal RHS As Object)
Set this.ViewModel = RHS
End Property
Public Property Get Target() As Object
Set Target = this.Target
End Property
Public Property Set Target(ByVal RHS As Object)
GuardClauses.GuardDoubleInitialization this.Target, TypeName(Me)
Set this.Target = RHS
Select Case True
Case TypeOf RHS Is MSForms.CommandButton
Set CommandButtonEvents = RHS
Case TypeOf RHS Is MSForms.CheckBox
Set CheckBoxEvents = RHS
Case TypeOf RHS Is MSForms.Image
Set ImageEvents = RHS
Case TypeOf RHS Is MSForms.Label
Set LabelEvents = RHS
Case Else
GuardClauses.GuardExpression _
Throw:=True, _
Source:=TypeName(Me), _
Message:="Type '" & TypeName(RHS) & "' does not support command bindings at the moment."
End Select
End Property
Public Property Get Command() As ICommand
Set Command = this.Command
End Property
Public Property Set Command(ByVal RHS As ICommand)
Set this.Command = RHS
If Not RHS Is Nothing And Not this.Target Is Nothing Then
this.Target.ControlTipText = RHS.Description
End If
End Property
Private Property Get AsInterface() As ICommandBinding
Set AsInterface = Me
End Property
Private Sub OnExecute()
If Not this.Command Is Nothing Then
this.Command.Execute this.ViewModel
Else
Debug.Print "BUG in " & TypeName(Me) & ": Command is 'Nothing', cannot execute."
Debug.Assert False ' should not happen, break here if it does.
End If
End Sub
Private Property Get ICommandBinding_Target() As Object
Set ICommandBinding_Target = this.Target
End Property
Private Property Get ICommandBinding_Command() As ICommand
Set ICommandBinding_Command = this.Command
End Property
Private Sub ICommandBinding_EvaluateCanExecute(ByVal Context As Object)
EvaluateCanExecute Context
End Sub
Private Sub EvaluateCanExecute(ByVal Source As Object)
If this.Target Is Nothing Then Exit Sub
If this.Command Is Nothing Then
this.Target.Enabled = False
Else
this.Target.Enabled = this.Command.CanExecute(Source)
End If
End Sub
Private Sub CheckBoxEvents_Click()
GuardClauses.GuardExpression Not TypeOf this.Target Is MSForms.CheckBox, TypeName(Me)
OnExecute
End Sub
Private Sub CommandButtonEvents_Click()
GuardClauses.GuardExpression Not TypeOf this.Target Is MSForms.CommandButton, TypeName(Me)
OnExecute
End Sub
Private Sub ImageEvents_Click()
GuardClauses.GuardExpression Not TypeOf this.Target Is MSForms.Image, TypeName(Me)
OnExecute
End Sub
Private Sub LabelEvents_Click()
GuardClauses.GuardExpression Not TypeOf this.Target Is MSForms.Label, TypeName(Me)
OnExecute
End Sub
</code></pre>
<h3>Binding Manager</h3>
<p>The <code>BindingManager</code> helper class is how the View can configure the bindings in the code-behind - I gave up trying to find something better than "manager" for a name:</p>
<p><strong>BindingManager</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Bindings
'@ModuleDescription "Implements helper methods for the View to consume."
'@PredeclaredId
'@Exposed
Option Explicit
Implements IBindingManager
Implements IHandlePropertyChanged
Private Type TState
Handlers As Collection
CommandBindings As Collection
PropertyBindings As Collection
End Type
Private this As TState
Public Function Create() As IBindingManager
GuardClauses.GuardNonDefaultInstance Me, BindingManager
Set Create = New BindingManager
End Function
Private Property Get IsDefaultInstance() As Boolean
IsDefaultInstance = Me Is BindingManager
End Property
Private Sub ApplyBindings(ByVal Source As Object)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me), "Member call is invalid against stateless default instance."
Dim Binding As IPropertyBinding
For Each Binding In this.PropertyBindings
Binding.Apply
Next
OnEvaluateCanExecute Source
End Sub
Private Sub OnEvaluateCanExecute(ByVal Source As Object)
Dim Binding As ICommandBinding
For Each Binding In this.CommandBindings
Binding.EvaluateCanExecute Source
Next
End Sub
Private Sub Class_Initialize()
If Not IsDefaultInstance Then
Set this.Handlers = New Collection
Set this.CommandBindings = New Collection
Set this.PropertyBindings = New Collection
End If
End Sub
Private Sub IBindingManager_BindPropertyPath(ByVal Source As Object, ByVal PropertyPath As String, ByVal Target As Object, _
Optional ByVal TargetProperty As String, _
Optional ByVal Mode As BindingMode, _
Optional ByVal Validator As IValueValidator, _
Optional ByVal Converter As IValueConverter, _
Optional ByVal ErrorFormat As IValidationErrorFormatter)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me), "Member call is invalid against stateless default instance."
Dim Binding As IPropertyBinding
Select Case True
Case TypeOf Target Is MSForms.CheckBox And (TargetProperty = "Value" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForCheckBox(Me, Target, Source, PropertyPath, Converter:=Converter, ErrorFormat:=ErrorFormat)
Case TypeOf Target Is MSForms.ComboBox And (TargetProperty = "Value" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForComboBoxValue(Me, Target, Source, PropertyPath, Converter:=Converter, ErrorFormat:=ErrorFormat)
Case TypeOf Target Is MSForms.Frame And (TargetProperty = "Caption" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForFrame(Me, Target, Source, PropertyPath, Converter:=Converter, ErrorFormat:=ErrorFormat)
Case TypeOf Target Is MSForms.Label And (TargetProperty = "Caption" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForLabel(Me, Target, Source, PropertyPath, Converter:=Converter, ErrorFormat:=ErrorFormat)
Case TypeOf Target Is MSForms.ListBox And TargetProperty = "List"
Set Binding = PropertyBinding.Create(Me, Target, TargetProperty, Source, PropertyPath, Validator:=Validator, Converter:=Converter)
Case TypeOf Target Is MSForms.ListBox And (TargetProperty = "Value" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForListBoxValue(Me, Target, Source, PropertyPath, Converter:=Converter)
Case TypeOf Target Is MSForms.OptionButton And (TargetProperty = "Value" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForOptionButton(Me, Target, Source, PropertyPath, Converter:=Converter, ErrorFormat:=ErrorFormat)
Case TypeOf Target Is MSForms.TextBox And (TargetProperty = "Text" Or TargetProperty = vbNullString)
Set Binding = PropertyBinding.ForTextBox(Me, Target, Source, PropertyPath, Validator:=Validator, Converter:=Converter, ErrorFormat:=ErrorFormat)
Case Else
Set Binding = PropertyBinding.Create(Me, Target, TargetProperty, Source, PropertyPath, Mode, OnPropertyChanged, Validator, Converter, ErrorFormat)
End Select
this.PropertyBindings.Add Binding
this.Handlers.Add Binding
If TargetProperty = vbNullString Then
Debug.Print TypeName(Source) & ": Binding property path '" & PropertyPath & "' to the default-binding property of " & TypeName(Target) & " object '" & Target.Name & "'."
Else
Debug.Print TypeName(Source) & ": Binding property path '" & PropertyPath & "' to " & TypeName(Target) & " object '" & Target.Name & "' property '" & TargetProperty & "'."
End If
End Sub
Private Sub IBindingManager_BindCommand(ByVal Source As Object, ByVal Target As Object, ByVal Command As ICommand)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me), "Member call is invalid against stateless default instance."
Dim Binding As ICommandBinding
Select Case True
Case TypeOf Target Is MSForms.CommandButton
Set Binding = CommandBinding.ForCommandButton(Target, Command, Source)
Case TypeOf Target Is MSForms.Image
Set Binding = CommandBinding.ForImage(Target, Command, Source)
Case TypeOf Target Is MSForms.Label
Set Binding = CommandBinding.ForLabel(Target, Command, Source)
Case TypeOf Target Is MSForms.CheckBox
Set Binding = CommandBinding.ForCheckBox(Target, Command, Source)
Case Else
GuardClauses.GuardExpression True, TypeName(Source), "Target type '" & TypeName(Target) & "' does not currently support command bindings."
End Select
this.CommandBindings.Add Binding
Debug.Print TypeName(Source) & ": Binding command '" & TypeName(Command) & "' to " & TypeName(Target) & " object '" & Target.Name & "'."
End Sub
Private Sub IBindingManager_ApplyBindings(ByVal Source As Object)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me), "Member call is invalid against stateless default instance."
ApplyBindings Source
End Sub
Private Sub IBindingManager_OnEvaluateCanExecute(ByVal Source As Object)
GuardClauses.GuardExpression IsDefaultInstance, TypeName(Me), "Member call is invalid against stateless default instance."
OnEvaluateCanExecute Source
End Sub
Private Sub IHandlePropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
OnEvaluateCanExecute Source
End Sub
</code></pre>
<p>There are other components, with <em>data validation</em> being a nicely handled concern that I'll save for another post. The pillar interfaces are <code>IView</code>, <code>IViewModel</code>, <code>ICommand</code>, but user code ViewModels also need to implement <code>INotifyPropertyChanged</code>:</p>
<p><strong>INotifyPropertyChanged</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Bindings
'@ModuleDescription "An object that can notify registered handlers when a property value changes."
'@Interface
'@Exposed
Option Explicit
'@Description "Registers the specified handler."
Public Sub RegisterHandler(ByVal Handler As IHandlePropertyChanged)
End Sub
'@Description "Notifies all registered handlers of a property value change."
Public Sub OnPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
End Sub
</code></pre>
<p>User code ViewModels also need to implement the <code>IViewModel</code> interface, which is almost a marker interface, except it's a cornerstone of the data validation functionality:</p>
<p><strong>IViewModel</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Exposed
'@Folder MVVM.Infrastructure
'@ModuleDescription "Formalizes the basic functionality of a ViewModel."
'@Interface
Option Explicit
'@Description "Gets the validation error handler for this ViewModel."
Public Property Get Validation() As IHandleValidationError
End Property
</code></pre>
<p>The API comes with <code>AcceptCommand</code> and <code>CancelCommand</code> convenient implementations of <code>ICommand</code> that can easily be command-bound to a <code>CommandButton</code> control:</p>
<p><strong>CancelCommand</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Infrastructure.Commands
'@ModuleDescription "A command that closes (hides) a cancellable View in a cancelled state."
'@PredeclaredId
'@Exposed
Option Explicit
Implements ICommand
Private Type TState
View As ICancellable
End Type
Private this As TState
'@Description "Creates a new instance of this command."
Public Function Create(ByVal View As ICancellable) As ICommand
Dim result As CancelCommand
Set result = New CancelCommand
Set result.View = View
Set Create = result
End Function
Public Property Get View() As ICancellable
Set View = this.View
End Property
Public Property Set View(ByVal RHS As ICancellable)
GuardClauses.GuardDoubleInitialization this.View, TypeName(Me)
Set this.View = RHS
End Property
Private Function ICommand_CanExecute(ByVal Context As Object) As Boolean
ICommand_CanExecute = True
End Function
Private Property Get ICommand_Description() As String
ICommand_Description = "Cancel pending changes and close."
End Property
Private Sub ICommand_Execute(ByVal Context As Object)
this.View.OnCancel
End Sub
</code></pre>
<p>User code needs to implement their own commands, and I'm hoping the API is simple enough to work with. The user code ViewModel might look like this:</p>
<p><strong>ExampleViewModel</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder MVVM.Example
'@ModuleDescription "An example ViewModel implementation for some dialog."
'@PredeclaredId
Implements IViewModel
Implements INotifyPropertyChanged
Option Explicit
Public Event PropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
Private Type TViewModel
'INotifyPropertyChanged state:
Handlers As Collection
'CommandBindings:
SomeCommand As ICommand
'Read/Write PropertyBindings:
SourcePath As String
SomeOption As Boolean
SomeOtherOption As Boolean
End Type
Private this As TViewModel
Private WithEvents ValidationHandler As ValidationManager
Public Function Create() As IViewModel
GuardClauses.GuardNonDefaultInstance Me, ExampleViewModel, TypeName(Me)
Dim result As ExampleViewModel
Set result = New ExampleViewModel
Set Create = result
End Function
Public Property Get Validation() As IHandleValidationError
Set Validation = ValidationHandler
End Property
Public Property Get SourcePath() As String
SourcePath = this.SourcePath
End Property
Public Property Let SourcePath(ByVal RHS As String)
If this.SourcePath <> RHS Then
this.SourcePath = RHS
OnPropertyChanged "SourcePath"
End If
End Property
Public Property Get SomeOption() As Boolean
SomeOption = this.SomeOption
End Property
Public Property Let SomeOption(ByVal RHS As Boolean)
If this.SomeOption <> RHS Then
this.SomeOption = RHS
OnPropertyChanged "SomeOption"
End If
End Property
Public Property Get SomeOtherOption() As Boolean
SomeOtherOption = this.SomeOtherOption
End Property
Public Property Let SomeOtherOption(ByVal RHS As Boolean)
If this.SomeOtherOption <> RHS Then
this.SomeOtherOption = RHS
OnPropertyChanged "SomeOtherOption"
End If
End Property
Public Property Get SomeCommand() As ICommand
Set SomeCommand = this.SomeCommand
End Property
Public Property Set SomeCommand(ByVal RHS As ICommand)
Set this.SomeCommand = RHS
End Property
Public Property Get SomeOptionName() As String
SomeOptionName = "Auto"
End Property
Public Property Get SomeOtherOptionName() As String
SomeOtherOptionName = "Manual/Browse"
End Property
Public Property Get Instructions() As String
Instructions = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
End Property
Private Sub OnPropertyChanged(ByVal PropertyName As String)
RaiseEvent PropertyChanged(Me, PropertyName)
Dim Handler As IHandlePropertyChanged
For Each Handler In this.Handlers
Handler.OnPropertyChanged Me, PropertyName
Next
End Sub
Private Sub Class_Initialize()
Set this.Handlers = New Collection
Set ValidationHandler = ValidationManager.Create
End Sub
Private Sub INotifyPropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
OnPropertyChanged PropertyName
End Sub
Private Sub INotifyPropertyChanged_RegisterHandler(ByVal Handler As IHandlePropertyChanged)
this.Handlers.Add Handler
End Sub
Private Property Get IViewModel_Validation() As IHandleValidationError
Set IViewModel_Validation = ValidationHandler
End Property
Private Sub ValidationHandler_PropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
OnPropertyChanged PropertyName
End Sub
</code></pre>
<p>Obviously MVVM is a (very) steep departure from <em>Smart UI</em> or even <em>Model-View-Presenter</em>, so I'm looking for the simplest possible constraints on user code, without sacrificing too much flexibility and of course all while making it as easy to extend as possible.</p>
<p>All feedback welcome, from minor nitpicks to refactoring & enhancement ideas in any area!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T21:27:27.037",
"Id": "488658",
"Score": "0",
"body": "This code has been [uploaded to GitHub](https://github.com/rubberduck-vba/examples/tree/master/MVVM)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T12:29:35.427",
"Id": "488712",
"Score": "1",
"body": "Man...this is good stuff!! I will likely post a review as soon as I get some free time, but 2 things stand out to me. \n\n1.`PropertyBinding ` indeed smells, and I do believe that it should be split it into separate classes. You could utilize composition by creating an interface called `IPropertyBindingBase`, with a concrete implementation of `PropertyBindingBase` that holds all common functionality. Then have implementations like `I<ControlType>PropertyBinding`, each of which would be injected with an instance of the base class. \n\n(See next comment for #2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T12:38:15.493",
"Id": "488713",
"Score": "2",
"body": "As for your , `<Something>Manager` naming dilemma, you could try using `<Something>Coordinator` as an alternative. It would at least get you away from using the ever ambiguous `Manager` naming convention...then again, is does if used too frequently or as a filler name, then you would right back in the same situation. Naming is hard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T13:27:37.013",
"Id": "488721",
"Score": "0",
"body": "Ah, re-reading the code I just picked up that `ApplyToSource` is using the extracted `TryRead` and `TryWrite` helper functions, but `Apply` was left behind and still uses inline error-handling - that's a low-hanging fruit right there, `Apply` can easily get a bit cleaner by leveraging these functions."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T17:39:11.800",
"Id": "249318",
"Score": "11",
"Tags": [
"object-oriented",
"vba",
"library",
"mvvm",
"rubberduck"
],
"Title": "Host-Agnostic Model-View-ViewModel Infrastructure"
}
|
249318
|
<p>I have an image toggle triggered by button clicks and checkboxes. My code is currently working how I need it to, but I'm very new to JavaScript so I'm sure there is a cleaner way to do this.</p>
<p>The desired functionality is this: There are three images that need to toggle, a before image, after image, and a combo image. There are two ways to toggle the images. One is a toggle button, that toggles between the before and after images. I've used a checkbox for this. The other button has an onclick that changes the image to the combo image, hides the checkbox and shows a 'toggle view' button that when clicked, switches back to the toggle mode. (Hopefully all of that makes sense..)</p>
<p>A few notes:</p>
<p>This is for a client, so for confidentiality reasons, I cannot share the actual images, but the alt tags should tell the story.</p>
<p>I'm not allowed to use anything other than vanilla JS on the platform this will live, and all variables and functions have to have custom names, hence the funky naming.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var csDMU_checkbox = document.getElementById("csDMU_checkbox");
var csDMU_imageBefore = document.getElementById("before-image");
var csDMU_imageAfter = document.getElementById("after-image");
var csDMU_imageCombo = document.getElementById("combo-image");
var csDMU_switch = document.getElementById("switch");
var csDMU_toggle = document.getElementById("toggle");
function csDMU_toggleImage() {
if (csDMU_checkbox.checked == true) {
csDMU_imageBefore.style.display = "none";
csDMU_imageAfter.style.display = "block";
csDMU_imageCombo.style.display = "none";
} else {
csDMU_imageBefore.style.display = "block";
csDMU_imageAfter.style.display = "none";
csDMU_imageCombo.style.display = "none";
}
}
function csDMU_comboView() {
csDMU_imageCombo.style.display = "block";
csDMU_imageBefore.style.display = "none";
csDMU_imageAfter.style.display = "none";
csDMU_switch.style.display = "none";
csDMU_toggle.style.display = "block";
}
function csDMU_toggleView() {
csDMU_switch.style.display = "block";
csDMU_toggle.style.display = "none";
csDMU_imageBefore.style.display = "block";
csDMU_imageCombo.style.display = "none";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:ital,wght@0,400;0,700;1,400;1,700&display=swap');
body {
font-family: 'Libre Franklin', sans-serif;
}
.flexRow {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 119px;
height: 40px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #243b43;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 32px;
width: 33px;
right: 4px;
bottom: 3px;
background: transparent -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), color-stop(47%, #EDEDED), color-stop(73%, #D0D0D0), to(#E5E5E5)) 0% 0% no-repeat padding-box;
background: transparent linear-gradient(180deg, #FFFFFF 0%, #EDEDED 47%, #D0D0D0 73%, #E5E5E5 100%) 0% 0% no-repeat padding-box;
-webkit-box-shadow: 0px 3px 6px #00000029;
box-shadow: 0px 3px 6px #00000029;
border: 1px solid #FFFFFF;
-webkit-transition: .4s;
transition: .4s;
}
.slider:after {
content: "BEFORE";
display: block;
font-size: 14px;
line-height: 14px;
letter-spacing: 0.16px;
font-weight: bold;
color: #FFF;
position: relative;
top: 13px;
left: 10px;
}
input:checked + .slider {
background-color: #F26322;
}
input:focus + .slider {
-webkit-box-shadow: 0 0 1px #2196F3;
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(-75px);
transform: translateX(-75px);
}
input:checked + .slider:after {
content:'AFTER';
left: 50px;
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.combo-button,
.toggle-button{
width: 172px;
height: 40px;
margin-left: 20px;
border-radius: 100px;
border: 1px solid #C4C4C4;
color: #4a4b4d;
letter-spacing: 0.16px;
}
.combo-button:hover,
.combo-button:focus {
background-color: #002D5E;
color: #FFF;
}
.combo-button:focus {
outline: 0;
}
.toggle-button {
display: none;
width: 119px;
margin: 0;
}
.hand-img {
max-width: 700px;
margin-right: -20px;
display: block;
}
#after-image,
#combo-image {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div id="image-change">
<img src="" alt="before image" class="hand-img" id="before-image" />
<img src="" alt="after image" class="hand-img" id="after-image" />
<img src="" alt="combo image" class="hand-img" id="combo-image" />
</div>
<div class="flexRow">
<label class="switch" id="switch">
<input type="checkbox" id="csDMU_checkbox" onclick="csDMU_toggleImage()">
<span class="slider round"></span>
</label>
<button class="toggle-button" id="toggle" onclick="csDMU_toggleView()">TOGGLE VIEW</button>
<button class="combo-button" onclick="csDMU_comboView()">COMPARISON</button>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Well you could minimize your JS code by first selecting all the elements using one line selector, note that you need to write the selected elements in their order in HTML to get them right because we're destructuring the returned node list into variables so the order matters because it's an array and not an object, then you are writing repeatedly <code>element.style.display = "some value"</code> so you can write a function to do that using an array of elements as input and their display value to set as two arrays and just loop over the first array of the elements and assign the correct CSS display value according to the index, and use a ternary expression instead of If-Else statement to write less and clean code, here is the full JS code</p>\n<pre class=\"lang-js prettyprint-override\"><code>let [csDMU_imageBefore, csDMU_imageAfter, csDMU_imageCombo, csDMU_switch, csDMU_checkbox, csDMU_toggle] = document.querySelectorAll("#before-image, #after-image, #combo-image, #switch, #csDMU_checkbox, #toggle");\n\nconst setCssDisplay = (elements, values) => elements.forEach((element, index) => element.style.display = values[index]);\n\nfunction csDMU_toggleImage() {\n setCssDisplay([csDMU_imageBefore, csDMU_imageAfter, csDMU_imageCombo], csDMU_checkbox.checked ? ["none", "block", "none"] : ["block", "none", "none"]);\n}\n\nfunction csDMU_comboView() {\n setCssDisplay([csDMU_imageCombo, csDMU_imageBefore, csDMU_imageAfter, csDMU_switch, csDMU_toggle], ["block", "none", "none", "none", "block"]);\n}\n\nfunction csDMU_toggleView() {\n setCssDisplay([csDMU_switch, csDMU_toggle, csDMU_imageBefore, csDMU_imageCombo], ["block", "none", "block", "none"]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:00:47.030",
"Id": "488651",
"Score": "0",
"body": "this makes sense, thank you!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T17:56:55.483",
"Id": "249320",
"ParentId": "249319",
"Score": "1"
}
},
{
"body": "<p>Inline handlers have <a href=\"https://stackoverflow.com/a/59539045\">a multitude of problems</a>, including a crazy scope chain and string escaping issues. Nowadays, there arguably isn't really any good reason to use them - better to leave the HTML code to be the <em>content itself</em>, and apply the required functionality and presentation elsewhere, ideally in a self-contained script. That is, rather than</p>\n<pre><code><input type="checkbox" id="csDMU_checkbox" onclick="csDMU_toggleImage()">\n</code></pre>\n<p>you can do</p>\n<pre><code>document.querySelector('#csDMU_checkbox').addEventListener('click', csDMU_toggleImage);\n</code></pre>\n<hr />\n<p>Another thing to consider is - is there any chance of the page ever getting expanded to include more elements, perhaps another before-after pair or few? If so, you will run into problems due to your IDs. (Every element with an ID must be unique in a document, or the HTML will be invalid.) IDs are probably best reserved for elements which will <em>absolutely</em> always be completely unique in a document. Another problem with IDs is that every element with an ID unfortunately <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">becomes a global variable</a>, which can result in bugs and hard-to-understand behavior (I've seen this happen many times on Stack Overflow questions).</p>\n<p>I'd consider using just classes instead, by default.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:09:12.360",
"Id": "488652",
"Score": "0",
"body": "Thank you! I will change the onclick to be an event listener. This particular page won't be expanded in the future, its for a 6-month campaign that runs once and then has to be taken down. But if it's best practice to use classes instead, I will change to just using classes, that makes sense. Thank you for your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T19:45:53.953",
"Id": "249323",
"ParentId": "249319",
"Score": "3"
}
},
{
"body": "<p>we can use <code>class</code> instead of using <code>inline style</code> for show/hide elements.</p>\n<p>Added a <code>show</code> class for the first/init image.</p>\n<pre class=\"lang-html prettyprint-override\"><code><div id="image-change">\n <img src="https://via.placeholder.com/150" alt="before image" class="hand-img show" id="before-image" />\n <img src="https://via.placeholder.com/151" alt="after image" class="hand-img" id="after-image" />\n <img src="https://via.placeholder.com/152" alt="combo image" class="hand-img" id="combo-image" />\n</div>\n<div class="flexRow">\n <label class="switch" id="switch">\n <input type="checkbox" id="csDMU_checkbox" onclick="csDMU_toggleImage()">\n <span class="slider round"></span>\n </label>\n <button class="toggle-button" id="toggle" onclick="csDMU_toggleView()">TOGGLE VIEW</button>\n <button class="combo-button" onclick="csDMU_comboView()">COMPARISON</button>\n</div>\n</code></pre>\n<p>Hide all images by default except who has a <code>show</code> class:</p>\n<pre class=\"lang-css prettyprint-override\"><code>@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:ital,wght@0,400;0,700;1,400;1,700&display=swap');\n\nbody {\n font-family: 'Libre Franklin', sans-serif;\n}\n.flexRow {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n}\n\n/* The switch - the box around the slider */\n.switch {\n position: relative;\n display: inline-block;\n width: 119px;\n height: 40px;\n}\n\n/* Hide default HTML checkbox */\n.switch input {\n opacity: 0;\n width: 0;\n height: 0;\n}\n\n/* The slider */\n.slider {\n position: absolute;\n cursor: pointer;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #243b43;\n -webkit-transition: .4s;\n transition: .4s;\n}\n\n.slider:before {\n position: absolute;\n content: "";\n height: 32px;\n width: 33px;\n right: 4px;\n bottom: 3px;\n background: transparent -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), color-stop(47%, #EDEDED), color-stop(73%, #D0D0D0), to(#E5E5E5)) 0% 0% no-repeat padding-box;\n background: transparent linear-gradient(180deg, #FFFFFF 0%, #EDEDED 47%, #D0D0D0 73%, #E5E5E5 100%) 0% 0% no-repeat padding-box;\n -webkit-box-shadow: 0px 3px 6px #00000029;\n box-shadow: 0px 3px 6px #00000029;\n border: 1px solid #FFFFFF;\n -webkit-transition: .4s;\n transition: .4s;\n}\n.slider:after {\n content: "BEFORE";\n display: block;\n font-size: 14px;\n line-height: 14px;\n letter-spacing: 0.16px;\n font-weight: bold;\n color: #FFF;\n position: relative;\n top: 13px;\n left: 10px;\n}\n\ninput:checked + .slider {\n background-color: #F26322;\n}\n\ninput:focus + .slider {\n -webkit-box-shadow: 0 0 1px #2196F3;\n box-shadow: 0 0 1px #2196F3;\n}\n\ninput:checked + .slider:before {\n -webkit-transform: translateX(-75px);\n transform: translateX(-75px);\n}\ninput:checked + .slider:after { \n content:'AFTER';\n left: 50px;\n}\n/* Rounded sliders */\n.slider.round {\n border-radius: 34px;\n}\n\n.slider.round:before {\n border-radius: 50%;\n}\n.combo-button,\n.toggle-button{\n width: 172px;\n height: 40px;\n margin-left: 20px;\n border-radius: 100px;\n border: 1px solid #C4C4C4;\n color: #4a4b4d;\n letter-spacing: 0.16px;\n}\n.combo-button:hover,\n.combo-button:focus {\n background-color: #002D5E;\n color: #FFF;\n}\n.combo-button:focus {\n outline: 0;\n}\n.toggle-button {\n display: none;\n width: 119px;\n margin: 0;\n}\n.hand-img {\n max-width: 700px;\n margin-right: -20px;\n display: block;\n}\n#after-image,\n#before-image,\n#combo-image {\n display: none;\n}\n.show {\n display: block !important\n}\n</code></pre>\n<p>and this is the JS:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const _ = el => {\n return document.querySelector(el);\n}\n\nconst csDMU_checkbox = _("#csDMU_checkbox"),\n csDMU_imageBefore = _("#before-image"),\n csDMU_imageAfter = _("#after-image"),\n csDMU_imageCombo = _("#combo-image"),\n csDMU_switch = _("#switch"),\n csDMU_toggle = _("#toggle"),\n image_change = document.querySelectorAll('#image-change img');\n\n\nconst hideAllImages = () => {\n image_change.forEach(item => item.classList.remove('show'))\n}\nconst toggleButtons = el => {\n [csDMU_switch, csDMU_toggle].forEach(item => item.style.display = "none");\n el.style.display = "block";\n}\n\nconst csDMU_toggleImage = () => {\n hideAllImages()\n const imageToShow = csDMU_checkbox.checked ? csDMU_imageAfter : csDMU_imageBefore;\n imageToShow.classList.toggle("show");\n}\n\nconst csDMU_comboView = () => {\n hideAllImages()\n csDMU_imageCombo.classList.toggle("show");\n toggleButtons(csDMU_toggle);\n}\n \nconst csDMU_toggleView = () => {\n csDMU_toggleImage();\n toggleButtons(csDMU_switch);\n}\n</code></pre>\n<p>This is a demo on CodePen <a href=\"https://codepen.io/moamen/pen/yLOqQWp\" rel=\"nofollow noreferrer\">https://codepen.io/moamen/pen/yLOqQWp</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:29:36.167",
"Id": "488979",
"Score": "0",
"body": "oh that is so much cleaner! thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T13:26:39.363",
"Id": "488991",
"Score": "0",
"body": "I'm unfamiliar with some of the syntax you're using (im a newbie). can you explain what the underscores do? In this:\n`const _ = el => {\n return document.querySelector(el);\n}`\nand below that, when setting the variables"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T15:09:21.613",
"Id": "489002",
"Score": "0",
"body": "@katiebry I use this function to select elements, so I can select an element by `_(element)` instead of type `document.querySelector(element)`, just a shortcut."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T12:02:48.117",
"Id": "249434",
"ParentId": "249319",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T17:42:52.000",
"Id": "249319",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Image toggle with checkbox and onclick"
}
|
249319
|
<p>On StackOverflow I have asked a <a href="https://stackoverflow.com/questions/63874453/keep-reading-user-keyboard-input-if-available-while-echoing-back-the-latest-ava/">question</a> a few minutes ago, but then by trying a bit more, I found the answer myself, and I'm posting the resulting working code here for review.</p>
<p>What the code does, is waiting for, and repeatedly prompting the user to enter a character; when the user enters one, the program echoes it back and goes back to the previous mode, waiting for further input. The program assumes an initial implicit input of <code>'A'</code>.</p>
<pre class="lang-hs prettyprint-override"><code>{-# language LambdaCase #-}
import Control.Concurrent
import Data.Maybe
import System.IO
main :: IO ()
main = do
hSetBuffering stdin NoBuffering
future_input <- newEmptyMVar
work future_input 'l'
work :: MVar Char -> Char -> IO ()
work future_input latest_input = do
forkIO $ putMVar future_input =<< getChar
wait future_input latest_input
where
wait :: MVar Char -> Char -> IO ()
wait future_input latest_input =
tryTakeMVar future_input >>=
\case Just input -> putStrLn ("new input " ++ return input)
>> work future_input input
Nothing -> putStrLn ("old input " ++ return latest_input)
>> threadDelay 100000
>> wait future_input latest_input
</code></pre>
<p>Some thoughts on about the code:</p>
<ul>
<li>I've tried to use applicative/monadic style wherever I could, without compromising readability too much;</li>
<li>as regards the concurrentcy-handling part, basically the <code>wait</code> function, I preferred using the <code>do</code> sugar because I could hardly get something working this way.</li>
</ul>
|
[] |
[
{
"body": "<p>With a bit of suggestion/help on Haskell's IRC channels, I came up with this, which doesn't <code>forkIO</code> at every recursion.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>{-# language LambdaCase #-}\n\nimport Control.Concurrent\nimport Data.Maybe\nimport System.IO\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin NoBuffering\n future_input <- newEmptyMVar\n forkIO $ pollInput future_input\n processInput future_input 'l'\n\npollInput :: MVar Char -> IO ()\npollInput future_input = (putMVar future_input =<< getChar) >> pollInput future_input\n\nprocessInput :: MVar Char -> Char -> IO ()\nprocessInput future_input latest_input = tryTakeMVar future_input >>=\n \\case Just input -> putStrLn ("direction change " ++ return input)\n >> processInput future_input input\n Nothing -> putStrLn ("keep direction " ++ return latest_input)\n >> threadDelay 100000\n >> processInput future_input latest_input\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T18:10:33.600",
"Id": "249404",
"ParentId": "249322",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T19:36:00.370",
"Id": "249322",
"Score": "2",
"Tags": [
"multithreading",
"haskell",
"functional-programming",
"concurrency"
],
"Title": "Keep reading user keyboard input if available, while echoing back the latest available"
}
|
249322
|
<p>I've been learning programming own my for a couple of years mainly using python, and
I've created a tetris-like command line game using Python's Curses library.
The game seems to function as intended; but I lack experience writing object oriented code.
So, I would like feedback about the code's structure, and assuming the structure is ok, the code's style.</p>
<pre><code>from copy import deepcopy
import time
import curses
import random
class TetrisPiece:
def __init__(self, indices, center_of_rotation, color):
self.indices = indices
self.center_of_rotation = center_of_rotation
self.last_move_overlap = False
self.color = color
class TetrisBoard:
def __init__(self, num_rows, num_columns):
self.num_rows = num_rows
self.num_columns = num_columns
self.array = [[0] * self.num_columns for _ in range(self.num_rows)]
self.active_piece = None
def in_bounds(self, temp_active_piece_indices):
return all(0 <= i < self.num_rows and 0 <= j < self.num_columns
for i, j in temp_active_piece_indices)
def no_overlap(self, temp_active_piece_indices):
return all(self.array[i][j] == 0 for i, j in
set(temp_active_piece_indices) - set(self.active_piece.indices))
def add_piece(self, piece):
# try to place Piece near top center of board
new_active_piece_indices = [(i, j + int(self.num_columns / 2) - 1)
for i, j in piece.indices]
if all(self.array[i][j] == 0 for i, j in new_active_piece_indices):
self.active_piece = piece
self.update_array(new_active_piece_indices)
piece.indices = new_active_piece_indices
piece.center_of_rotation[1] += int(self.num_columns / 2) - 1
piece.last_move_overlap = False
else:
piece.last_move_overlap = True
def rotate_active_piece(self):
# rotates active piece indices 90 degrees counter clockwise about it's
# center of a rotation
x, y = self.active_piece.center_of_rotation
# this translates the active piece so that it's center is
# the origin, then rotates each point in indices about the origin,
# then translates the piece so that it's center is at it's
# original position
temp_active_piece_indices = [(int(-j + y + x), int(i - x + y))
for i, j in self.active_piece.indices]
if (self.in_bounds(temp_active_piece_indices)
and self.no_overlap(temp_active_piece_indices)):
self.update_array(temp_active_piece_indices)
self.active_piece.indices = temp_active_piece_indices
def translate_active_piece(self, direction):
if direction == 'right':
x, y = 0, 1
elif direction == 'left':
x, y = 0, -1
elif direction == 'down':
x, y = 1, 0
temp_active_piece_indices = [(i + x, j + y)
for i, j in self.active_piece.indices]
if (self.in_bounds(temp_active_piece_indices)
and self.no_overlap(temp_active_piece_indices)):
self.update_array(temp_active_piece_indices)
self.active_piece.indices = temp_active_piece_indices
self.active_piece.center_of_rotation[0] += x
self.active_piece.center_of_rotation[1] += y
self.active_piece.last_move_overlap = False
elif (self.in_bounds(temp_active_piece_indices)
and not self.no_overlap(temp_active_piece_indices)):
self.active_piece.last_move_overlap = True
# this is necessary to tell when a piece hits the bottom of the
# board
elif not self.in_bounds(temp_active_piece_indices) and direction == 'down':
self.active_piece.last_move_overlap = True
def update_array(self, new_indices):
for i, j in self.active_piece.indices:
self.array[i][j] = 0
for i, j in new_indices:
self.array[i][j] = self.active_piece.color
class CursesWindow:
def __init__(self, game):
self.game = game
self.window = None
def update(self):
pass
def refresh(self):
self.window.refresh()
def addstr(self, y, x, string):
self.window.addstr(y, x, string)
class BoardWindow(CursesWindow):
def __init__(self, game):
CursesWindow.__init__(self, game)
# the window's border adds two extra rows and two extra columns
self.num_rows = game.board.num_rows + 2
self.num_columns = game.board.num_columns + 2
self.window = curses.newwin(
self.num_rows,
self.num_columns
)
self.window.border('*', '*', '*', '*', '*', '*', '*', '*')
self.update()
def update(self):
# only update the interior of the window
for i in range(self.num_rows - 2):
for j in range(self.num_columns - 2):
if self.game.board.array[i][j] != 0:
self.window.addstr(
i + 1,
j + 1,
'1',
curses.color_pair(self.game.board.array[i][j])
)
else:
self.window.addstr(i + 1, j + 1, '.')
self.window.refresh()
def keypad(self, flag):
self.window.keypad(flag)
def nodelay(self, flag):
self.window.nodelay(flag)
def getch(self):
return self.window.getch()
class ScoreWindow(CursesWindow):
def __init__(self, game, board_window):
CursesWindow.__init__(self, game)
self.num_items_to_display = 3
# the window's border adds two extra rows
self.num_rows = self.num_items_to_display + 2
# 6 digits for the string 'score:' + max_num_score_digits + 2 for border
self.num_columns = 6 + game.max_num_score_digits + 2
self.window = curses.newwin(
self.num_rows,
self.num_columns,
0,
board_window.num_columns + 1
)
self.update()
def update(self):
self.window.erase()
self.window.border('*', '*', '*', '*', '*', '*', '*', '*')
self.window.addstr(1, 1, f'Score:{self.game.score}')
self.window.addstr(2, 1, f'Lines:{self.game.lines_completed}')
self.window.addstr(3, 1, f'Level:{self.game.level}')
self.window.refresh()
class PiecePreviewWindow(CursesWindow):
def __init__(self, game, board_window, score_window):
CursesWindow.__init__(self, game)
# the window's border adds two extra rows and two extra columns
self.num_rows = game.max_piece_length + 2
self.num_columns = game.max_piece_length + 2
self.window = curses.newwin(
self.num_rows,
self.num_columns,
score_window.num_rows,
board_window.num_columns + 1
)
self.window.border('*', '*', '*', '*', '*', '*', '*', '*')
self.update()
def update(self):
self.window.erase()
# only update the interior of the window
for i in range(self.num_rows - 2):
for j in range(self.num_columns - 2):
if (i, j) in self.game.next_piece.indices:
self.window.addstr(
i + 1,
j + 1,
'1',
curses.color_pair(self.game.next_piece.color)
)
self.window.refresh()
class GUI:
def __init__(self, game):
self.game = game
curses.initscr()
curses.start_color()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)
self.board_window = BoardWindow(game)
self.score_window = ScoreWindow(game, self.board_window)
self.piece_preview_window = PiecePreviewWindow(game, self.board_window,
self.score_window)
self.board_window.keypad(True)
self.board_window.nodelay(True)
class Game:
def __init__(self, board_num_rows, board_num_columns):
self.board = TetrisBoard(board_num_rows, board_num_columns)
self.score = 0
self.max_num_score_digits = 8
self.lines_completed = 0
self.level = 0
self.SPACE_KEY_VALUE = 32
# approximate frame rate
self.frame_rate = 60
self.pieces = [
TetrisPiece([(0, 1), (1, 1), (2, 1), (3, 1)], [1.5, 1.5], 1), # I
TetrisPiece([(0, 1), (1, 1), (2, 1), (2, 2)], [1, 1], 2), # J
TetrisPiece([(0, 1), (1, 1), (2, 1), (2, 0)], [1, 1], 3), # L
TetrisPiece([(0, 0), (0, 1), (1, 0), (1, 1)], [.5, .5], 4), # O
TetrisPiece([(1, 0), (1, 1), (0, 1), (0, 2)], [1, 1], 5), # S
TetrisPiece([(1, 0), (1, 1), (1, 2), (0, 1)], [1, 1], 6), # T
TetrisPiece([(0, 0), (0, 1), (1, 1), (1, 2)], [1, 1], 7) # Z
]
self.max_piece_length = 4
self.next_piece = deepcopy(random.choice(self.pieces))
self.GUI = GUI(self)
def points(self, number_of_lines):
coefficients = [0, 40, 100, 300, 1200]
return coefficients[number_of_lines] * (self.level + 1)
def main_loop(self):
self.board.add_piece(self.next_piece)
self.next_piece = deepcopy(random.choice(self.pieces))
self.GUI.piece_preview_window.update()
loop_count = 0
while True:
keyboard_input = self.GUI.board_window.getch()
loop_count += 1
force_move = (loop_count % max(self.frame_rate - self.level, 1) == 0)
hard_drop = (keyboard_input == self.SPACE_KEY_VALUE)
if force_move or hard_drop:
if hard_drop:
while not self.board.active_piece.last_move_overlap:
self.board.translate_active_piece('down')
self.GUI.board_window.update()
time.sleep(.5)
elif force_move:
self.board.translate_active_piece('down')
if self.board.active_piece.last_move_overlap:
# try to clear lines one at a time starting from the top of
# the screen
line_count = 0
for row_number, row in enumerate(self.board.array):
if all(row):
# highlight row to be deleted
# add 1 to row_number because of board_window's border
self.GUI.board_window.addstr(
row_number + 1, 1, '=' * self.board.num_columns
)
self.GUI.board_window.refresh()
time.sleep(.5)
# delete row
del self.board.array[row_number]
self.board.array.insert(0, [0] * self.board.num_columns)
self.GUI.board_window.update()
time.sleep(.5)
line_count += 1
self.score += self.points(line_count)
self.lines_completed += line_count
self.level = self.lines_completed // 2
# Basically, reset the game to prevent the strings
# corresponding to the score, lines_completed, or level
# variables from exceeding the dimensions the score_window
if len(str(self.score)) > self.max_num_score_digits:
self.score = 0
self.level = 0
self.lines_completed = 0
self.GUI.score_window.update()
# try to add nextPiece to Board
self.board.add_piece(self.next_piece)
# if unsuccessful, gameover
if self.next_piece.last_move_overlap:
break
self.next_piece = deepcopy(random.choice(self.pieces))
self.GUI.piece_preview_window.update()
else:
if keyboard_input == ord('w'):
self.board.rotate_active_piece()
if keyboard_input == ord('d'):
self.board.translate_active_piece('right')
if keyboard_input == ord('s'):
self.board.translate_active_piece('down')
if keyboard_input == ord('a'):
self.board.translate_active_piece('left')
# exit game
if keyboard_input == ord('e'):
break
self.GUI.board_window.update()
# delay after a rotation
if keyboard_input == ord('w'):
time.sleep(.25)
time.sleep(1 / self.frame_rate)
# Reset terminal window before exiting the game.
curses.nocbreak()
self.GUI.board_window.keypad(False)
self.GUI.board_window.nodelay(False)
curses.echo()
curses.endwin()
curses.curs_set(1)
print('Game Over')
exit()
# Run the game
game = Game(board_num_rows=16, board_num_columns=10)
game.main_loop()
</code></pre>
|
[] |
[
{
"body": "<p>In general it looks structured, using good names, split up into functions etc. Those are good things.</p>\n<p>I have some comments but remember these are my opinions, I can't say that it's right or wrong and I won't refer to any standard or code style.</p>\n<h2>1</h2>\n<pre><code>def in_bounds(self, temp_active_piece_indices):\n return all(0 <= i < self.num_rows and 0 <= j < self.num_columns\n for i, j in temp_active_piece_indices)\n</code></pre>\n<p>This piece of code is very short and compact. Few lines, and using Python things like double list comprehension. It gets a lot done with few bytes of code.</p>\n<p>I find it hard to read though and I wouldn't want to cooperate with you on this project if you wrote a lot of code like this, because I would have to spend so much time untangling and trying to understand what something does, before modifying or extending it. And if it needs to be modified, it might need to be completely rewritten.</p>\n<p>A suggestion for how to write it differently, that I find easier to understand (again, this is subjective of course).</p>\n<pre><code>def in_bounds(self, x, y):\n return x >= 0 and x < self.num_columns and y >= 0 and y < self.num_rows\n \n</code></pre>\n<p>This function only handles one piece and it takes the coordinates in directly, it doesn't "care" what those coordinates represents (a piece, but could now be used for anything else too).</p>\n<p>I think using <code>x</code> and <code>y</code> is natural since the rows and columns function as coordinates in a tetris game. This is more specific than <code>i</code> and <code>j</code> which are often used as iterators for any inner loop, which doesn't necessarily or naturally relate to coordinates.</p>\n<p>Also, I'm looking at each case one at a time, no need to use <code>all</code> and "remember" the pieces simultaneously. This is the most important change to make it readable and piece-by-piece easy to understand.</p>\n<p>When calling the function from the outside, it now makes sense to use <code>all</code>.</p>\n<p><code>if all([in_bounds(x,y) for (y,x) in pieces]):</code></p>\n<h2>2</h2>\n<pre><code>def translate_active_piece(self, direction):\n if direction == 'right':\n x, y = 0, 1\n elif direction == 'left':\n x, y = 0, -1\n elif direction == 'down':\n x, y = 1, 0\n</code></pre>\n<p>This is the opposite. No one will ever misunderstand this code or have to look more than a few seconds to understand it. I prefer code like this when I review something. It could be rewritten and convoluted to be much shorter, but that's not necessary and it wouldn't make it easier to work with.</p>\n<p>If you had more options though, let's say 4 or more, I would use a dict to reduce the repetition of <code>if</code> <code>elif</code> and <code>x,y=</code></p>\n<h2>3</h2>\n<pre><code> curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)\n curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)\n curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)\n curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)\n</code></pre>\n<p>Too much repetition here. This can be improved.</p>\n<pre><code>colors = [curses.COLOR_RED, curses.COLOR_GREEN, curses.COLOR_YELLOW, ...]\nfor i, x in enumerate(colors, start=1):\n curses.init_pair(i, x, curses.COLOR_BLACK)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T01:13:48.303",
"Id": "488672",
"Score": "0",
"body": "Thanks for the feedback. Related to your first point, did you find the no_overlap method of the TetrisBoard class difficult to read as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T08:15:02.270",
"Id": "488689",
"Score": "1",
"body": "Yes. same problem with that one. Even worse, I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T08:29:08.860",
"Id": "488690",
"Score": "1",
"body": "I added a suggestion for a different way to do #1"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T22:55:08.170",
"Id": "249332",
"ParentId": "249326",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "249332",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T20:26:59.583",
"Id": "249326",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"tetris"
],
"Title": "Python 3 Curses Terminal Tetris"
}
|
249326
|
<p>I am new in Python coding. I think the code could be written in a better and more compact form. It compiles quite slowly due to the method of removing stop-words.</p>
<p>I wanted to find the top 10 most frequent words from the column excluding the URL links, special characters, punctuations... and stop-words.</p>
<p>Any criticisms and suggestions to improve the efficiency & readability of my code would be greatly appreciated. Also, I want to know if there exists any dedicated python module to get the desired result easily.</p>
<p>I have a <a href="https://www.kaggle.com/gpreda/covid19-tweets/version/24" rel="nofollow noreferrer">dataframe</a> <code>df</code> such that:</p>
<pre><code>print(df['text'])
</code></pre>
<pre><code>0 If I smelled the scent of hand sanitizers toda...
1 Hey @Yankees @YankeesPR and @MLB - wouldn't it...
2 @diane3443 @wdunlap @realDonaldTrump Trump nev...
3 @brookbanktv The one gift #COVID19 has give me...
4 25 July : Media Bulletin on Novel #CoronaVirus...
...
179103 Thanks @IamOhmai for nominating me for the @WH...
179104 2020! The year of insanity! Lol! #COVID19 http...
179105 @CTVNews A powerful painting by Juan Lucena. I...
179106 More than 1,200 students test positive for #CO...
179107 I stop when I see a Stop\n\n@SABCNews\n@Izinda...
Name: text, Length: 179108, dtype: object
</code></pre>
<p>I have done it in the following way:</p>
<pre><code>import pandas as pd
import nltk
import re
import string
from nltk.corpus import stopwords
nltk.download('punkt')
nltk.download('stopwords')
from nltk.tokenize import word_tokenize
stop_words = stopwords.words()
def cleaning(text):
# converting to lowercase, removing URL links, special characters, punctuations...
text = text.lower()
text = re.sub('https?://\S+|www\.\S+', '', text)
text = re.sub('<.*?>+', '', text)
text = re.sub('[%s]' % re.escape(string.punctuation), '', text)
text = re.sub('\n', '', text)
text = re.sub('[’“”…]', '', text)
# removing the emojies # https://www.kaggle.com/alankritamishra/covid-19-tweet-sentiment-analysis#Sentiment-analysis
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
text = emoji_pattern.sub(r'', text)
# removing the stop-words
text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in stop_words]
filtered_sentence = (" ").join(tokens_without_sw)
text = filtered_sentence
return text
dt = df['text'].apply(cleaning)
from collections import Counter
p = Counter(" ".join(dt).split()).most_common(10)
rslt = pd.DataFrame(p, columns=['Word', 'Frequency'])
print(rslt)
</code></pre>
<pre><code> Word Frequency
0 covid19 104546
1 cases 18150
2 new 14585
3 coronavirus 14189
4 amp 12227
5 people 9079
6 pandemic 7944
7 us 7223
8 deaths 7088
9 health 5231
</code></pre>
<p>An example IO of my function <code>cleaning()</code>:</p>
<pre><code>inp = 'If I smelled the scent of hand sanitizers today on someone in the past, I would think they were so intoxicated that… https://t.co/QZvYbrOgb0'
outp = cleaning(inp)
print('Input:\n', inp)
print('Output:\n', outp)
</code></pre>
<pre><code>Input:
If I smelled the scent of hand sanitizers today on someone in the past, I would think they were so intoxicated that… https://t.co/QZvYbrOgb0
Output:
smelled scent hand sanitizers today someone past would think intoxicated
</code></pre>
|
[] |
[
{
"body": "<p>Note: The data you're going through is 370k+ lines. Because I tend to run different versions of code <em>a lot</em> during review, I've limited my version to 1000 lines.</p>\n<hr>\n<p>Your code goes all over the place. Imports, downloads, another import, a variable being loaded, a function definition, the function being called and oh, another import. In that order. Would you agree it's helpful to sort those, so we can easily find what we're looking for?</p>\n<p>The revised head of the file would look like this:</p>\n<pre><code>import re\nimport string\nimport nltk\n\nimport pandas as pd\n\nfrom collections import Counter\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\n\nnltk.download('punkt')\nnltk.download('stopwords')\n</code></pre>\n<p>After that, we'd ordinarily put the function definition. However, there's part of the program that doesn't have to be in the function itself. It only has to be executed once, even if multiple files are handled.</p>\n<pre><code># removing the emojies\n# https://www.kaggle.com/alankritamishra/covid-19-tweet-sentiment-analysis#Sentiment-analysis\nEMOJI_PATTERN = re.compile("["\n u"\\U0001F600-\\U0001F64F" # emoticons\n u"\\U0001F300-\\U0001F5FF" # symbols & pictographs\n u"\\U0001F680-\\U0001F6FF" # transport & map symbols\n u"\\U0001F1E0-\\U0001F1FF" # flags (iOS)\n u"\\U00002702-\\U000027B0"\n u"\\U000024C2-\\U0001F251"\n "]+", flags=re.UNICODE)\n</code></pre>\n<p>The variable is in <code>UPPER_CASE</code> now, because it's a pseudo-constant (Python doesn't really have constants, but it's a reminder to you and other developers that the variable should be set once and only once). It's customary to put the pseudo-constants between the imports and function definitions so you know where to look for them.</p>\n<p>Now, the rest of the program is mostly fine already. You could use more functions, but with a program this size that would mostly be an exercise. I'd rename some of the variables, cut up the lines, use a proper <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> (you had a great start already with the comment at the start of the <code>cleaning</code> function) and <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">prepare the program for re-use</a>. After all, it would be nice to simply import from this file instead of having to copy code to the next few projects using this, wouldn't it? And we don't want to run the specifics of this program every time it's imported, so we explicitly only run it if it's <em>not</em> imported.</p>\n<pre><code>import re\nimport string\nimport nltk\n\nimport pandas as pd\n\nfrom collections import Counter\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\n\nnltk.download('punkt')\nnltk.download('stopwords')\n\nSTOP_WORDS = stopwords.words()\n\n# removing the emojies\n# https://www.kaggle.com/alankritamishra/covid-19-tweet-sentiment-analysis#Sentiment-analysis\nEMOJI_PATTERN = re.compile("["\n u"\\U0001F600-\\U0001F64F" # emoticons\n u"\\U0001F300-\\U0001F5FF" # symbols & pictographs\n u"\\U0001F680-\\U0001F6FF" # transport & map symbols\n u"\\U0001F1E0-\\U0001F1FF" # flags (iOS)\n u"\\U00002702-\\U000027B0"\n u"\\U000024C2-\\U0001F251"\n "]+", flags=re.UNICODE)\n\n\ndef cleaning(text):\n """\n Convert to lowercase.\n Rremove URL links, special characters and punctuation.\n Tokenize and remove stop words.\n """\n text = text.lower()\n text = re.sub('https?://\\S+|www\\.\\S+', '', text)\n text = re.sub('<.*?>+', '', text)\n text = re.sub('[%s]' % re.escape(string.punctuation), '', text)\n text = re.sub('\\n', '', text)\n text = re.sub('[’“”…]', '', text)\n\n text = EMOJI_PATTERN.sub(r'', text)\n\n # removing the stop-words\n text_tokens = word_tokenize(text)\n tokens_without_sw = [\n word for word in text_tokens if not word in STOP_WORDS]\n filtered_sentence = (" ").join(tokens_without_sw)\n text = filtered_sentence\n\n return text\n\n\nif __name__ == "__main__":\n max_rows = 1000 # 'None' to read whole file\n input_file = 'covid19_tweets.csv'\n df = pd.read_csv(input_file,\n delimiter = ',',\n nrows = max_rows,\n engine = "python")\n\n dt = df['text'].apply(cleaning)\n\n word_count = Counter(" ".join(dt).split()).most_common(10)\n word_frequency = pd.DataFrame(word_count, columns = ['Word', 'Frequency'])\n print(word_frequency)\n</code></pre>\n<p>Naturally, if you'd want a more memory-efficient version, you could cut-out all intermediate variables in those last few lines. That would make it a little harder to read though. As long as you're not reading multiple large files into memory in the same program, it should be fine.</p>\n<p>Some of the advice I've provided comes from the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, the official Python style guide. I can highly recommend taking a look at it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T18:06:05.273",
"Id": "260128",
"ParentId": "249329",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T21:29:35.867",
"Id": "249329",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"pandas"
],
"Title": "Finding the most frequent words in Pandas dataframe"
}
|
249329
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.