body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>This is a simple and robust LRUCache implementation using doubly linked list and unordered map. It supports <code>.get()</code>, <code>.put()</code>, and <code>.has()</code> operations in constant time.</p> <p>I want to know if my code conforms to the best practices. Any suggestions or feedback are appreciated! </p> <pre><code>#pragma once #include &lt;list&gt; #include &lt;unordered_map&gt; namespace cache { template &lt;typename KeyType, typename ValueType, typename KeyHash = std::hash&lt;KeyType&gt;, typename KeyEqual = std::equal_to&lt;KeyType&gt;&gt; class LRUCache { private: using KeyValuePair = std::pair&lt;KeyType, ValueType&gt;; using ListIterator = typename std::list&lt;KeyValuePair&gt;::iterator; const size_t maxSize_; std::unordered_map&lt;KeyType, ListIterator&gt; hashmap_; std::list&lt;KeyValuePair&gt; itemsList_; void promoteItemWithKey(const KeyType&amp; key) { ListIterator keyIterator = hashmap_[key]; if (std::next(keyIterator) == itemsList_.end()) { return; } std::iter_swap(keyIterator, std::next(keyIterator)); hashmap_[key] = std::next(keyIterator); hashmap_[keyIterator-&gt;first] = keyIterator; } void removeItemWithKey(const KeyType&amp; key) { itemsList_.erase(hashmap_[key]); hashmap_.erase(key); } public: LRUCache(size_t maxSize) : maxSize_(maxSize) {}; bool has(const KeyType&amp; key) const { return hashmap_.find(key) != hashmap_.end(); } ValueType get(const KeyType&amp; key) { if (!this-&gt;has(key)) throw std::range_error("The key doesn't exist in the cache."); this-&gt;promoteItemWithKey(key); return hashmap_[key]-&gt;second; } void put(const KeyType&amp; key, const ValueType&amp; value) { if (this-&gt;has(key)) { this-&gt;removeItemWithKey(key); } if (itemsList_.size() == maxSize_) { hashmap_.erase(itemsList_.begin()-&gt;first); itemsList_.pop_front(); } itemsList_.emplace_back(std::pair&lt;KeyType, ValueType&gt;(key, value)); hashmap_[key] = std::next(itemsList_.end(), -1); } size_t size() const { return itemsList_.size(); } size_t capacity() const noexcept { return maxSize_; } }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T11:01:31.887", "Id": "408332", "Score": "1", "body": "Do you have some tests, or at least a simple `main()` that shows this class in use?" } ]
[ { "body": "<h1>Headers</h1>\n\n<p>We're missing some headers. I'm guessing that your platform happens to include these as a side-effect of including <code>&lt;list&gt;</code> and <code>&lt;unordered_map&gt;</code>, but that's not a portable assumption.</p>\n\n<pre><code>#include &lt;algorithm&gt; // for std::iter_swap\n#include &lt;cstddef&gt; // for std::size_t\n#include &lt;functional&gt; // for std::equal_to and std::hash\n#include &lt;iterator&gt; // for std::next\n#include &lt;stdexcept&gt; // for std::range_error\n#include &lt;utility&gt; // for std::pair\n</code></pre>\n\n<h1>Size member</h1>\n\n<p>We've consistently misspelt <code>std::size_t</code> (as just <code>size_t</code>). Again, another portability problem.</p>\n\n<p>We might want to check that we are not given a zero size; doing so will break the code's assumptions in <code>put()</code>. We could test and throw, or we could use <code>std::min</code> to ensure it's at least 1, for example.</p>\n\n<p>The accessor <code>capacity()</code> is fairly pointless - we could simply make the <code>maxSize_</code> member public (which is safe, because it's declared <code>const</code>).</p>\n\n<h1>Strange promotion isn't LRU</h1>\n\n<p>Despite the name, this cache doesn't discard the <strong>least-recently</strong> used item to make space, as <code>promoteItemWithKey</code> only swaps the used item with the next one in the list. True LRU means moving the accessed item to the end of the queue; I think you might be able to use the list's <code>splice()</code> method to achieve this more efficiently than <code>std::rotate</code>.</p>\n\n<h1>Unnecessary explicit <code>this</code></h1>\n\n<p>The redundant <code>this-&gt;</code> dereference can make code harder to read:</p>\n\n<blockquote>\n<pre><code> if (this-&gt;has(key)) {\n this-&gt;removeItemWithKey(key);\n }\n</code></pre>\n</blockquote>\n\n<p>It's rare that we need to explicitly write <code>this-&gt;</code> (usually only if we have name conflicts, or call a non-dependent template function), and we can write with much less clutter:</p>\n\n<pre><code> if (has(key)) {\n removeItemWithKey(key);\n }\n</code></pre>\n\n<p>That said, I would prefer us to directly overwrite (and promote) the found element, rather than removing it and constructing a new one - that saves on memory allocation. In fact, the same applies when removing a stale item to insert a new one - </p>\n\n<h1>Unnecessary construction</h1>\n\n<p>Here, we have an unwieldy constructor that we don't need:</p>\n\n<blockquote>\n<pre><code> itemsList_.emplace_back(std::pair&lt;KeyType, ValueType&gt;(key, value));\n</code></pre>\n</blockquote>\n\n<p>The point of <code>emplace_back()</code> is to call the constructor for us:</p>\n\n<pre><code> itemsList_.emplace_back(key, value);\n</code></pre>\n\n<h1>Consider passing by value</h1>\n\n<p>If we <code>put()</code> with an rvalue for <code>value</code>, it's copied unnecessarily. It's probably better to push any copying to the caller (which may be able to elide it), and then <code>std::move</code> the value:</p>\n\n<pre><code>void put(const KeyType&amp; key, ValueType value)\n{\n // ...\n itemsList_.emplace_back(key, std::move(value));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T11:47:39.647", "Id": "211183", "ParentId": "211037", "Score": "4" } } ]
{ "AcceptedAnswerId": "211183", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:27:14.823", "Id": "211037", "Score": "2", "Tags": [ "c++", "c++11", "cache" ], "Title": "LRU Cache in C++11" }
211037
<p>I wrote this class a few months ago and noticed from a few examples that it's better to break down these classes and separate them. I am not so sure what is the proper way to break it into parts. </p> <p>It currently includes a creation of a <code>System_user</code> obj based on user id (fetching user data), login validation, logout, storing user data to session (more specifically CSRF), and I think that's all.</p> <pre><code>&lt;?php namespace MyApp\Models; use \Exception; use MyApp\Core\Database; use MyApp\Core\Config; use MyApp\Helpers\Session; use MyApp\Helpers\Cookie; use MyApp\Helpers\Token; use MyApp\Helpers\General; use MyApp\Helpers\Hash; /** * * System User Class * */ class System_user { /*================================= = Variables = =================================*/ # @object database Database instance private $db; # Users data private $data; # User user ID name public $user_id; # User first name public $first_name; # User last name public $last_name; # Username public $user_name; # User Email public $email; # User Last logged in public $last_login; # is user logged in public $isLoggedIn; # is user logged in public $login_timestamp; # is user IP private $user_ip; /*=============================== = Methods = ================================*/ /** * * Construct * */ public function __construct($system_user = NULL) { # Get database instance $this-&gt;db = Database::getInstance(); # If system_user isn't passed as a variable if ( !$system_user ) { # ...so check if there is a session user id set if (Session::exists(Config::$session_name)) { # Insert session data to system_user variable $system_user = Session::get(Config::$session_name); # Get user data $this-&gt;find($system_user); } } else { $this-&gt;find($system_user); } } /** * * Find method: Find user by id or by username * @param $user String/Init A username or user ID * */ public function find($system_user = NULL) { if ($system_user) { // Enable search for a system_user by a string name or if numeric - so by id. $field = ( is_numeric($system_user) ) ? 'system_user_id' : 'uname'; // Search for the system_user in the Database 'system_users' table. $data = $this-&gt;db-&gt;row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' =&gt; $system_user)); // If there is a result if ( $data ) { // Set data $this-&gt;setUserData($data); return $this; } else { return false; } } else{ return false; } } /** * * Check if user exist in 'system_users' table * @param $username String Get a username user input * @param $password String Get a password user input * @throws Array/Boolian Is this a signed System user? * */ private function system_user_login_validation($username, $password) { $user_data = $this-&gt;db-&gt;row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' =&gt; $username, 'password' =&gt; sha1($password))); if ($user_data) return $user_data; else return false; } /** * * Login method * @param $customer_name String Get a customer_name user input * @param $username String Get a username user input * @param $password String Get a password user input * @throws Boolian Is this a signed System user? * */ public function login($customer_name, $username, $password) { # Create a Customer Obj $customer = new \MyApp\Models\Customer($customer_name); try { # Check if the result is an array # OR there is no row result: if ( (!isset($customer)) || (!isset($customer-&gt;dbName)) || (!isset($customer-&gt;host)) ) throw new \MyApp\Core\Exception\Handler\LoginException("Bad company name: {$customer_name}"); # Change localhost string to 127.0.0.1 (prevent dns lookup) $customer-&gt;host = ($customer-&gt;host === 'localhost') ? '127.0.0.1' : $customer-&gt;host; # Connect to new database $new_connection = $this-&gt;db-&gt;customer_connect($customer-&gt;host, $customer-&gt;dbName); # If status is connected if ($new_connection) { # Check for user credentials data $user_data = $this-&gt;system_user_login_validation($username, $password); # If the result isn't a valid array - EXEPTION if ( (!is_array($user_data)) || (empty($user_data)) ) throw new \MyApp\Core\Exception\Handler\LoginException("Customer: '{$customer_name}' - Invalid username ({$username}) or password ({$password})"); # Store Customer in the sesison Session::put(Config::$customer, serialize($customer)); # Update host and db for the db object # $this-&gt;db-&gt;update_host_and_db($customer-&gt;host, $customer-&gt;dbName); # Set data for this System_user object $this-&gt;setUserData($user_data); # Set a login session for the user id: Session::put(Config::$session_name, $this-&gt;user_id); # Set logged in user sessions $this-&gt;set_loggedin_user_sessions(); return $this; } else { # Connect back to backoffice (current db set) $this-&gt;db-&gt;connect_to_current_set_db(); throw new \MyApp\Core\Exception\Handler\LoginException('User does not exist'); return false; } } catch (\MyApp\Core\Exception\Handler\LoginException $e) { $e-&gt;log($e); return false; // die(General::toJson(array( 'status' =&gt; false, 'message' =&gt; 'Bad login credentials.' ))); } } /** * * Set sessions for the logged in user. * Tutorial: http://forums.devshed.com/php-faqs-stickies/953373-php-sessions-secure-post2921620.html * */ public function set_loggedin_user_sessions() { # Generate security sessions $this-&gt;generate_security_sessions(); # Set login timestamp Session::put(Config::$login_timestamp, $this-&gt;login_timestamp); # Set login flag to true Session::put(Config::$is_logged_in, true); # Set login IP Session::put(Config::$login_user_ip, $this-&gt;user_ip); } /** * * Generate system user security sessions * @param $new_session Boolean (optinal) Dedices if to delete the cookie session id [default is set to true] * */ public function generate_security_sessions($new_session = true) { if ($new_session) # Generate a new session ID session_regenerate_id(true); # Fetch cookie session ID $session_id = session_id(); # Set the session id to the session Session::put(Config::$session_id, $session_id); # Create a secret token # Set it in session (does them both) $secret = Token::generate_login_token(); # Combine secret and session_id and create a hash $combined = Hash::make_from_array(array($secret, $session_id, $this-&gt;user_ip)); # Add combined to session Session::put(Config::$combined, $combined); } /** * * Check if there is a logged in user * */ public function check_logged_in() { if ( Session::exists(Config::$secret) &amp;&amp; # Secret session exists Session::exists(Config::$session_id) &amp;&amp; # Session_id session exists Session::exists(Config::$session_name) &amp;&amp; # User session exists Session::exists(Config::$is_logged_in) &amp;&amp; # Check if 'logged in' session exists Session::exists(Config::$session_name) # Check if sys_user id is set in session ) { # Get users ip $ip = $this-&gt;get_system_user_ip(); # if the saved bombined session if ( (Session::get(Config::$combined) === Hash::make_from_array(array(Session::get(Config::$secret), session_id()), $ip)) &amp;&amp; (Session::get(Config::$is_logged_in) === true ) ) { # Set ip to system user object $this-&gt;user_ip = $ip; return true; } else { return false; } } else { return false; } } /** * * Check if loggin session is timeout * */ public function check_timeout() { if (Session::exists(Config::$login_timestamp)){ # Calculate time $session_lifetime_seconds = time() - Session::get(Config::$login_timestamp) ; if ($session_lifetime_seconds &gt; Config::MAX_TIME){ $this-&gt;logout(); return true; } else { return false; } } else { $this-&gt;logout(); return false; } } /** * * Get user IP * */ private function get_system_user_ip() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP']; elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; else $ip = $_SERVER['REMOTE_ADDR']; return $ip; } /** * * Set User data to (this) System_user object * @param $user_data Array User data fetched from the db (usually by the find method) * */ private function setUserData($user_data) { // Set data for this user object $this-&gt;user_id = $user_data['system_user_id']; $this-&gt;first_name = $user_data['fname']; $this-&gt;last_name = $user_data['lname']; $this-&gt;user_name = $user_data['uname']; $this-&gt;email = $user_data['email']; $this-&gt;last_login = $user_data['last_login']; $this-&gt;isLoggedIn = true; $this-&gt;user_ip = $this-&gt;get_system_user_ip(); $this-&gt;login_timestamp = time(); } /** * * Logout: Now guess what this method does.. * */ public function logout() { $this-&gt;isLoggedIn = false; Cookie::eat_cookies(); Session::kill_session(); session_destroy(); session_write_close(); } } </code></pre> <p>I would like to get suggestions about my current code, and if possible, about structuring it differently with more than one class. (<code>class SystemUser</code>, <code>class systemUserLogin</code>, <code>class systemUserAuthenticator</code>, ect')</p> <p>In general, the webapp by default logs in to a general database. When a user inserts their company_name, username and password, I check if the company name actually exists, and if it does, I disconnect from the general db and connect to the customer's database and validate their username and password.</p> <p>This is the new class I started writing (not tested, so I can't assure this is working code) with more classes following <a href="https://codereview.stackexchange.com/questions/170961/user-class-taking-on-login-and-registration-capabilities">this</a> example and inspired by <a href="https://codereview.stackexchange.com/questions/201066/should-i-add-the-fetch-group-method-to-my-user-class-or-should-i-create-a-sepa">this</a> post I found, while trying to follow the SOLID principals and PSR standards, focusing on the structure and architecture.</p> <pre><code>&lt;?php namespace MyApp\Models; use MyApp\Core\Config; use MyApp\Helpers\Session; use MyApp\Core\Database; /** * * System User Class * */ class SystemUser { /*================================= = Variables = =================================*/ # @obj SystemUser profile information (fullname, profile picture... etc') protected $systemUserDetatils; # @obj SystemUser Login data protected $systemUserLogin; # @obj SystemUser Authenticator protected $systemUserAuthenticator; /*=============================== = Methods = ================================*/ /** * * Construct * */ public function __construct($systemUserId = NULL) { # If system_user passed if ( $systemUserId ) { # Create systemUserDedatils obj $this-&gt;systemUserDetatils = new MyApp\Models\SystemUser\SystemUserDetatils(); # Get SysUser data $this-&gt;systemUserDetatils-&gt;get($systemUserId); } else { # Check for sysUser id in the session: $systemUserId = $this-&gt;systemUserDetatils-&gt;getUserFromSession(); # Get user data from session if ( $systemUserId ) { # Create systemUserDedatils obj $this-&gt;systemUserDetatils = new MyApp\Models\SystemUser\SystemUserDetatils(); # Get SysUser data $this-&gt;systemUserDetatils-&gt;get($systemUserId); } } } /** * * Set Login: Sets the SystemUserLogin object to $systemUserLogin variable * @param $_systemUserLogin SystemUserLogin Gets a SystemUserLogin object * */ public function setSystemUserLogin(SystemUserLogin $_systemUserLogin) { $this-&gt;systemUserLogin = $_systemUserLogin; } /** * * Login * */ public function login() { $this-&gt;systemUserAuthenticator($this); } } &lt;?php namespace MyApp\Models\SystemUser; use MyApp\Core\Config; use MyApp\Helpers\Session; /** * * System User Details Class * */ class SystemUserDetails { /*================================= = Variables = =================================*/ # @object database Database instance private $db; # Users data private $data; # User user ID name public $userId; # User first name public $firstName; # User last name public $lastName; # Username public $userName; # User Email public $email; # User Last logged in public $lastLogin; /*# is user logged in public $isLoggedIn; # is user logged in public $login_timestamp;*/ # is user IP private $user_ip; /*=============================== = Methods = ================================*/ /** * * Construct * */ public function __construct() { # Get database instance $this-&gt;db = Database::getInstance(); } /** * * Find method: Find user by id or by username * @param $user String / Init A username or user ID * @return * */ public function get(Int $systemUserId) { if ($systemUserId) { # Enable search for a system_user by a string name or if numeric - so by id. $field = ( is_numeric($systemUserId) ) ? 'system_user_id' : 'uname'; # Search for the system_user in the Database 'system_users' table. $data = $this-&gt;db-&gt;row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' =&gt; $systemUserId)); # If there is a result if ( $data ) { # Set data $this-&gt;setUserData($data); return $this; } else { return false; } } else { return false; } } /** * * Set User data to $this obj * @param $userData Array User data fetched from the db (usually by the find method) * @return * */ public function set(Array $userData) { // Set data for this user object $this-&gt;userId = $userData['system_user_id']; $this-&gt;firstName = $userData['fname']; $this-&gt;lastName = $userData['lname']; $this-&gt;userName = $userData['uname']; $this-&gt;email = $userData['email']; $this-&gt;lastLogin = $userData['last_login']; } /** * * Get User from session * @param * @return * */ public function getUserFromSession() { # Check if there is a session user id set if (Session::exists(Config::$session_name)) { # Insert session data to system_user variable return Session::get(Config::$session_name); } else { # Returning false cause there is no user id session return false; } } } &lt;?php namespace MyApp\Models\SystemUser; /** * * System User Details Class * */ class systemUserLogin { /*================================= = Variables = =================================*/ # @str Customer name public $customerName; # @str UserName public $userName; # @str Password public $password; # @str user IP public $userIp; /*=============================== = Methods = ================================*/ /** * * Construct - Set customer, username and password * @param $_customerName String * @param $_userName String * @param $_password String * */ public function __construct(String $_customerName, String $_userName, String $_password) { $this-&gt;customerName = $_customerName; $this-&gt;userName = $_userName; $this-&gt;password = $_password; $this-&gt;userIp = $this-&gt;getSystemUserIp(); } /** * * Get user IP * @return String Returns the user IP that is trying to connect. * */ private function getSystemUserIp() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP']; elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; else $ip = $_SERVER['REMOTE_ADDR']; return $ip; } } &lt;?php namespace MyApp\Models\SystemUser; /** * * System User Details Class * */ class systemUserAuthenticator { /*================================= = Variables = =================================*/ # @object Database instance private $db; # @bool Is logged in public $isLoggedIn = false; # @str Login Timestamp public $loginTimestamp; /*=============================== = Methods = ================================*/ /** * * Construct * */ public function __construct() { # Get database instance $this-&gt;db = Database::getInstance(); } /** * * Login method * @param $customer_name String Get a customer_name user input * @param $username String Get a username user input * @param $password String Get a password user input * @throws Boolian Is this a signed System user? * */ public function login(User $user) { # Create a Customer Obj $customer = new \MyApp\Models\Customer($user-&gt;SystemUserLogin-&gt;customerName); try { # Check if the result is an array # OR there is no row result: if ( (!isset($customer)) || (!isset($customer-&gt;dbName)) || (!isset($customer-&gt;host)) ) throw new \MyApp\Core\Exception\Handler\LoginException("Bad company name: {$user-&gt;SystemUserLogin-&gt;customerName}"); # Change localhost string to 127.0.0.1 (prevent dns lookup) $customer-&gt;host = ($customer-&gt;host === 'localhost') ? '127.0.0.1' : $customer-&gt;host; # Connect to new database $new_connection = $this-&gt;db-&gt;customer_connect($customer-&gt;host, $customer-&gt;dbName); # If status is connected if ($new_connection) { # Check for user credentials data $user_data = $this-&gt;system_user_login_validation($user-&gt;SystemUserLogin-&gt;userName, $user-&gt;SystemUserLogin-&gt;password); # If the result isn't a valid array - EXEPTION if ( (!is_array($user_data)) || (empty($user_data)) ) throw new \MyApp\Core\Exception\Handler\LoginException("Customer: '{$user-&gt;SystemUserLogin-&gt;customerName}' - Invalid username ({$user-&gt;SystemUserLogin-&gt;userName}) or password ({$user-&gt;SystemUserLogin-&gt;password})"); # Store Customer in the sesison Session::put(Config::$customer, serialize($customer)); # Update host and db for the db object # $this-&gt;db-&gt;update_host_and_db($customer-&gt;host, $customer-&gt;dbName); # Set data for this System_user object $this-&gt;setUserData($user_data); # Set a login session for the user id: Session::put(Config::$session_name, $this-&gt;user_id); # Set logged in user sessions $this-&gt;set_loggedin_user_sessions(); return $this; } else { # Connect back to backoffice (current db set) $this-&gt;db-&gt;connect_to_current_set_db(); throw new \MyApp\Core\Exception\Handler\LoginException('User does not exist'); return false; } } catch (\MyApp\Core\Exception\Handler\LoginException $e) { $e-&gt;log($e); return false; // die(General::toJson(array( 'status' =&gt; false, 'message' =&gt; 'Bad login credentials.' ))); } } /** * * Check if user exist in 'system_users' table * @param $username String Get a username user input * @param $password String Get a password user input * @throws Array/Boolian Is this a signed System user? * */ private function systemUserLoginValidation($username, $password) { $userData = $this-&gt;db-&gt;row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' =&gt; $username, 'password' =&gt; sha1($password))); if ($userData) return $userData; else return false; } } </code></pre> <p>Login controller:</p> <pre><code>&lt;?php namespace MyApp\Controllers; use MyApp\Core\Controller; use MyApp\Models\System_user; use MyApp\Helpers\Token; use MyApp\Helpers\Input; use MyApp\Helpers\Redirect; use MyApp\Helpers\General; use MyApp\Helpers\Validation; use MyApp\Core\Config; /** * * Login Class * */ class Login extends Controller { /** * * Constructor * */ public function __construct() {} /** * * Index: Login Main login Form * */ public function index($name ='') { // Create a new system user $system_user = new System_user(); // If user is logged in - Redirect to dashboard if ( $system_user-&gt;check_logged_in() ) Redirect::to('dashboard'); // Redirect to login form else // $this-&gt;view('login/pages-login', array('token'=&gt;'banana')); // Redirect to login form $this-&gt;view( 'login/pages-login', array( 'token' =&gt; Token::generate_form_token() ) ); // Redirect to login form } /** * * User login: Creates the user login. * */ public function user_login() { # Check if there are any inputs submitted if (Input::exists()) { # Check if submitted token is identical to the one that's currently set to the session. if (Token::check(Input::get('token'))) { # Validation init $validation = new Validation(); # Set validation requirements $validation = $validation-&gt;check($_POST, array( 'company_name' =&gt; array( 'required' =&gt; true, 'min' =&gt; 3, 'max' =&gt; 30 ), 'user_name' =&gt; array( 'required' =&gt; true, 'min' =&gt; 3, 'max' =&gt; 30, 'unique' =&gt; 'system_users' ), 'password' =&gt; array( 'required' =&gt; true, 'min' =&gt; 6, 'max' =&gt; 30 ) )); if ( $validation-&gt;passed() ) { # Create a new user object // $this-&gt;system_user = new System_user(); // # Check login // if ($this-&gt;system_user-&gt;login(Input::get('company_name'), Input::get('user_name'), Input::get('password'))) { // General::toJson(array( 'status' =&gt; true, 'message' =&gt; 'You have successfully logged in.' )); // } else { // General::toJson(array( 'status' =&gt; false, 'message' =&gt; 'Bad login credentials.' )); // } # Create a login obj $login = new \MyApp\Models\SystemUser\SystemUserLogin(Input::get('company_name'), Input::get('user_name'), Input::get('password')); # Create a new user object $this-&gt;systemUser = new \MyApp\Models\SystemUser(); # Set login credentials $this-&gt;systemUser-&gt;setSystemUserLogin($login); # Login # Check login if ( $this-&gt;systemUser-&gt;login() ) { General::toJson(array( 'status' =&gt; true, 'message' =&gt; 'You have successfully logged in.' )); } else { General::toJson(array( 'status' =&gt; false, 'message' =&gt; 'Bad login credentials.' )); } } } } } } </code></pre> <p>Controller class (<code>Login</code> class extends <code>Controller</code>):</p> <pre><code>&lt;?php namespace MyApp\Core; /** * * Controller instance: * */ class Controller { /*================================= = Variables = =================================*/ # System User protected $system_user; /*=============================== = Methods = ================================*/ /** * * Constructor * */ public function __construct() { # Check if system user is logged in / still logged in / Validate tokens $this-&gt;system_user = new \MyApp\Models\SystemUser(); // # Redirect to login if user not logged in // if (!$this-&gt;system_user) if (!$this-&gt;system_user-&gt;isLoggedIn()) \MyApp\Helpers\Redirect::to('login'); } /** * * Model Class: Loads a requested model * @param $model String Gets a model name * */ protected function model($model) { require_once '../MyApp/models/' . $model . '.php'; return new $model(); } /** * * View Class: Loads a requested view * @param $view String Gets a view name * @param $data Array (optional) Gets an array of variables to pass to the view * @throws Plain view * */ protected function view($view, $data=[]) { require_once '../MyApp/views/' . $view . '.php'; } /** * * Check if a user is logged in * */ protected function is_loggedin() { # Flag for final result: $flag = false; # init user obj $this-&gt;system_user = new \MyApp\Models\System_user(); # Check if user is logged in if ($this-&gt;system_user-&gt;isLoggedIn()) { # Check if the user is timed-out // if (!$this-&gt;system_user-&gt;check_timeout()){ if ( !$this-&gt;system_user-&gt;checkTimeout() ) { # If system user exists // if ( $this-&gt;system_user-&gt;find(intval(Session::get(Config::$systemUserId))) ){ # Re-generate users secret stuff $this-&gt;system_user-&gt;generate_security_sessions(false); $flag = true; // } } } # To return true "it" must pass all "if"s if ( $flag ) { # Return System_user object return $this-&gt;system_user; } else { # logout the user $this-&gt;system_user-&gt;logout(); return false; } } /**************************************************************************************************/ /** * * Automate Views * */ protected function dashboard($optionArray, $view) { $this-&gt;view('main/head', ['controller_name' =&gt; \MyApp\Helpers\General::remove_namespace(get_class($this))]); $this-&gt;view('main/body'); $this-&gt;view('main/top_bar'); $this-&gt;view('main/sidebar', [ 'first_name' =&gt; ($this-&gt;system_user-&gt;firstName) ? $this-&gt;system_user-&gt;firstName : '', 'last_name' =&gt; ($this-&gt;system_user-&gt;lastName) ? $this-&gt;system_user-&gt;lastName : '', 'main_menu' =&gt; \MyApp\Helpers\General::main_menu() ] ); $this-&gt;view('main/page_wrapper', ['controller_name' =&gt; \MyApp\Helpers\General::remove_namespace(get_class($this))]); if ( in_array('date',$optionArray) ){ $this-&gt;view('main/datePicker'); } $this-&gt;view($view); $this-&gt;view('main/footer'); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T15:02:01.520", "Id": "408655", "Score": "0", "body": "I think this needs some carefull thought. The new code is still full of mixed responsibilities - it seems like a `SystemUser ` should be a simple data object, SystemUserDetails is superflous, the other two both do things unrelated to their names, and none of these objects should be using superglobals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T15:06:52.873", "Id": "408656", "Score": "0", "body": "Perhaps if you showed how you actually use these classes it would help clear things up. Are you using an MVC approach? if yes please show your LoginController (or whatever its called)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T15:12:53.713", "Id": "408657", "Score": "0", "body": "Oh and i see from your last question you have a (common) issue with dependancy injection, namely \"having to pass the DB to every class that uses it\" - this only seems like a problem when you are not really using dependency injection. If the app is using it properly, you pretty much never use the `new` keyword outside of your composition root, or factory classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T14:29:33.543", "Id": "408800", "Score": "0", "body": "@Steve Thanks for your reply, I edited my post with these code parts you requested." } ]
[ { "body": "<p>In my <a href=\"https://codereview.stackexchange.com/questions/210972/system-user-class-all-in-one-class-including-login-functions/210978#210978\">last answer for you</a> I mention how you should use <a href=\"http://php-di.org/doc/understanding-di.html\" rel=\"nofollow noreferrer\">dependency injection</a> to avoid tight coupling and promote testability. Then in the comments I go further to mention to take it a step further and use a container like <a href=\"https://pimple.symfony.com/\" rel=\"nofollow noreferrer\">Pimple</a>. Since I don't see those changes here I'll show the container example here since I showed the basic dependency injection in the other answer.</p>\n\n<p><strong>Using Pimple, the Dependency Injection Container</strong></p>\n\n<p><em>I'll assume you will have installed Pimple already and have included it in your application. Their documentation covers that so I won't get into it here.</em></p>\n\n<pre><code>use Pimple\\Container;\nuse MyApp\\Core\\Database;\n\n$container = new Container();\n\n$container['db'] = function ($c) {\n return Database::getInstance();\n};\n</code></pre>\n\n<p>The above code simply:</p>\n\n<ol>\n<li>Creates a container</li>\n<li>Defines a service called <code>db</code></li>\n<li>Instantiates your database class</li>\n<li>Places it in your container</li>\n</ol>\n\n<p>You can add your session logic and other shared objects at this time as well. This is typically contained in its own file but where you put this ins entirely up to you as long as it executes as part of your bootstrap process (i.e. before your business logic).</p>\n\n<p>From here you only need to include Pimple as an argument of the constructor of objects that need to use something in your container.</p>\n\n<pre><code>class System_user\n{\n public function __construct(\\Pimple $container, $system_user = NULL)\n {\n $this-&gt;db = $container['db'];\n }\n}\n</code></pre>\n\n<p>Now you can easily make sure all of your classes are working with the same objects, eliminate dependencies in your code, and your code is testable. </p>\n\n<hr>\n\n<p><strong>Good job with not putting login info into the User object</strong></p>\n\n<p>A common pitfall many developers fall into is to put the login logic into a user object because the user is the one who logs in. You pass the User object into the login functionality which is a <em>much</em> better way to do this. An area for improvement is you place the validation and the login logic all in one method. You could break out the validation into it's own method so you separate the two concerns. You also do this like work with IP addresses again which should be separated out into its own logic.</p>\n\n<p><strong>Getting IP addresses is kind of common</strong></p>\n\n<p>You have a private method for getting the user's IP address (<code>systemUserLogin::getSystemUserIp()</code>). That actually is something not directly related to a user and may be something you eventually wish to use elsewhere. That probably should be broken out into its own function or into another helper class.</p>\n\n<p><strong>FYI Stuff</strong></p>\n\n<p><code>sha1()</code> is obsolete for hashing passwords and should <em>not be used</em>. PHP provides <a href=\"//php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">password_hash()</a> and <a href=\"//php.net/manual/en/function.password-verify.php\" rel=\"nofollow noreferrer\">password_verify()</a>, please use them. And here are some <a href=\"//www.owasp.org/index.php/Password_Storage_Cheat_Sheet\" rel=\"nofollow noreferrer\">good ideas about passwords</a>. If you are using a PHP version prior to 5.5 <a href=\"https://github.com/ircmaxell/password_compat\" rel=\"nofollow noreferrer\">there is a compatibility pack available here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T09:31:19.450", "Id": "408094", "Score": "0", "body": "I made a little research about pimple and it's amazing! Thank you! I am mainly expecting a review regarding the re-construction of the class (/classes)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:53:51.280", "Id": "408111", "Score": "1", "body": "I added some more info directly related to how you architected your classes. I'll add more if I think of anything through the day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:13:24.703", "Id": "408300", "Score": "0", "body": "Since when did `sha1()` become obsolete and why? :O I am continuing to write the new classes and I came across a problem - Do I need to set the properties `$this->user_id | $this->first_name | $this->last_name | $this->user_name | $this->email | $this->last_login | $this->isLoggedIn | $this->user_ip | $this->login_timestamp ` (see first \"old\" code part) to he SystemUser class? or should I add it to the SystemUserDetails class? (so to fetch it i will have to `$user->systemUserDetails->userId` & `$user->systemUserAuthenticator->isLoggedIn` & `$user->systemUserDetails->userId` ect?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:50:09.837", "Id": "408348", "Score": "1", "body": "SHA1 has been obsolete [since 2005 when it was first successfully attacked by researchers](https://en.wikipedia.org/wiki/SHA-1#Attacks)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:28:24.633", "Id": "408364", "Score": "0", "body": "Ok, and any idea regarding to the object variables?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:57:46.897", "Id": "408374", "Score": "1", "body": "Those properties look like they belong ot the SystemUser class as they are properties of that user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:09:35.593", "Id": "408377", "Score": "0", "body": "I was just wondering, if I split my SystemUser class to more classes, maybe it would be more appropriate to set some variables separately too. I started doing that, and noticed that it's very uncomfortable.. Thanks, that settles my confusion :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:00:10.487", "Id": "408386", "Score": "0", "body": "If I want to login from a Login class... and I create an instance of `$systemUser = new SystemUser($something, $_SESSION[Config::$userIdSessionName]);` When I pass the `\\Pimple $container`, what should I exactly pass as a variable of `new SystemUser(x,y)` in that case ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:54:36.363", "Id": "408404", "Score": "0", "body": "I'm not exactly sure what you mean here. But, if you're thinking about putting that SystemUser into Pimple, I would not. Your container should hold your shared services but not you actual business logic or implementation. I would pass your SystemUser around outside of Pimple so it is clear in your code that is business logic and not a common service." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T07:31:40.910", "Id": "408496", "Score": "0", "body": "No, but never mind i figured this out, just from curiosity, why do you like to use Pimple and not others like PHP DI or Symphonys DI? Just wanted to share with you :) https://rawgit.com/kocsismate/php-di-container-benchmarks/master/var/benchmark.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T12:26:23.120", "Id": "408504", "Score": "0", "body": "I have been using Pimple for a long time and am very comfortable with it. Some of the others on that list look very good, especially if every millisecond of performance counts. The basic idea is just to use a container whichever one that you choose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T12:49:12.233", "Id": "408506", "Score": "0", "body": "You recommended using a dependency injection container for the database, right after I told you that I do not want to create / pass an instance of it to everyclass which uses it. I have the same thing with the SystemUser class. Is it common to save a logged in user (or better say, a class such as SystemUser that handles a logged in user) in a pre-initialized container of \"SystemUser\" ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T12:50:00.880", "Id": "408507", "Score": "0", "body": "btw I'm almost done with the new class, I will create a new post with a link for you to see :D !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T12:51:29.327", "Id": "408508", "Score": "1", "body": "That's up to you. Usually containers store generic services. But that doesn't mean you can't put objects like users in there. If that will make your application easier to maintain then it is not a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T14:52:18.510", "Id": "408652", "Score": "0", "body": "This looks like the service locator (anti)pattern, rather than dependency injection. Its an improvement on the original code, but still obscures logic. Why not have `System_user` require an instance of `Database` in its constructor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T15:02:02.957", "Id": "409048", "Score": "0", "body": "Hey @JohnConde https://codereview.stackexchange.com/questions/211557/user-class-getting-user-data-logging-in-secure-csrf-session-handling-logging" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T15:08:07.007", "Id": "409049", "Score": "0", "body": "@Steve, can you please review my new post? https://codereview.stackexchange.com/questions/211557/user-class-getting-user-data-logging-in-secure-csrf-session-handling-logging\n\nI have 0 dependency injections right now, currently trying to figure this out. Passing a DB through the construct will work, but I am so confused about how to structure this app. I wrote a post about it but didn't receive a decent answer. \nhttps://stackoverflow.com/questions/54185501/symfony-di-is-it-possible-to-get-the-database-class-from-the-container-without" } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T00:07:15.853", "Id": "211066", "ParentId": "211040", "Score": "3" } } ]
{ "AcceptedAnswerId": "211066", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:42:12.330", "Id": "211040", "Score": "2", "Tags": [ "php", "object-oriented", "design-patterns" ], "Title": "User class: getting user data, logging in, secure CSRF session handling" }
211040
<p>I implemented <a href="https://core.ac.uk/download/pdf/82129717.pdf" rel="noreferrer">this paper</a>, more specifically the bipartite graph case in numpy.</p> <p>The whole code is available on <a href="https://github.com/louisabraham/matchmaker" rel="noreferrer">github</a>.</p> <p>The file <a href="https://github.com/louisabraham/matchmaker/blob/master/matchmaker/munkres.py" rel="noreferrer"><code>munkres.py</code></a> comes from <a href="https://github.com/scipy/scipy/blob/v0.18.1/scipy/optimize/_hungarian.py" rel="noreferrer">scipy</a>.</p> <p>Some variables seem poorly named but they respect the definitions of the paper.</p> <p>I pasted the main file below. If you want to read it with line numbers and syntax coloring, it is also on <a href="https://github.com/louisabraham/matchmaker/blob/master/matchmaker/munkres.py" rel="noreferrer">github</a>.</p> <pre><code>__all__ = ["cost_matrix_without_inf", "linear_sum_assignment_iter"] from heapq import heappush, heappop import numpy as np from .munkres import linear_sum_assignment def cost_matrix_without_inf(cost_matrix): """ Replaces inf with a value that yield the same assignment. inf means that an edge should not be used. """ cost_matrix = np.asarray(cost_matrix).copy() if not np.issubdtype(cost_matrix.dtype, np.floating): return cost_matrix if np.isneginf(cost_matrix).any(): raise ValueError("matrix contains -inf") values = cost_matrix[~np.isinf(cost_matrix)] m = values.min() M = values.max() n = min(cost_matrix.shape) # strictly positive constant even when added # to elements of the cost matrix positive = n * (M - m + np.abs(M) + np.abs(m) + 1) place_holder = (M + (n - 1) * (M - m)) + positive cost_matrix[np.isposinf(cost_matrix)] = place_holder return cost_matrix def _coords_to_index(x): if not x: return np.array([], dtype=int), np.array([], dtype=int) a, b = zip(*x) return np.array(a), np.array(b) def _index_to_coords(x): return list(zip(*x)) def _second_best_assignment(cost_matrix, M, I, O): """Returns the second best solution to the assignment problem defined by ``cost_matrix`` with the constraints: - all edges from ``I`` must be used - the edges from ``O`` are forbidden ``M`` is the best solution to this problem. If the solution does not exist, returns None """ cost_matrix = cost_matrix.copy() # select a boolean mask to discard the # rows and columns of already chosed assignments select = np.ones_like(cost_matrix, dtype=bool) i1, i2 = _coords_to_index(I) select[i1, :] = False select[:, i2] = False # put an infinite weight to forbidden edges cost_matrix[_coords_to_index(O)] = np.inf # the theorem only works for perfect matchings n, m = cost_matrix.shape assert n == m # build the graph distance = np.tile(np.inf, (2 * n, 2 * n)) distance[:n, n:][select] = cost_matrix[select] distance[M[0], n + M[1]] = np.inf distance[n + M[1], M[0]] = np.where( np.isposinf(cost_matrix[M]), cost_matrix[M], -cost_matrix[M] ) backtrack = np.tile(np.arange(2 * n), (2 * n, 1)) # Floyd–Warshall algorithm for k in range(2 * n): for i in range(2 * n): for j in range(2 * n): if distance[i, k] + distance[k, j] &lt; distance[i, j]: distance[i, j] = distance[i, k] + distance[k, j] backtrack[i, j] = backtrack[i, k] # restricting to the first n values should not be necessary # but not doing it can fail some tests like this one: # list( # linear_sum_assignment_iter( # [ # [-319.77581059, -426.02257358, 129.91680618], # [201.86064154, float("inf"), 483.324417], # [434.94794501, -324.91883433, 204.60857852], # ] # ) # ) # no solution is possible if np.isposinf(np.diagonal(distance)[:n].min()): return # compute the symetric difference of M and the cycle matching = set(_index_to_coords(M)) target = np.diagonal(distance)[:n].argmin() next_vertex = lambda i: backtrack[i, target] i, j = target, next_vertex(target) while True: matching.add((i, j - n)) i, j = j, next_vertex(j) matching.remove((j, i - n)) if j == target: break i, j = j, next_vertex(j) return _coords_to_index(sorted(matching)) def _choose_in_difference(M, N): return next( eM for (eM, eN) in zip(_index_to_coords(M), _index_to_coords(N)) if eM != eN ) def linear_sum_assignment_iter(cost_matrix: np.ndarray): """Iterate over the solutions to the linear sum assignment problem in increasing order of cost The method used for the first solution is the Hungarian algorithm, also known as the Munkres or Kuhn-Munkres algorithm. The method used to find the second best solution and iterate over the solutions is described in [1]_, but is implemented in a slightly different, Dijkstra-like way. The states are represented as .. math: (cost(N_k), r, M_k, N_k, I_k, O_k) with :math:``r`` a random number used to avoid comparing the assignments. This function can also solve a generalization of the classic assignment problem where the cost matrix is rectangular. If it has more rows than columns, then not every row needs to be assigned to a column, and vice versa. It supports infinite weights to represent edges that must never be used. Parameters ---------- cost_matrix : array The cost matrix of the bipartite graph. Yields ------- row_ind, col_ind : array An array of row indices and one of corresponding column indices giving the optimal assignment. The cost of the assignment can be computed as ``cost_matrix[row_ind, col_ind].sum()``. The row indices will be sorted; in the case of a square cost matrix they will be equal to ``numpy.arange(cost_matrix.shape[0])``. Examples -------- &gt;&gt;&gt; cost = np.array([[4, 1, 3], [2, 0, float("inf")], [3, 2, 2]]) &gt;&gt;&gt; from matchmaker import linear_sum_assignment_iter &gt;&gt;&gt; it = linear_sum_assignment_iter(cost) &gt;&gt;&gt; row_ind, col_ind = next(it) &gt;&gt;&gt; col_ind array([1, 0, 2]) &gt;&gt;&gt; cost[row_ind, col_ind].sum() 5.0 &gt;&gt;&gt; row_ind, col_ind = next(it) &gt;&gt;&gt; col_ind array([0, 1, 2]) &gt;&gt;&gt; cost[row_ind, col_ind].sum() 6.0 References ---------- .. [1] Chegireddy, Chandra R., and Horst W. Hamacher. "Algorithms for finding k-best perfect matchings." Discrete applied mathematics 18, no. 2 (1987): 155-165. """ cost_matrix = np.asarray(cost_matrix) # make the cost_matrix square as the algorithm only works # for perfect matchings # any value other than 0 would work # see &lt;https://cstheory.stackexchange.com/a/42168/43172&gt; n, m = cost_matrix.shape if n &lt; m: cost_matrix = np.concatenate( (cost_matrix, np.zeros((m - n, m), dtype=cost_matrix.dtype)), axis=0 ) elif n &gt; m: cost_matrix = np.concatenate( (cost_matrix, np.zeros((n, n - m), dtype=cost_matrix.dtype)), axis=1 ) def transform(a, b): """transforms a solution assignment (a, b) back to the original matrix """ mask = (a &lt; n) &amp; (b &lt; m) return a[mask], b[mask] cost = lambda assignment: cost_matrix[assignment].sum() # linear_sum_assignment doesn't require the matrix to be square, # but second_best_assignment needs the best solution for a square matrix M1 = linear_sum_assignment(cost_matrix_without_inf(cost_matrix)) if not np.isposinf(cost(M1)): yield transform(*M1) else: return # from now, use a copy of cost_matrix # with dtype float cost_matrix = cost_matrix.astype(float) I1 = [] O1 = [] N1 = _second_best_assignment(cost_matrix, M1, I1, O1) if N1 is None: return Q = [(cost(N1), np.random.rand(), M1, N1, I1, O1)] while Q: _, _, M, N, I, O = heappop(Q) yield transform(*N) e = _choose_in_difference(M, N) Ip, Op = I + [e], O Np = _second_best_assignment(cost_matrix, M, Ip, Op) if Np is not None: heappush(Q, (cost(Np), np.random.rand(), M, Np, Ip, Op)) Ik, Ok = I, O + [e] Nk = _second_best_assignment(cost_matrix, N, Ik, Ok) if Nk is not None: heappush(Q, (cost(Nk), np.random.rand(), N, Nk, Ik, Ok)) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:19:30.410", "Id": "211047", "Score": "5", "Tags": [ "python", "algorithm" ], "Title": "Iterate over the solutions for minimum cost matching" }
211047
<p>I am trying to learn Python 3.6 with the help of a book. Until now I have learned the basics of functions, conditions and printing etc. No loops yet - so they need to come from recursion.</p> <p>To test the current stuff I wrote this basic TicTacToe - and would like to know what could be better.</p> <pre><code>def print_game(*args): formatstring = " A B C\n" + "-" *10 + "\n1 {}|{}|{}\n" + "-" *10 + "\n2 {}|{}|{}\n" + "-" *10 + "\n3 {}|{}|{}" print(formatstring.format(*args)) def ask_player(round): prompt_player1 = "Player one&gt;&gt; " prompt_player2 = "Player two&gt;&gt; " if round % 2 == 0: current_choice = input(prompt_player2) current_player = 2 else: current_choice = input(prompt_player1) current_player = 1 if current_choice != "A1" and current_choice != "B1" and current_choice != "C1" and current_choice != "A2" and current_choice != "B2" and current_choice != "C2" and current_choice != "A3" and current_choice != "B3" and current_choice != "C3": print("Please use Field identifier like A1/B3 ...") ask_player(round) else: return current_choice, current_player def do_the_draw(game,field,player): valid = 1 if player == 1: char='X' if player == 2: char='O' if field == 'A1' and game[0]==' ': game[0] = char elif field == 'B1' and game[1]==' ': game[1] = char elif field == 'C1' and game[2]==' ': game[2] = char elif field == 'A2' and game[3]==' ': game[3] = char elif field == 'B2' and game[4]==' ': game[4] = char elif field == 'C2' and game[5]==' ': game[5] = char elif field == 'A3' and game[6]==' ': game[6] = char elif field == 'B3' and game[7]==' ': game[7] = char elif field == 'C3' and game[8]==' ': game[8] = char else: print(f"Invalid Move field {field} is already used - Choose another one") valid = 0 print_game(*game) return game,valid def evaluate(s): result = False #game continues # Horizontal lines if s[0]+s[1]+s[2] == 'XXX' or s[0]+s[1]+s[2] == 'OOO': result = True if s[3]+s[4]+s[5] == 'XXX' or s[3]+s[4]+s[5] == 'OOO': result = True if s[6]+s[7]+s[8] == 'XXX' or s[6]+s[7]+s[8] == 'OOO' : result = True # Vertical lines if s[0]+s[3]+s[6] == 'XXX' or s[0]+s[3]+s[6] == 'OOO': result = True if s[1]+s[4]+s[7] == 'XXX' or s[1]+s[4]+s[7] == 'OOO': result = True if s[2]+s[5]+s[8] == 'XXX' or s[2]+s[5]+s[8] == 'OOO' : result = True # Diagonal lines if s[0]+s[4]+s[8] == 'XXX' or s[1]+s[4]+s[7] == 'OOO': result = True if s[2]+s[4]+s[6] == 'XXX' or s[2]+s[5]+s[8] == 'OOO' : result = True return result def main(draws,status): user_input, player = ask_player(draws) status,valid = do_the_draw(status,user_input,player) if valid == 0: return main(draws,status) draws -=1 if evaluate(status): draws = False print(f"We have a winner Player: {player}") if draws: return main(draws,status) elif input("try again?")=='y': print("#" *100) print("Here we go again\n\n") draws = 9 status = " , , , , , , , , " status = status.split(',') print_game(*status) return main(draws,status) # Print the initial Game pattern themaingame=" , , , , , , , , " # cause i was not able to figure out how to initialise lists ... we split themaingame = themaingame.split(',') # Initial Print of the Board print_game(*themaingame) #Calling the Main Method with the maximum number of draws (9) and the prepared List main(9,themaingame) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:32:10.167", "Id": "408104", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:48:45.797", "Id": "408107", "Score": "0", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:59:27.787", "Id": "408115", "Score": "0", "body": "Isn't this a duplicate to https://codereview.stackexchange.com/questions/211067/my-first-python-project-tic-tac-toe-v2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:24:57.790", "Id": "408127", "Score": "0", "body": "thanks for pointing out - I was not sure how to do it and I only found the code of conduct." } ]
[ { "body": "<p>maybe I have some useful suggestions.</p>\n\n<p>I think having main recursively call itself is a little weird. Try to keep the main very short, so my suggestion create a function called play_tictactoe() and call that from main instead. This also means <code>play_tictactoe</code> recursively calls itself instead of <code>main</code>.</p>\n\n<p>You have a function called do_the_draw() but it also updates the game board. Functions typically do 1 thing and it should be obvious based on it's name. You could separate your draw logic and update logic. You could just rename <code>do_the_draw()</code> to <code>update_board()</code> and remove the drawing logic and call it in the play function.</p>\n\n<p><code>evaluate</code> can be simplified by supplying a symbol. <code>evaluate(s, char)</code> could reduce the function by half, so it could be <code>evaluate(status, 'OOO')</code> and <code>evaluate(status, 'XXX')</code> which will result in less typing errors like you have for <code>if s[0]+s[4]+s[8] == 'XXX' or s[1]+s[4]+s[7] == 'OOO':</code></p>\n\n<p>Finally if you have access to maps or arrays (ignore this if you do not) you can probably reduce some of those huge if groups down using a map. I won't go into too much detail since you probably don't have access but a map of field to numbers such as <code>{ \"A1\": 0, \"A2\": 1 }</code> could help reduce the long if statement by just checking if the map has a key and the other if statement since it could just check <code>game[fields[field]] == ' '</code>. If you have access to array functions you could do something similar with just arrays and using their built in functions so you do not need to loop over them yourself.</p>\n\n<p>Hopefully that makes sense and it was an inter</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:48:13.807", "Id": "211060", "ParentId": "211053", "Score": "3" } } ]
{ "AcceptedAnswerId": "211060", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:07:00.247", "Id": "211053", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "tic-tac-toe" ], "Title": "Beginner TicTacToe" }
211053
<p>It is to find the maximum element in an array which is first increasing and then decreasing. I've tried to write my idea by using divide and conquer approach. Is there any improvable or missing point? My code is following,</p> <pre><code>def search(arr, low, high): if low == high: return arr[low] mid = low + (high - low) // 2 if arr[mid] &gt; arr[mid + 1]: # if it's peak that a number whose left and right are smaller than it, return it if arr[mid] &gt; arr[mid - 1]: return arr[mid] else: return search(arr, low, mid) else: return search(arr, mid + 1, high) if __name__ == "__main__": arr = [ 70, 80, 9, 6 ] arr2 = [60, 70, 72, 74, 88] arr3 = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1] arr4 = [10, 20, 30, 40, 50] arr5 = [1, 3, 50, 10, 9, 7, 6] arr6 = [120, 100, 80, 20, 0] print(search(arr, 0, len(arr) - 1)) print(search(arr2, 0, len(arr2) - 1)) print(search(arr3, 0, len(arr3) - 1)) print(search(arr4, 0, len(arr4) - 1)) print(search(arr5, 0, len(arr5) - 1)) print(search(arr6, 0, len(arr6) - 1)) </code></pre> <p>Output:</p> <pre><code>80 88 500 50 50 120 </code></pre>
[]
[ { "body": "<p>The code will crash with an out of bounds exception if given a zero-length array.</p>\n\n<p>You are playing a little loose with the array endpoints. If you get to <code>mid=0</code>, and it turns out that <code>arr[mid] &gt; arr[mid+1]</code>, then you will check <code>arr[mid] &gt; arr[mid-1]</code>, which will be reading <code>arr[-1]</code> which is the element at <strong>the other end</strong> of the array. Fortunately, if <code>arr[0] &gt; arr[1]</code>, then the array must be monotonically decreasing, and the last value will be the smallest, but relying on that is tricky behaviour.</p>\n\n<p>Your code is recursively executing <code>return search(...)</code>, Python does not do tail-recursion-optimization. This could could easily be re-written to use a loop, which would be faster and doesn’t require any additional stack space. For example, something like:</p>\n\n<pre><code>while low &lt; high:\n mid = low + (high - low) // 2\n\n if arr[mid-1] &lt; arr[mid] &lt; arr[mid+1]:\n return arr[mid]\n\n if arr[mid] &gt; arr[mid+1]:\n high = mid\n else:\n low = mid + 1\n\nreturn arr[low]\n</code></pre>\n\n<p>You <code>search(mid+1, high)</code>. Why don’t you <code>search(low, mid-1)</code>? Seems asymmetrical. </p>\n\n<p>Minor nit: You algorithm will fail if the array can have equal elements, such as 5, 50, 10, 10, 10, 10, 5. It will find “10” at the mid-point and on both sides, at which point it will drift to the larger indexes, and eventually declare “10” as the maximum.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T01:16:46.870", "Id": "211068", "ParentId": "211059", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:21:01.567", "Id": "211059", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "recursion", "divide-and-conquer" ], "Title": "Finding peak point in an array by using divide and conquer approach" }
211059
<p>I have 2 Classes, the first one is only used as Container, and the second Class Splits a GpsString, Converts it to suitable data types and returns the Container Class.</p> <p>The String to analyze looks about like this:</p> <pre><code>("$GPGGA,120003.533,7926.184,N,02222.419,W,1,12,1.0,88.5,M,0.0,M,,*71") </code></pre> <p>Now i want to know if this is good practice in ObjectOriented Programming, or if there is a better way for this Problem.</p> <pre><code>final class GpsData { int Hours; int Minutes; double Seconds; double Lattitude; char DirectionLattitude; // North or South double Longitude; char DirectionLongitude; // North or South int Quality; int Satelites; } class ProtocolAnalyzer { private GpsData AnalyzedData = new GpsData(); boolean AnalyzeData(String GpsData){ GpsData Gps = new GpsData(); int Attribute = 0; StringBuilder WorkString = new StringBuilder(); int beginIndex = 0; int length = GpsData.length(); for (int i = 0;i&lt;=length;i++){ if(i == GpsData.length() || GpsData.charAt(i) == ','){ String Data = GpsData.substring(beginIndex,i); boolean bool = ConvertData(Data,Attribute,Gps); if(!bool) return false; beginIndex = i + 1; Attribute ++; } } setAnalyzedData(Gps); return true; } private boolean ConvertData(String Data,int Attribute,GpsData Gps){ boolean b = false; switch (Attribute) { case 0: // §GPGGA if(Data.equals("$GPGGA")) { b = true; } break; case 1: //HHMMSS.sss if(Data.length() == 10) { b = true; String split = Data.substring(0,2); Gps.Hours = Integer.parseInt(split); split = Data.substring(2,4); Gps.Minutes = Integer.parseInt(split); split = Data.substring(4,10); Gps.Seconds = Double.parseDouble(split); } break; case 2: //BBBB.BBBB if (Data.length() != 0) { b = true; Gps.Lattitude = Double.parseDouble(Data); } break; case 3: //b if (Data.length() != 0) { char DirLat = Data.charAt(0); if (DirLat == 'N' || DirLat == 'S') { b = true; Gps.DirectionLattitude = DirLat; } } break; case 4: //LLLLL.LLLL if (Data.length() != 0) { b = true; Gps.Longitude = Double.parseDouble(Data); } break; case 5: //l if (Data.length() != 0) { char DirLong = Data.charAt(0); if (DirLong == 'E' || DirLong == 'W') { b = true; Gps.DirectionLongitude = DirLong; } } break; case 6: //Q if (Data.length() != 0) { int Quality = Integer.parseInt(Data); Gps.Quality = Quality; if(Quality != 0) { b = true; } } break; case 7: //NN if (Data.length() != 0) { int Satellites = Integer.parseInt(Data); Gps.Satelites = Satellites; if(Satellites &gt; 3) { b = true; } } break; } return b; } private void setAnalyzedData(GpsData LogData) { this.AnalyzedData = (LogData); } GpsData getAnalyzedData() { return AnalyzedData; } } </code></pre>
[]
[ { "body": "<p>First, <em>please please please</em> use Java naming conventions to aid readability. Methods and local variables like <code>int Hours</code> should be in <code>camelCase</code> and not <code>CapitalCase</code> which is for classes. Statements like this: </p>\n\n<pre><code>boolean AnalyzeData(String GpsData){\n</code></pre>\n\n<p>are especially confusing. Is <code>GpsData</code> referring to the local variable, or the class? That can get very nasty very quickly. Please fix this before you do anything else.</p>\n\n<pre><code>final class GpsData {\n</code></pre>\n\n<p>This does not do what I suspect you think it does. A <code>final</code> declaration for a class just means it can't be further extended. Its data can still be modified. To properly encapsulate the properties of <code>GpsData</code> you should declare each of those properties as <code>private</code> and provide <code>public</code> constructors, setters, and getters as appropriate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T07:20:28.317", "Id": "408086", "Score": "0", "body": "Ok i understand, i will use the naming conventions in the future.\nBut about the setters, getters and constructors, i want to get the whole structure with one getter not multiple ones." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:09:28.997", "Id": "408102", "Score": "0", "body": "@Martin.Schloegelhofer avoiding getters does not give you \"the whole structure\". A simple reference does that either way. However, using getters doesn't provide real encapsulation. It provides a place to set a breakpoint so you can watch someone break your encapsulation. This is good. It's just not encapsulation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:28:18.963", "Id": "408147", "Score": "0", "body": "@candied_orange You are correct, using simple setters is not \"encapsulation\". But, with setters you can at least incorporate checks to ensure that your data does not enter into an invalid state. At any rate, I was addressing OP's questions of whether what he was doing is \"OOP\". If he isn't concerned about that, then it's fine of course." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:44:40.067", "Id": "408155", "Score": "0", "body": "@StalemateOfTuning that's validation. Getters don't help with that. Setters do. Or preferably constructors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:29:35.533", "Id": "408198", "Score": "0", "body": "That's what I said?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:57:15.450", "Id": "211064", "ParentId": "211062", "Score": "1" } }, { "body": "<p>You may want to think about encapsulating your GPS data to protect it. As Stalemate indicated this means making GpsData class variables private and adding getters, setters and constructors to the class. This <a href=\"https://en.wikipedia.org/wiki/Java_package\" rel=\"nofollow noreferrer\">wiki</a> may explain why better than I can.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T09:09:16.640", "Id": "211085", "ParentId": "211062", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:33:42.097", "Id": "211062", "Score": "2", "Tags": [ "java" ], "Title": "Splitting a String and Returning Converted Data" }
211062
<p>Hey guys this is my second attempt at a Tic Tac Toe game using the advice given in my first post: <a href="https://codereview.stackexchange.com/questions/210958/my-first-python-project-tic-tac-toe">My first Python project: Tic Tac Toe</a></p> <p>Again, just looking for advice on things I can improve. There is no classes because I have not really learned a great deal about OOP yet. I wanted to make sure I could use functions proficiently before I continued. I'm sure there is a way to loop the if statements in check_win(), but I have not figured it out yet.</p> <pre><code>def num_to_coord(num): # 0-index num num -= 1 coord = [] while True: curr_coord = num % 3 coord.append(curr_coord) if len(coord) &gt;= 2: break num -= curr_coord num //= 3 return coord def change_symbol(the_symbol): if the_symbol == 'x': the_symbol = 'o' return the_symbol if the_symbol == 'o': the_symbol = 'x' return the_symbol def get_position(): position = int(input("Enter a position: ")) return position def check_position(the_position, the_taken_positions): if the_position in the_taken_positions: return True if the_position not in the_taken_positions: return False def draw_position(location, the_symbol, the_game_board): coord = num_to_coord(location) the_game_board[coord[0]][coord[1]] = the_symbol for y in range(3): print(add_sep('|', [the_game_board[x][y] for x in range(3)])) def add_sep(sep, lst): """Adding | to board""" output = sep for i in lst: output += i + sep return output def check_win(the_game_board): if the_game_board[0][0] == 'x' and the_game_board[1][0] == 'x' and the_game_board[2][0] == 'x' or \ (the_game_board[0][0] == 'o' and the_game_board[1][0] == 'o' and the_game_board[2][0] == 'o'): return True if the_game_board[0][1] == 'x' and the_game_board[1][1] == 'x' and the_game_board[2][1] == 'x' or \ (the_game_board[0][1] == 'o' and the_game_board[1][1] == 'o' and the_game_board[2][1] == 'o'): return True if the_game_board[0][2] == 'x' and the_game_board[1][2] == 'x' and the_game_board[2][2] == 'x' or \ (the_game_board[0][2] == 'o' and the_game_board[1][2] == 'o' and the_game_board[2][2] == 'o'): return True if the_game_board[0][0] == 'x' and the_game_board[0][1] == 'x' and the_game_board[0][2] == 'x' or \ (the_game_board[0][0] == 'o' and the_game_board[0][1] == 'o' and the_game_board[0][2] == 'o'): return True if the_game_board[1][0] == 'x' and the_game_board[1][1] == 'x' and the_game_board[1][2] == 'x' or \ (the_game_board[1][0] == 'o' and the_game_board[1][1] == 'o' and the_game_board[1][2] == 'o'): return True if the_game_board[2][0] == 'x' and the_game_board[2][1] == 'x' and the_game_board[2][2] == 'x' or \ (the_game_board[2][0] == 'o' and the_game_board[2][1] == 'o' and the_game_board[2][2] == 'o'): return True if the_game_board[0][0] == 'x' and the_game_board[1][1] == 'x' and the_game_board[2][2] == 'x' or \ (the_game_board[0][0] == 'o' and the_game_board[1][1] == 'o' and the_game_board[2][2] == 'o'): return True if the_game_board[0][2] == 'x' and the_game_board[1][1] == 'x' and the_game_board[2][0] == 'x' or \ (the_game_board[0][2] == 'o' and the_game_board[1][1] == 'o' and the_game_board[2][0] == 'o'): return True else: return False def intro(): intro_board = [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']] print("Welcome to Tic Tac Toe") print("You can pick location by identifying the position on the board. (There are 9 positions)") print("The player who plays first will be using 'x' and the second player will be using 'o'.") for y in range(3): print(add_sep('|', [intro_board[x][y] for x in range(3)])) def main(): game_board = [[' '] * 3 for _ in range(3)] taken_positions = [] symbol = 'x' num_moves = 0 win = False intro() while num_moves &lt; 9 and not win: position = get_position() taken = check_position(position, taken_positions) if taken: print("Position taken! Try again.") else: draw_position(position, symbol, game_board) taken_positions.append(position) symbol = change_symbol(symbol) num_moves = num_moves + 1 win = check_win(game_board) if win: print("We have a winner!") break if num_moves == 9 and not win: print("WOW! You guys are good! DRAW!!!") # MAIN main() print("Thanks for playing! Exiting") </code></pre>
[]
[ { "body": "<p>You could begin with <code>win</code> checking. The way you have done it works fine. But what if you were to resize the board? lets say <code>5x5</code>? You would need to write lots of if/else statements to check for winning cases.</p>\n\n<p>Now, instead of using loads of <code>if/else</code> statements to look for winning cases you could use <code>for</code> loops to look trough <code>rows</code>, <code>columns</code>, and <code>crosses</code> as shown here:<br><br>\n<a href=\"https://i.stack.imgur.com/tphhD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tphhD.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here is an example of what I am talking about (you can use this if you wish so):</p>\n\n<p>this one is for <code>column</code> checking (top-down)</p>\n\n<pre><code># check columns\n# symbol can be x or o\ndef checkCol(symbol, board):\n counter = 0\n for i in range(len(board)):\n for j in range(len(board)):\n if board[j][i] == symbol:\n counter += 1\n else:\n counter = 0\n if counter == len(board):\n break\n return True if counter == len(board) else False\n</code></pre>\n\n<p>and this is for <code>row</code> checking (left-right)</p>\n\n<pre><code># check rows\n# symbol can be x or o\ndef checkRow(symbol, board):\n counter = 0\n for i in range(len(board)):\n for j in range(len(board)):\n if board[i][j] == symbol:\n counter += 1\n else:\n counter = 0\n if counter == len(board):\n break\n return True if counter == len(board) else False\n</code></pre>\n\n<p>Positive cross:</p>\n\n<pre><code>#prositive cross (top left to bottom right)\ndef checkCrossPositive(symbol, board):\n counter = 0\n for i in range(len(board)):\n if board[i][i] == symbol:\n counter+=1\n else:\n counter = 0\n return True if counter == len(board) else False\n</code></pre>\n\n<p>Negative cross:</p>\n\n<pre><code># negative cross (top right to bottom left)\ndef checkCrossNegative(symbol, board):\n counter = 0\n j = len(board)-1\n for i in range(len(board)):\n if board[i][j] == symbol:\n counter += 1\n else:\n counter = 0\n j-=1\n return True if counter == len(board) else False\n</code></pre>\n\n<p>Here's how it can be used:</p>\n\n<pre><code>def check_win(board):\n return \\\n (checkRow('x', board) or checkRow('o', board) )\\\n or (checkCol('x', board) or checkCol('o', board))\\\n or (checkCrossPositive('x', board) or checkCrossPositive('o', board))\\\n or (checkCrossNegative('x', board) or checkCrossNegative('o', board))\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Avoid manually placing numbers here and there such as in</p>\n\n<pre><code>if num_moves == 9 and not win:\n</code></pre>\n\n<p>instead of that you could have it in a \"constant\" variable.\n(I know <code>python</code> doesn't have <code>constant</code> but just for the sake of best-practice)</p>\n\n<pre><code>if num_moves == MAX_MOVES and not win:\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT (Explanation for column checker):</strong></p>\n\n<p><strong>Part 1</strong></p>\n\n<p>Usually when we iterate over a two dimensional array we use <code>i</code> and <code>j</code> as <code>X</code> and <code>Y</code> where <code>i=Y</code> and <code>j=X</code>\nlet's say we have a two dimensional array as this:</p>\n\n<pre><code>array = [\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 0]\n]\n</code></pre>\n\n<p>If we iterate over this array the usual way we'd get <code>1,2,3,4,5</code> &amp; <code>6,7,8,9,0</code>\nas output because the <code>Y-axis ( i )</code> represents indexes of inner arrays (those that contain numbers 1,2,3 ...).\nFirst (inner-)array has index <code>0</code>, the second one has <code>1</code> and so on it goes.</p>\n\n<p>This way we are iterating <code>row =&gt; col1, col2, col3, ...</code> meaning <code>i =&gt; j1, j2, j3, ...</code> but since we need to\nlook for columns rather than rows we need to switch the usage of <code>i</code> and <code>j</code>\nwhere, for example, to access number <code>1</code> in the first array we would have the following: <code>array[i][j]</code> or <code>array[0][0]</code>\nbut in this case we have to use it as <code>array[j][i]</code> <em>(&lt;- notice that i switched them)</em>.</p>\n\n<p>Now when we have switched the index (representors?) we would get an output as this:\n<code>1,6</code> &amp; <code>2,7</code> &amp; <code>3,8</code> &amp; <code>4,9</code> &amp; <code>5,6</code></p>\n\n<p>Here is a \"GIF\" to animate the concept behind this:\n<a href=\"https://i.imgur.com/4HqLpcD.mp4\" rel=\"nofollow noreferrer\">https://i.imgur.com/4HqLpcD.mp4</a></p>\n\n<p><strong>Part 2</strong></p>\n\n<p>As you might have noticed there is a <code>counter</code> variable initialized with <code>0</code> at the very beginning of the code.\nThe purpose of this <code>counter</code> is to keep track of how many of <code>_symbol_</code> we have found while iterating of columns.</p>\n\n<p>Inside the second loop there's a code block:</p>\n\n<pre><code>if board[j][i] == symbol:\n counter += 1\nelse:\n counter = 0\n</code></pre>\n\n<p>The purpose of this part is to increase our <code>counter</code> variable by <code>1</code> if a symbol is found. if not it is re-set back to <code>0</code>.\nThis is because for someone to win, the whole column would have to be of the same symbol, let's say symbol <code>o</code>\nand if any section in the column does not match our symbol <code>o</code> then it means <code>player-o</code>\ncan not win because in order for him to win all of the sections in the current column (index <code>0</code> to <code>4</code>)\nwould have to be of the same symbol.</p>\n\n<p>When the first column has been scanned, we must check whether we have found enough symbols to call it a win or not.</p>\n\n<pre><code>if counter == len(board):\n break\n</code></pre>\n\n<p>Since our board is a square we can safely compare our counter to the length of our board.\nWhy? Because there are as many indexes(<code>0</code> to <code>4</code>) as the length(<code>5</code>) of our board.\nSo when I have filled the first column with symbol-<code>o</code> there will be exactly 5 <code>o</code>s in that column.</p>\n\n<p>When the above statement is true; main loop will break and then a boolean value is returned:</p>\n\n<pre><code>return True if counter == len(board) else False\n</code></pre>\n\n<p>As obvious as it is: When counter is equal to the length of our board <code>True</code>(won!) is returned otherwise <code>False</code> (didn't win)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:48:03.693", "Id": "408188", "Score": "0", "body": "Thank you for the advice on how to loop through the check_win. I have to admit though, looking at the code, I'm pretty confused. Can you explain the code in a bit more detail? If not, no problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:37:47.243", "Id": "408241", "Score": "0", "body": "@BobPage UPDATE: Added explanation for column checking (will add other explanations as soon as possible) btw, let me know if you have trouble understanding anything" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T07:14:11.117", "Id": "211079", "ParentId": "211067", "Score": "2" } }, { "body": "<h1>magic numbers</h1>\n\n<p>I see the value 3 (and 9) in your code when it refers to the board size. It is best to prevent such magic number, and either replace them with variables, or with constants</p>\n\n<pre><code>BOARD_SIZE = 3\n</code></pre>\n\n<h1><code>num_to_coord</code></h1>\n\n<p>you can use <code>divmod</code> to calculate the quotient and remainder of a modulo division in 1 step, so <code>num_to_coord</code> gets reduced to:</p>\n\n<pre><code>def num_to_coord(num):\n \"\"\"calculates the coordinate of a 1-indexed position number\n\n Examples\n --------\n &gt;&gt;&gt; num_to_coord(1)\n (0, 0)\n &gt;&gt;&gt; num_to_coord(3)\n (0, 2)\n &gt;&gt;&gt; num_to_coord(4)\n (1, 0)\n \"\"\"\n return divmod(num - 1, BOARD_SIZE)\n</code></pre>\n\n<p>The effect is a 90° rotation of the board</p>\n\n<h1>multi-line strings</h1>\n\n<p>Python has multiline string literals, so your welcome ca</p>\n\n<pre><code>def intro():\n welcome_message = \"\"\"\n Welcome to Tic Tac Toe\n ______________________\n You can pick location by identifying the position on the board. (There are 9 positions)\n The player who plays first will be using 'x' and the second player will be using 'o'.\n \"\"\"\n print(welcome_message)\n intro_board = \"\"\"\n |1|2|3|\n |4|5|6|\n |7|8|9|\"\"\"\n print(intro_board)\n</code></pre>\n\n<h1>State</h1>\n\n<p>to separate state and representation, I would use an <code>enum.Enum</code> to keep the state of a board position</p>\n\n<pre><code>import enum\nclass Position(enum.Enum):\n EMPTY = \" \"\n PLAYER_1 = \"x\"\n PLAYER_2 = \"o\"\n</code></pre>\n\n<p>then later on, you can define the game_board as <code>game_board = [[Position.EMPTY] * BOARD_SIZE for _ in range(BOARD_SIZE)]</code></p>\n\n<p>This allows you to check whether there are still open positions in this way:</p>\n\n<pre><code>def check_board_open(the_game_board):\n \"\"\"checks whether there are still open positions in the board\"\"\"\n return any(Position.EMPTY in row for row in the_game_board)\n</code></pre>\n\n<p>instead of having to keep a count of how many moves have been done</p>\n\n<p>and drawing the board becomes:</p>\n\n<pre><code>def format_row(row, separator=\"|\"):\n return (\n separator\n + separator.join(position.value for position in row)\n + separator\n )\n\n\ndef draw_board(the_game_board, separator=\"|\"):\n return \"\\n\".join(format_row(row, separator) for row in the_game_board)\n</code></pre>\n\n<p>In your code, you also put changed the board in the method to draw the board, which is a serious violation of the separation of concerns.</p>\n\n<h1><code>taken_positions</code></h1>\n\n<p>you define <code>taken_positions</code> as a list, but the order is unimportant, and the main goal is check for containment. A <code>set</code> is a more suited collection for this purpose.</p>\n\n<h1><code>check_position</code></h1>\n\n<pre><code>def check_position(the_position, the_taken_positions):\n if the_position in the_taken_positions:\n return True\n if the_position not in the_taken_positions:\n return False\n</code></pre>\n\n<p>can be simplified to </p>\n\n<pre><code>def check_position(the_position, the_taken_positions):\n return the_position in the_taken_positions\n</code></pre>\n\n<p>and then dropped altogether to make it inline</p>\n\n<h1>user input</h1>\n\n<p>You trust your user to input a valid number. This can be made more robust, and integrate the check whether the position is empty</p>\n\n<pre><code>class GameEnd(Exception):\n pass\n\n\ndef get_empty_position(the_game_board):\n max_position = BOARD_SIZE ** 2\n while True:\n user_input = input(f\"Enter a position [1-{max_position}]: (q to quit)\")\n if user_input.lower() == \"q\":\n raise GameEnd()\n try:\n position = int(user_input)\n if not 0 &lt; position &lt;= max_position:\n continue\n x, y = num_to_coord(position)\n if the_game_board[x][y] != Position.EMPTY:\n print(\"Position taken! Try again.\")\n continue\n return x, y\n except ValueError:\n pass\n</code></pre>\n\n<p>This keeps asking for input until a valid, empty position is given, or <code>\"q\"</code>.\nIf the user wants to end the game, this raises a <code>GameEnd</code> exception.</p>\n\n<p>You also don't need the <code>taken_positions</code>, since checking whether the position is taken is done here immediately, and directly compared to the game board instead of a second data structure.</p>\n\n<h1>Win situations</h1>\n\n<p>@feelsbadman is correct that you can decouple the different rows, columns and diagonals to check for a win condition, but I think the way he implements it can be improved. For tips on looping, check the great talk: <a href=\"https://archive.org/stream/pycon-2017-looping\" rel=\"nofollow noreferrer\">\"Looping like a Pro\"</a> (video on Youtube)</p>\n\n<p>Instead of looping over the indices, you can loop over the rows or columns, and then see whether there is a sole player in that row or column.</p>\n\n<p>To see whether there is a winner in a row, columns or diagonal, you can use this:</p>\n\n<pre><code>def get_winner(row):\n row_set = set(row)\n if len(row_set) == 1 and Position.EMPTY not in row_set:\n return row_set.pop()\n</code></pre>\n\n<p>This returns the winner if there is one, or None if there isn't</p>\n\n<pre><code>def check_win_horizontal(the_game_board):\n for row in the_game_board:\n winner = get_winner(row)\n if winner:\n return winner\n return None\n</code></pre>\n\n<p>to check vertical, you can transpose the board with <code>zip(*the_game_board)</code> so a separate vertical method is unnecessary.</p>\n\n<p>For the diagonal, you can define 2 diagonals:</p>\n\n<pre><code>diagonal1 = {the_game_board[i][i] for i in range(BOARD_SIZE)}\ndiagonal2 = {the_game_board[i][-(i + 1)] for i in range(BOARD_SIZE)}\n</code></pre>\n\n<p>and then check them like this:</p>\n\n<pre><code>def check_win_diagonal(the_game_board):\n diagonal1 = {the_game_board[i][i] for i in range(BOARD_SIZE)}\n diagonal2 = {the_game_board[i][-(i + 1)] for i in range(BOARD_SIZE)}\n winner = get_winner(diagonal1) or get_winner(diagonal2)\n return winner\n</code></pre>\n\n<p>The general method to check whether there is a winner then simply is:</p>\n\n<pre><code>def check_win(the_game_board):\n return (\n check_win_horizontal(the_game_board)\n or check_win_horizontal(zip(*the_game_board))\n or check_win_diagonal(the_game_board)\n )\n</code></pre>\n\n<h1><code>change_symbol</code></h1>\n\n<p>can be simplified to</p>\n\n<pre><code>def change_symbol(the_symbol):\n symbols = {\"x\": \"o\", \"o\": \"x\"}\n return symbols[the_symbol]\n</code></pre>\n\n<p>But this can also be done differently:</p>\n\n<p>In the <code>main</code> method, you define the players as a <code>itertools.cycle</code> of <code>(Position.PLAYER_1, Position.PLAYER_2)</code>. To get the next player, you just do <code>player = next(players)</code></p>\n\n<p>changing the board is then as simple as</p>\n\n<pre><code> x, y = get_empty_position(game_board)\n game_board[x][y] = player \n</code></pre>\n\n<h1>main</h1>\n\n<pre><code>def main():\n game_board = [[Position.EMPTY] * BOARD_SIZE for _ in range(BOARD_SIZE)]\n players = cycle((Position.PLAYER_1, Position.PLAYER_2))\n intro()\n while check_board_open(game_board):\n player = next(players)\n print(f\"Player {player.value} to move\")\n x, y = get_empty_position(game_board)\n game_board[x][y] = player\n print(draw_board(game_board))\n winner = check_win(game_board)\n if winner:\n return winner\n</code></pre>\n\n<h1>main guard</h1>\n\n<p>Best put the code that should be run as a script behind a <code>if __name__ == \"__main__\":</code> guard, so you can import this file with a minimum of side effects</p>\n\n<pre><code>def ask_retry():\n user_input = input(\"press ENTER to continue, q, then ENTER to quit\")\n return not user_input.lower() in {\"q\", \"quit\"}\n\nif __name__ == \"__main__\":\n retry = True\n while retry:\n try:\n winner = main()\n message = f\"{winner.name} won!\" if winner else \"WOW! You guys are good! DRAW!!!\"\n print(message)\n retry = ask_retry()\n except GameEnd:\n print(\"Thanks for playing! Exiting\")\n retry = False\n</code></pre>\n\n<h1>testing</h1>\n\n<p>By separating the methods like this, you can easily test them with unit tests. For code like this, which is 140 lines long, you can easily test it by hand, but if you want to incorporate changes later, like varying board sizes, a working, complete test suite will be a great help in spotting bugs. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T21:02:07.847", "Id": "408440", "Score": "0", "body": "Great stuff, going to take me a while to understand all this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T11:48:04.517", "Id": "211184", "ParentId": "211067", "Score": "4" } } ]
{ "AcceptedAnswerId": "211184", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T00:44:13.347", "Id": "211067", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "tic-tac-toe" ], "Title": "My first Python project Tic Tac Toe v2" }
211067
<p>Alright, so first, the reason I'm posting this is because I've seen so many tutorials that conflict with each other, and I would like to get this all straightened out. (Ignore the lack of shaders/mvp matrices/etc.)</p> <p>Here is my simple example code: <a href="https://pastebin.com/q2jWdVtq" rel="nofollow noreferrer">You can view it on pastebin here to make it easier to read.</a></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; #include &lt;glm.hpp&gt; #include "Logger.h" #include "GL.h" namespace engine { using Index = unsigned int; struct Vertex { glm::vec3 position; glm::vec2 texcoord; }; struct Mesh { std::vector&lt;Vertex&gt; vertices; std::vector&lt;Index&gt; indices; }; struct MeshRenderer { GLsizei count; GLuint vao; ~MeshRenderer() { // Is this the only call needed to clean up a vao? glDeleteVertexArrays(1, &amp;vao); } }; class Engine { Logger logger; MeshRenderer mr; public: Engine() : logger{"Engine"} { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glClearColor(0, 0, 0, 0); Mesh mesh; mesh.vertices.push_back({{ 0.5f, 0.5f, 0.0f}, {0.5f, 0.5f}}); mesh.indices.push_back(0); mesh.vertices.push_back({{-0.5f, 0.5f, 0.0f}, {-0.5f, 0.5f}}); mesh.indices.push_back(1); mesh.vertices.push_back({{-0.5f, -0.5f, 0.0f}, {-0.5f, -0.5f}}); mesh.indices.push_back(2); mr.count = mesh.indices.size(); // Only needed temp while binding to vao. GLuint vbo, ibo; glGenVertexArrays(1, &amp;mr.vao); // Vertex Array Object glGenBuffers(1, &amp;vbo); // Vertex Buffer Object (temp) glGenBuffers(1, &amp;ibo); // Element Buffer Object (temp) glBindVertexArray(mr.vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, mesh.vertices.size() * sizeof(Vertex), mesh.vertices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh.indices.size() * sizeof(Index), mesh.indices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast&lt;const void*&gt;(offsetof(Vertex, position))); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast&lt;const void*&gt;(offsetof(Vertex, texcoord))); glBindVertexArray(0); // Is there any reason not to clean these up now that they have been bound to the vao? glDeleteBuffers(1, &amp;vbo); glDeleteBuffers(1, &amp;ibo); } void onLoop(double time) { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(mr.vao); glDrawElements(GL_TRIANGLES, mr.count, GL_UNSIGNED_INT, nullptr); } }; } </code></pre> <p>Basically, I want to know: </p> <ol> <li>Is the VAO setup/initialization shown done correctly, or am I missing any steps or have I done anything sub optimally?</li> <li>The way I delete the VAO (<code>glDeleteVertexArrays(1, &amp;vao);</code>) is that the only call I need to do to fully delete it?</li> <li>Is it safe/good practice to delete the VBO and IBO where I do (or should I save these in until the VAO is deleted)?</li> <li>(<em>Bonus points</em>) What would be the best way to go about updating an existing mesh? For instance if I'm rendering a grid of tiles, but I want to update the texture UVs on specific vertices, what would be the best approach for something like this? (In the past I'd rebuild the mesh manually, and make a new VAO and pass it in again. Is there a way to just add/update/delete specific vertices and/or vertex attributes?)</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T01:59:19.180", "Id": "211069", "Score": "1", "Tags": [ "c++", "opengl" ], "Title": "C++ OpenGL minimal VAO example" }
211069
<p>I'm still a freshman and this one of my first projects I made using Java and Swing. </p> <p>The program is a simple League of Legends multi-threaded ping checker that pings the server 10 times to get an average ping and determine the max and minimum ranges.</p> <p>How can I make my code cleaner instead of writing so many if statements? Any suggestions or tips are greatly appreciated.</p> <p>To check your ping you can download the software <a href="https://github.com/LeoBogod22/Java-LoL-ping-checker/blob/master/selenium.jar" rel="nofollow noreferrer">here</a>.</p> <pre><code>import java.awt.Color; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import java.net.InetAddress; import java.util.GregorianCalendar; import java.util.*; import javax.swing.JProgressBar; /** * * @author User */ public class App { public static void sendPingRequest2(String ipAddress, javax.swing.JTextPane jTextPane1, javax.swing.JTextPane jTextPane2, javax.swing.JTextField jTextField1) { try { for (int i = 0; i &lt; 10; i++) { InetAddress inet = InetAddress.getByName(ipAddress); long finish = 0; long start = new GregorianCalendar().getTimeInMillis(); System.out.println("Sending Ping Request to " + ipAddress); long sum = 0; List &lt; Long &gt; list = new ArrayList &lt; &gt; (); if (inet.isReachable(5000)) { finish = new GregorianCalendar().getTimeInMillis(); long value = finish - start; list.add(value); long lowest = Collections.min(list); System.out.println("value" + lowest); sum = value + value / 10; if (value &lt; 250) { jTextPane1.setText("Ping RTT: " + value + "ms"); jTextPane2.setText("average ping: " + sum + "ms"); jTextField1.setText("" + lowest + "ms"); jTextPane1.setBackground(Color.green); jTextPane2.setForeground(Color.green); jTextField1.setBackground(Color.green); } else if (value &gt; 250 || value &lt; 500) { jTextPane1.setText("Ping RTT: " + value + "ms"); jTextPane2.setText("average ping: " + sum + "ms"); jTextField1.setText("" + lowest + "ms"); jTextPane1.setBackground(Color.yellow); jTextPane2.setBackground(Color.yellow); jTextField1.setBackground(Color.yellow); } else { jTextPane1.setText("Ping RTT: " + value + "ms"); jTextPane2.setText(" " + sum + "ms"); jTextField1.setText("" + lowest + "ms"); jTextPane1.setBackground(Color.red); jTextPane2.setBackground(Color.red); jTextField1.setBackground(Color.red); } } else { System.out.println(ipAddress + " NOT reachable."); } } } catch (Exception e) { System.out.println("Exception:" + e.getMessage()); } } public static void main(String[] args) { App m = new App(); NewJFrame jf = new NewJFrame(); } void sendPingRequest(String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } </code></pre> <p>Gui.java</p> <pre><code>package selenium; import java.net.InetAddress; import java.util.GregorianCalendar; import javax.swing.JProgressBar; import javax.swing.JTextField; /** * * @author User public class NewJFrame extends javax.swing.JFrame { * Creates new form NewJFrame */ public NewJFrame() { initComponents(); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: App m = new App(); if (jRadioButton1.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.141.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); t1.start(); } if (jRadioButton2.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.156.1", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } if (jRadioButton3.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.142.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } if (jRadioButton4.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.136.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } if (jRadioButton5.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.131.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } } private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: App m = new App(); if (jRadioButton1.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.141.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); t1.start(); } if (jRadioButton2.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.156.1", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } if (jRadioButton3.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.142.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } if (jRadioButton4.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.136.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } if (jRadioButton5.isSelected()) { Thread t1 = new Thread(new progress(jProgressBar1)); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { m.sendPingRequest2("104.160.131.3", jTextPane1, jTextPane2, jTextField1); // Insert some method call here. } }); t2.start(); } } private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } </code></pre> <p>constants.java</p> <pre><code>public enum Constants { NA ("104.160.131.3"), EUW("104.160.141.3"),EUNE("104.160.142.3"),KOR("104.160.156.1"),LAN("104.160.136.3"); private String ip; Constants(String ip){ this.ip = ip; } public String getIp(){ return ip; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T04:47:25.787", "Id": "408071", "Score": "0", "body": "Not sure whether this counts as an answer but I think there is strong reason to switch to JavaFX instead of using Swing. [See here](https://www.oracle.com/technetwork/java/javafx/overview/faq-1446554.html#6)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T04:52:28.533", "Id": "408072", "Score": "0", "body": "Also, I haven't used Swing, but it seems part of the reason you should use JavaFX is that it better supports the MVC paradigm. In particular, you can utilize FXML/CSS to design the UI and let the logic be controlled in Java. This isn't particularly in depth since I don't do much Java development, but the general rule of thumb for GUI applications is to *not* write static UIs in Java/C/etc. and use a markup-esque language to do so instead." } ]
[ { "body": "<p>In no particular order:</p>\n\n<ul>\n<li><p><strong>Trust the math</strong>. When you test for <code>value &gt; 250 || value &lt; 500</code> you already <em>know</em> that <code>value</code> is greater than 250 (otherwise, the code would go into <code>if</code> clause). Testing for <code>value &lt; 500</code> suffices.</p>\n\n<p>BTW, what a background color would be if <code>value</code> is exactly 250?</p></li>\n<li><p><strong>DRY #1</strong>. The block of code</p>\n\n<pre><code> jTextPane1.setText(\"Ping RTT: \" + value + \"ms\");\n jTextPane2.setText(\"average ping: \" + sum + \"ms\");\n jTextField1.setText(\"\" + lowest + \"ms\");\n jTextPane1.setBackground(Color.green);\n jTextPane2.setForeground(Color.green);\n jTextField1.setBackground(Color.green);\n</code></pre>\n\n<p>is repeated thrice. The only difference is <code>Color</code> value. Assign it in the <code>if</code>s, and factor the rest out:</p>\n\n<pre><code> if (value &lt; 250) {\n color = Color.green;\n } else if (value &lt; 500) {\n color = Color.yellow;\n } else {\n color = Color.red;\n }\n\n jTextPane1.setText(\"Ping RTT: \" + value + \"ms\");\n jTextPane2.setText(\"average ping: \" + sum + \"ms\");\n jTextField1.setText(\"\" + lowest + \"ms\");\n jTextPane1.setBackground(color);\n jTextPane2.setForeground(color);\n jTextField1.setBackground(color);\n</code></pre></li>\n<li><p><strong>DRY #2</strong>. Ditto for <code>if (jRadioButtonX.isSelected())</code> cases. The only difference is the IP you are going to ping. Associate the IP with the button, and use the same <code>actionPerformed</code> for each of them.</p>\n\n<p>Speaking of which, why <code>jRadioButton1.isSelected()</code> case calls <code>t1.start()</code> twice?</p></li>\n<li><p>It feels creepy that <code>jButton1ActionPerformed</code> creates <code>new App()</code>. An <code>App</code> should be created once. I am afraid there is a big design problem here.</p></li>\n<li><p><strong><code>sum = value + value / 10</code></strong> is very much a mistake. Even <code>sum = sum + value / 10</code> does not compute the correct average.</p></li>\n<li><p>I see reporting the (incorrect) average, and the min time. I don't see reporting <em>max</em> time.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T20:13:40.890", "Id": "408201", "Score": "0", "body": "what exactly is the design problem and how can i fix it ? can you please explain in more details? i was trying to call the method when you click the button" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T06:44:35.823", "Id": "211078", "ParentId": "211070", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T02:26:24.793", "Id": "211070", "Score": "2", "Tags": [ "java", "multithreading", "swing", "networking", "benchmarking" ], "Title": "Java League of Legends ping checker" }
211070
<p>I have an implementation for my first binary search tree in C++. I was wondering if there was some cleaner way to avoid using the double pointer in the way I have my code setup? Such as on one line I have:</p> <pre><code>(*node)-&gt;left = insert(&amp;((*node)-&gt;left),value); </code></pre> <p>Which seems a bit "messy", but it almost seems necessary for the way I have implemented the BST. Maybe I am possibly missing a way I can change the syntax slightly to achieve the same result? I understand that I can have a double pointer as a parameter for my functions, but I have been told that it is not the standard in C++. I have my code posted below, along with how I am testing it.I am trying to prepare for technical interviews so any feedback is welcome. </p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;iostream&gt; struct Node { int data; Node *left, *right; }; // A utility function to create a new BST node Node* newNode(int data) { Node *temp = new Node(); temp-&gt;data = data; temp-&gt;left = NULL; temp-&gt;right = NULL; return temp; } // A utility function to do inorder traversal of BST void inorder(Node **root) { if (*root != NULL) { inorder(&amp;((*root)-&gt;left)); printf("%d \n", (*root)-&gt;data); inorder(&amp;((*root)-&gt;right)); } } /* A utility function to insert a new node with given key in BST */ Node* insert(Node** node, int value) { if(*node==NULL){ return newNode(value); } if((*node)-&gt;data &gt; value){ (*node)-&gt;left = insert(&amp;((*node)-&gt;left),value); } else if((*node)-&gt;data &lt; value){ (*node)-&gt;right = insert(&amp;((*node)-&gt;right),value); } return *node; } // Driver Program to test above functions int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(&amp;root, 50); insert(&amp;root, 30); insert(&amp;root, 20); insert(&amp;root, 40); insert(&amp;root, 70); insert(&amp;root, 60); insert(&amp;root, 80); // print inoder traversal of the BST inorder(&amp;root); return 0; } </code></pre> <p><strong>EDIT</strong>: By changing " ** " in the parameters of the function to "*&amp;" was able to make code much easier to read, with the same functionality. </p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;iostream&gt; struct Node { int data; Node *left, *right; }; // A utility function to create a new BST node Node* newNode(int data) { Node *temp = new Node(); temp-&gt;data = data; temp-&gt;left = NULL; temp-&gt;right = NULL; return temp; } // A utility function to do inorder traversal of BST void inorder(Node *&amp;root) { if (root != NULL) { inorder(((root)-&gt;left)); printf("%d \n", (root)-&gt;data); inorder(((root)-&gt;right)); } } /* A utility function to insert a new node with given key in BST */ Node* insert(Node*&amp; node, int value) { if(node==NULL){ return newNode(value); } if((node)-&gt;data &gt; value){ node-&gt;left = insert(((node)-&gt;left),value); } else if((node)-&gt;data &lt; value){ (node)-&gt;right = insert(((node)-&gt;right),value); } return node; } // Driver Program to test above functions int main() { /* following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // print inoder traversal of the BST inorder(root); return 0; } </code></pre>
[]
[ { "body": "<p>If you're trying to learn C++, you should get comfortable with constructors and destructors — they're what C++ is all about!</p>\n\n<pre><code>struct Node \n{ \n int data; \n Node *left, *right; \n}; \n\n// A utility function to create a new BST node \nNode* newNode(int data) \n{ \n Node *temp = new Node(); \n temp-&gt;data = data; \n temp-&gt;left = NULL; \n temp-&gt;right = NULL; \n return temp; \n}\n</code></pre>\n\n<p>That's C style. C++ style would be:</p>\n\n<pre><code>struct Node { \n int data_; \n Node *left_ = nullptr;\n Node *right_ = nullptr;\n\n explicit Node(int data) : data_(data) {}\n}; \n</code></pre>\n\n<p>Then when you want a new heap-allocated node, you don't call <code>newNode(42)</code> — you call <code>new Node(42)</code>! Or, a good habit you should get into: call <code>std::make_unique&lt;Node&gt;(42)</code> to get back a <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\">smart pointer</a>.</p>\n\n<p>Notice that I added sigils to your data members (<code>data_</code> etc) to distinguish them from non-member variables; and I declared no more than one variable per line to reduce reader confusion.</p>\n\n<hr>\n\n<pre><code>void inorder(Node *&amp;root) \n{ \n if (root != NULL) \n { \n inorder(((root)-&gt;left)); \n printf(\"%d \\n\", (root)-&gt;data); \n inorder(((root)-&gt;right)); \n } \n}\n</code></pre>\n\n<p>Several things weird here. First, you have a bunch of unnecessary parentheses. <code>(root)</code> is the same thing as <code>root</code>. Second, you're passing <code>root</code> by <em>non-const reference</em>, even though you don't intend to modify it. Third, very minor nit, you're using C-style <code>NULL</code> instead of <code>nullptr</code>. Fourth, why do you print a space before the newline? Fixed up:</p>\n\n<pre><code>void inorder(const Node *root)\n{\n if (root != nullptr) {\n inorder(root-&gt;left); \n printf(\"%d\\n\", root-&gt;data); \n inorder(root-&gt;right); \n } \n}\n</code></pre>\n\n<p>Remember to remove the redundant parentheses in places like <code>insert(((node)-&gt;right),value)</code>. It's much easier to read as <code>insert(node-&gt;right, value)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:40:29.197", "Id": "408079", "Score": "0", "body": "Yeah the unnecessary parentheses came from when I was editing from the previous solution. Also, surprisingly was not aware of putting a constructor / destructor into the struct, thanks for pointing that out to me. Much needed feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:50:53.640", "Id": "408109", "Score": "1", "body": "Actually, leaving `Node` without *any* user-declared ctors and functions is much better: It **doesn't have any invariants**, as much as anyone might pretend, and they only get in the way of implementing the list efficiently and correctly, which *does*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:53:15.660", "Id": "408110", "Score": "1", "body": "@Deduplicator \"A node always has the data set\" is quite obviously a (very simple) invariant which the constructor nicely enforces. And in what way does it make the implementation harder?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:56:34.197", "Id": "408113", "Score": "0", "body": "@Voo Well, first I would always put the links first. Then, a new `Node` is created with `new Node{nullptr, nullptr, {args...}}`, irrespective what `{args...}` is, even a function-call, and whether the data-type can be copied, moved, or only in-place-constructed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:26:56.477", "Id": "408129", "Score": "1", "body": "@Deduplicator Wouldn't that work just as well with a constructor if you use the right signature?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:57:41.077", "Id": "408130", "Score": "0", "body": "@Voo Then you need a variadic-template forwarding-constructor. A lot of boilerplate for no use, imho, especially as aggregate-initialisation already works. Also, iif you have at least one layer of forwarding the function-call cannot create the return-value directly at the target, though you will probably have that anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:14:40.237", "Id": "408143", "Score": "1", "body": "@Deduplicator is wrong: Providing a constructor is obviously correct (especially for this programmer's level of expertise). Besides the \"Node's data is always set\" invariant, there are at least two more: \"Node's left pointer is always initialized (never garbage)\" and \"Node's right pointer is always initialized (never garbage).\" If `Node` were an internal implementation detail of some larger `List` type, then making it a POD struct might be a reasonable optimization; but remember that correctness trumps _premature_ optimization. (That said, Deduplicator's _answer_ deserves more upvotes. :))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T00:15:05.040", "Id": "409861", "Score": "0", "body": "@Quuxplusone Also, why the use of \"explicit\" before the constructor in the struct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T00:35:23.377", "Id": "409863", "Score": "0", "body": "@Pulse: The keyword `explicit` should go on *every* constructor and conversion operator in your programs, unless you want to enable an implicit conversion (in this case, from `int` to `Node`). Implicit conversions are sometimes useful (e.g. from `const char *` to `std::string`) but vastly more often are a source of surprising behavior and bugs." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T04:39:45.630", "Id": "211073", "ParentId": "211072", "Score": "9" } }, { "body": "<ol>\n<li><p>I would have expected an empty line between your includes and the declaration of <code>Node</code>.</p></li>\n<li><p>You seem inordinately fond of having extra-whitespace at the end of lines. Loose it, both in the code and in the output, as it at best irritates co-workers and diff.</p></li>\n<li><p>Consider using smartpointers, specifically <code>std::unique_ptr</code> for the link- and root-pointer. That way, you won't leak your tree. Admittedly, not freeing might be an intentional optimisation for faster shutdown, but that seems unlikely.<br>\n<a href=\"https://www.youtube.com/watch?v=JfmTagWcqoE&amp;t=15m57s\" rel=\"nofollow noreferrer\">Yes, you have as much recursion as in <code>inorder()</code>, using an explicit stack could avoid that. Or much more iteration. Or having back-pointers. Or a custom area-allocator.</a></p></li>\n<li><p>As a matter of course, I would always put the links first in any kind of node-class.</p></li>\n<li><p><code>newNode</code> is very expansively written, and if the value_type isn't trivially constructible, might not be optimisable by the compiler from initialisation+assignment for all members to just initialisation. Why ask it to?</p>\n\n<pre><code>Node* newNode(int value) {\n return new Node{value};\n // Or if you move the links: `new Node{nullptr, nullptr, value}`\n // With C++20: `new Node{.data = value}`\n}\n</code></pre>\n\n<p>That can easily be used for non-copyable, non-movable, and even only in-place-constructible types.</p></li>\n<li><p>Prefer <code>nullptr</code> for nullpointer-constants, if you actually need one. That is more type-safe, and sometimes enables additional optimisations.</p></li>\n<li><p>Try to take advantage of references to simplify calling your functions.</p></li>\n<li><p><code>insert()</code> drops any duplicate values. Is that intentional? If so, that needs to be called out in a comment, or made more obvious from the code-structure!</p></li>\n<li><p><code>insert()</code> has no need to recurse:</p>\n\n<pre><code>void insert(Node* &amp;root, int value) {\n auto p = &amp;root;\n while (*p &amp;&amp; p[0]-&gt;data != value)\n p = p[0]-&gt;data &gt; value ? &amp;p[0]-&gt;left : &amp;p[0]-&gt;right;\n if (!*p)\n *p = newNode(value);\n}\n</code></pre></li>\n<li><p><code>inorder()</code> only needs to know the root-node, not where the pointer to it is saved. Also, it never modifies anything. Thus, it should accept <code>Node const*</code> or <code>Node const&amp;</code>.</p></li>\n<li><p><code>inorder()</code> cannot throw by design, so mark it <code>noexcept</code>.</p></li>\n<li><p>Try to minimize the level of indentation. Guards at the start of a function are quite idiomatic.</p></li>\n<li><p>What does <code>inorder()</code> do in order? Ah, printing. So, why not call it <code>print_inorder()</code>?</p>\n\n<pre><code>void print_inorder(const Node *root) noexcept {\n if (!root)\n return;\n print_inorder(root-&gt;left);\n printf(\"%d\\n\", root-&gt;data);\n print_inorder(root-&gt;right);\n}\n</code></pre></li>\n<li><p>Some would suggest favoring iostreams over stdio for added type-safety, but there are downsides for that too.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>.</p></li>\n<li><p>Naturally, for any further use you would want to wrap your data-structure in its own class-template with members for observing, modifying, iterating, and ctors / dtor for enforcing the invariants and manage the resources. But ensuring full re-usability is probably far out-of-scope at the moment.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:20:56.933", "Id": "408144", "Score": "1", "body": "On #3, I think it's worth mentioning that if you use `unique_ptr` for the links, then [the destructor of `Node` becomes recursive](https://www.youtube.com/watch?v=JfmTagWcqoE&t=15m57s), which means it's probably not a good idea for real code (but is still a good suggestion for OP to think about and understand how it'd work)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:14:36.543", "Id": "408196", "Score": "2", "body": "The ` extra-whitespace at the end of lines` This is more important than it looks (it feels trivial but I agree with deduplicator that it is important). People specifically set their editors to show extra white space at then end of lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:27:46.427", "Id": "408197", "Score": "0", "body": "Relying on the order of members in such an implicit and hidden way for #3 strikes me as an awful, awful maintenance burden for very little benefit. Using the c++20 syntax is fine though (that one's really only in c++20? I guess before it was just a really popular extension?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T20:27:00.430", "Id": "408203", "Score": "0", "body": "@Voo Yes, it's a popular extension and C got it earlier with C99." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T22:13:04.507", "Id": "408219", "Score": "0", "body": "@Deduplicator Yeah I know that C had it for years, I just assumed C++ would've gotten it around c++11 or possibly 14 as well. Well, better late than never." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:52:42.173", "Id": "211104", "ParentId": "211072", "Score": "5" } }, { "body": "<p>In insert, You don't need to both catch the value (i.e. <code>((*node)-&gt;left = insert(&amp;((*node)-&gt;left),value);</code>) returned AND pass the pointers by reference (i.e. double pointers). That is redundant. Choose one or the other.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T21:16:31.740", "Id": "253001", "ParentId": "211072", "Score": "2" } } ]
{ "AcceptedAnswerId": "211073", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T02:44:14.597", "Id": "211072", "Score": "7", "Tags": [ "c++", "algorithm", "binary-search" ], "Title": "Cleaner way to handle double pointer in C++ BST?" }
211072
<p>I am an experienced developer but pretty new to React. I wanted to go on my own and build a simple little weather app that updates the image, tempature, and description of each day when you click on the + or - buttons.</p> <p>I got it to work but I think it is pretty messy and was hoping for some advice. Firstly, is it bad practice to create a state on a component from props passed in by its parent? I know I could set the values within the state but just decided to keep it the way i designed it initially (at first WeatherCard was a stateless component so i was pulling in props either way). However, I could only imagine that there would be a couple instances that this would be applicable...?</p> <p>Also, I ran into a problem with injecting images, I was trying to use</p> <pre><code>&lt;img src={'./folder/image.extension'}&gt; </code></pre> <p>and then update the src but couldn't figure out how to do that, so I made the function getImage() to help me out. Is there a way you guys can think of to update the src of the image so I can get rid of getImage() and just update the state to a string (file path) that the src pulls from?</p> <p>Lastly I am really baffled about how the description was reacting. The description would update at a different time than the image, which was not what I was expecting. If you look at the code you will see that I had to adjust the if statements in handleClick to a -1 and a +1 to make up for some kind of what seemed to be like a delay. I don't really understand the issue here, but thats how I compensated for it. What are your guys' thoughts?</p> <p>Overall, I know this is probably some pretty junk code here but I intend on improving it. Will probably start from scratch and maybe it will go better for me but hoping for some advice!</p> <hr> <h3>WeatherCard.js</h3> <pre><code>import React, { Component } from 'react'; import sunny from '../img/sunny.png'; import partly from '../img/partly.png'; import cloudy from '../img/cloudy.png'; import rainy from '../img/rainy.png'; class WeatherCard extends Component { state = { day: this.props.data.day, temp: this.props.data.temp, description: this.props.data.description } getImage = () =&gt; { if (this.state.temp &gt;= 95 ) { return &lt;img src={ sunny } alt="sunny"&gt;&lt;/img&gt; } else if (this.state.temp &gt;= 85) { return &lt;img src={ partly } alt="partly cloudy"&gt;&lt;/img&gt; } else if (this.state.temp &gt;= 75) { return &lt;img src={ cloudy } alt="cloudy"&gt;&lt;/img&gt; } else { return &lt;img src={ rainy } alt="rainy"&gt;&lt;/img&gt; } } handleClick = (e) =&gt; { if (e.target.innerHTML === '+') { this.setState(function(prevState, props){ if (this.state.temp &gt;= 94) { return {description: 'Sunny'} } else if (this.state.temp &gt;= 84) { return {description: 'Partly Cloudy'} } else if (this.state.temp &gt;= 74) { return {description: 'Cloudy'} } else { return {description: 'Rainy'} } }); this.setState ({ temp: (this.state.temp+1) }); } else { this.setState(function(prevState, props){ if (this.state.temp &gt;= 96) { return {description: 'Sunny'} } else if (this.state.temp &gt;= 86) { return {description: 'Partly Cloudy'} } else if (this.state.temp &gt;= 76) { return {description: 'Cloudy'} } else { return {description: 'Rainy'} } }); this.setState ({ temp: (this.state.temp-1) }); } } render() { return ( &lt;div className="card"&gt; &lt;div className="card-head"&gt;{ this.state.day }&lt;/div&gt; &lt;div className="card-body"&gt; &lt;h1&gt;{ this.state.temp }&lt;/h1&gt; { this.getImage() } &lt;p&gt;{ this.state.description }&lt;/p&gt; &lt;/div&gt; &lt;div className="controls"&gt; &lt;div className="upButton" onClick={ this.handleClick }&gt;+&lt;/div&gt; &lt;div className="downButton" onClick={ this.handleClick }&gt;-&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } } export default WeatherCard; </code></pre> <hr> <h3>App.js</h3> <pre><code>import React, { Component } from 'react'; import WeatherCard from './components/WeatherCard'; class App extends Component { state = { data : [ { day : 'Monday', temp : 100, description : 'Sunny' }, { day : 'Tuesday', temp : 100, description : 'Sunny' }, { day : 'Wednesday', temp : 100, description : 'Sunny' }, { day : 'Thursday', temp : 100, description : 'Sunny' }, { day : 'Friday', temp : 100, description : 'Sunny' }, { day : 'Saturday', temp : 100, description : 'Sunny' }, { day : 'Sunday', temp : 100, description : 'Sunny' } ] } renderCards = () =&gt; { return this.state.data.map((card, i) =&gt; &lt;WeatherCard key = {i} data = {this.state.data[i]}&gt;&lt;/WeatherCard&gt;) } render() { return ( &lt;div className="App"&gt; &lt;div className="cards"&gt; { this.renderCards() } &lt;/div&gt; &lt;/div&gt; ); } } export default App; </code></pre>
[]
[ { "body": "<p><strong>The initial data</strong></p>\n\n<p>Since every day shares the exact same default temperature, repeating it would be useless, you can instead map a list of days and create a JSON for each element using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">map</a>.</p>\n\n<p>The description should also be removed from your data, since it entirely depends on the temperature, there is no reason to store both <code>temp</code> and <code>description</code>.</p>\n\n<pre><code>this.state = {\n data: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',].map(day =&gt; ({\n day,\n temp: 100\n }))\n}\n</code></pre>\n\n<p><strong>Setting your initial state</strong></p>\n\n<p>The React documentation recommends using a class contructor instead of setting your state raw into your class. This solution may wokr for now, but it can cause unexpected behavior on the long term.</p>\n\n<pre><code>constructor(props) {\n super(props)\n\n this.state = {\n data: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',].map(day =&gt; ({\n day,\n temp: 100\n }))\n }\n}\n</code></pre>\n\n<p><strong>Getting the description and image</strong></p>\n\n<p>Having blocks of <code>if/else</code> nested statements is almost never necessary when using JSON objects. Just create an array containing every possible description/image combination and which temperature it represent.</p>\n\n<p>When done, use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\">find</a> function to get get the corresponding description/image. This function will execute a verification (<code>weather =&gt; temp &gt;= weather.value</code>) on every JSON of list until it finds a correct one, here, the first JSON that has a value lower than the given temperature.</p>\n\n<p>Code :</p>\n\n<pre><code>getInfos = temp =&gt; {\n return [\n {\n value: 95,\n description: 'Sunny',\n image: sunny\n },\n {\n value: 85,\n description: 'Partly Cloudy',\n image: partly\n },\n {\n value: 75,\n description: 'Cloudy',\n image: cloudy\n },\n {\n value: -Infinity,\n description: 'Rainy',\n image: rainy\n },\n ].find(weather =&gt; temp &gt;= weather.value)\n}\n</code></pre>\n\n<p><strong>Changing the temperature</strong></p>\n\n<p>To change your temperature, simply add a parameter saying by how much you want to vary it :</p>\n\n<pre><code>&lt;div className=\"upButton\" onClick={this.changeTemp(1)}&gt;+&lt;/div&gt;\n&lt;div className=\"downButton\" onClick={this.changeTemp(-1)}&gt;-&lt;/div&gt;\n</code></pre>\n\n<p>Then, make a function that receives both this parameter and the click event (even if you're not using it). this function should also update the information about the image and the description using <code>getInfos</code>: </p>\n\n<pre><code>changeTemp = value =&gt; ev =&gt; {\n this.setState(prevState =&gt; ({ \n temp: prevState.temp + value,\n ...this.getInfos(prevState.temp + value)\n }))\n}\n</code></pre>\n\n<p>Full code :</p>\n\n<pre><code>class App extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n data: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',].map(day =&gt; ({\n day,\n temp: 100\n }))\n }\n }\n\n cardClicked = card =&gt; event =&gt; {\n this.setState({ data })\n }\n\n render() {\n return (\n &lt;div className=\"App\"&gt;\n &lt;div className=\"cards\"&gt;\n {this.state.data.map(card =&gt; &lt;WeatherCard key={card.day} data={card}&gt;&lt;/WeatherCard&gt;)}\n &lt;/div&gt;\n &lt;/div&gt;\n );\n }\n}\n\nimport sunny from '../img/sunny.png';\nimport partly from '../img/partly.png';\nimport cloudy from '../img/cloudy.png';\nimport rainy from '../img/rainy.png';\n\nclass WeatherCard extends React.Component {\n constructor(props) {\n super(props)\n\n const { temp } = props\n\n this.state = {\n temp\n }\n\n getInfos(temp)\n }\n\n getInfos = temp =&gt; {\n return [\n {\n value: 95,\n description: 'Sunny',\n image: sunny\n },\n {\n value: 85,\n description: 'Partly Cloudy',\n image: partly\n },\n {\n value: 75,\n description: 'Cloudy',\n image: cloudy\n },\n {\n value: -Infinity,\n description: 'Rainy',\n image: rainy\n },\n ].find(weather =&gt; temp &gt;= weather.value)\n }\n\n changeTemp = value =&gt; ev =&gt; {\n this.setState(prevState =&gt; ({ \n temp: prevState.temp + value,\n ...this.getInfos(prevState.temp + value)\n }))\n }\n\n render() {\n const { day } = this.props\n const { temp, image, description } = this.state\n\n return (\n &lt;div className=\"card\"&gt;\n &lt;div className=\"card-head\"&gt;{day}&lt;/div&gt;\n &lt;div className=\"card-body\"&gt;\n &lt;h1&gt;{temp}&lt;/h1&gt;\n &lt;img src={image} alt={description}&gt;&lt;/img&gt;\n &lt;p&gt;{description}&lt;/p&gt;\n &lt;/div&gt;\n &lt;div className=\"controls\"&gt;\n &lt;div className=\"upButton\" onClick={this.changeTemp(1)}&gt;+&lt;/div&gt;\n &lt;div className=\"downButton\" onClick={this.changeTemp(-1)}&gt;-&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n )\n }\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT :</p>\n\n<p>Here's an even shorter version of your <code>getInfos</code> function using array deconstruction, just because :</p>\n\n<pre><code>getInfos = temp =&gt; \n [ \n [95, 'Sunny', sunny],\n [85, 'Partly Cloudy', partly],\n [75, 'Cloudy', cloudy],\n [-Infinity, 'Rainy', rainy]\n ].find(([value]) =&gt; temp &gt;= value)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T06:20:07.337", "Id": "408262", "Score": "0", "body": "There were a couple bugs in what you gave me but overall this is just what I was looking for. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:55:53.367", "Id": "408298", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I do not understand how a Map will help us in that case. Since every result is a temperature range and not just : `95`. Can you show me your solution ?\n\n@user3158670 Sorry, the code is partly not tested, I hope the explanation made it up for you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:50:06.687", "Id": "408435", "Score": "0", "body": "ah nuts... I just scanned the filter function and believed I saw an equals sign. nevermind :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T10:52:57.777", "Id": "408886", "Score": "0", "body": "I made the `getInfos` function even shorter if you are interested ;)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T11:21:11.363", "Id": "211092", "ParentId": "211086", "Score": "1" } }, { "body": "<p>Here is the working code</p>\n\n<p>--- App.js ---</p>\n\n<pre><code>import React, { Component } from 'react';\nimport WeatherCard from './components/WeatherCard';\n\nclass App extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n data: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',].map((day, i) =&gt; ({\n day,\n temp: (100 - (i*10))\n }))\n }\n }\n\n render() {\n return (\n &lt;div className=\"App\"&gt;\n &lt;div className=\"cards\"&gt;\n {this.state.data.map(card =&gt; &lt;WeatherCard key={card.day} data={card}&gt;&lt;/WeatherCard&gt;)}\n &lt;/div&gt;\n &lt;/div&gt;\n );\n }\n}\nexport default App;\n</code></pre>\n\n<p>--- WeatherCard.js ---</p>\n\n<pre><code>import sunny from '../img/sunny.png';\nimport partly from '../img/partly.png';\nimport cloudy from '../img/cloudy.png';\nimport rainy from '../img/rainy.png';\n\nimport React, { Component } from 'react';\n\nclass WeatherCard extends React.Component {\n constructor(props) {\n super(props)\n\n const { day, temp } = props.data\n\n this.state = {\n day,\n temp,\n ...this.getData(temp)\n }\n }\n\n getData = temp =&gt; {\n return [\n {\n value: 95,\n description: 'Sunny',\n image: sunny\n },\n {\n value: 85,\n description: 'Partly Cloudy',\n image: partly\n },\n {\n value: 75,\n description: 'Cloudy',\n image: cloudy\n },\n {\n value: -Infinity,\n description: 'Rainy',\n image: rainy\n },\n ].find(weather =&gt; temp &gt;= weather.value)\n }\n\n changeTemp = value =&gt; ev =&gt; {\n this.setState(prevState =&gt; ({ \n temp: prevState.temp + value,\n ...this.getData(prevState.temp + value)\n }))\n }\n\n render() {\n const { day } = this.props.data\n const { temp, image, description } = this.state\n\n return (\n &lt;div className=\"card\"&gt;\n &lt;div className=\"card-head\"&gt;{day}&lt;/div&gt;\n &lt;div className=\"card-body\"&gt;\n &lt;h1&gt;{temp}&lt;/h1&gt;\n &lt;img src={image} alt={description}&gt;&lt;/img&gt;\n &lt;p&gt;{description}&lt;/p&gt;\n &lt;/div&gt;\n &lt;div className=\"controls\"&gt;\n &lt;div className=\"upButton\" onClick={this.changeTemp(1)}&gt;+&lt;/div&gt;\n &lt;div className=\"downButton\" onClick={this.changeTemp(-1)}&gt;-&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n )\n }\n}\n\nexport default WeatherCard;\n</code></pre>\n\n<p>If I remember correctly I think the biggest issues with what you provided (@Treycos) were reference bugs ('this' not placed where it should have been) - etc. But some really good stuff you provided, thanks again!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:39:34.883", "Id": "211177", "ParentId": "211086", "Score": "0" } } ]
{ "AcceptedAnswerId": "211092", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T09:47:16.690", "Id": "211086", "Score": "3", "Tags": [ "html", "react.js", "jsx" ], "Title": "React-based weather app" }
211086
<p>I've the following d3 chart which is both grouped and each grouped contains a stacked bar. But somehow, I feel this is not a proper way to implement and little complicated. If there was only stacked bar chart, I would have used <code>d3.stack()</code>. Is there anyway I can still use the <code>d3.stack()</code> with current setup. Can someone let me know is there any better way to do this?</p> <p>Snippet as follows</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 data = [ { Category: "cat1", type1: 300, type2: 450, type3: 120 }, { Category: "cat2", type1: 400, type2: 100, type3: 200 }, { Category: "cat3", type1: 400, type2: 100, type3: 200 }, { Category: "cat4", type1: 400, type2: 100, type3: 200 } ]; var margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = 500 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var barWidth = 40; var x0 = d3.scaleBand().range([0, width]); var x1 = d3.scaleBand(); var y = d3.scaleLinear().range([height, 0]); var xAxis = d3.axisBottom(x0); var yAxis = d3.axisLeft(y).tickFormat(d3.format(".2s")); var color = d3.scaleOrdinal().range(["#98abc5", "#8a89a6", "#7b6888"]); var svg = d3 .select("body") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var yBegin; var innerColumns = { column1: ["type1", "type2"], column2: ["type3"] }; var columnHeaders = d3.keys(data[0]).filter(function(key) { return key !== "Category"; }); color.domain( d3.keys(data[0]).filter(function(key) { return key !== "Category"; }) ); var groupData = data.forEach(function(d) { var yColumn = new Array(); d.columnDetails = columnHeaders.map(function(name) { for (ic in innerColumns) { if (innerColumns[ic].indexOf(name) &gt;= 0) { if (!yColumn[ic]) { yColumn[ic] = 0; } yBegin = yColumn[ic]; yColumn[ic] += +d[name]; return { name: name, column: ic, yBegin: yBegin, yEnd: +d[name] + yBegin }; } } }); d.total = d3.max(d.columnDetails, function(d) { return d.yEnd; }); }); //console.log(data); x0.domain( data.map(function(d) { return d.Category; }) ); x1.domain(d3.keys(innerColumns)).range([0, x0.bandwidth()]); y.domain([ 0, 1.15 * d3.max(data, function(d) { return d.total; }) ]); svg .append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg .append("g") .attr("class", "y axis") .call(yAxis); var stackedbar = svg .selectAll(".stackedbar") .data(data) .enter() .append("g") .attr("class", "g") .attr("transform", function(d) { return "translate(" + x0(d.Category) + ",0)"; }); stackedbar .selectAll("rect") .data(function(d) { return d.columnDetails; }) .enter() .append("rect") .attr("width", barWidth) .attr("x", function(d) { return x1(d.column) + (x1.bandwidth() - barWidth) / 2; }) .attr("y", function(d) { return y(d.yEnd); }) .attr("height", function(d) { return y(d.yBegin) - y(d.yEnd); }) .style("fill", function(d) { return color(d.name); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: steelblue; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.6.0/d3.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T09:50:06.180", "Id": "211087", "Score": "2", "Tags": [ "javascript", "d3.js", "svg" ], "Title": "Grouped stacked bar chart in d3js" }
211087
<p>I just study Python, and have finished my first personal challenge game Tetris. It has multi-game, bindable keys, customizable game field. It would be great to have review/feedback on it. <a href="https://github.com/vberd/different/blob/master/tetris.py" rel="nofollow noreferrer">https://github.com/vberd/different/blob/master/tetris.py</a></p> <pre><code>import pygame from random import choice, randint class Field: def __init__(self, start_y, hi_score=0): self.field = [[0] * (width + 2) for i in range(height + 2)] self.score = self.score_plus = self.score_up = 0 self.hiscore = hi_score self.k = self.lines = 0 self.start_x, self.start_y = cell_size, start_y self.game = False self.figure_last_x = self.figure_last_y = 0 def draw(self): for i in range(2, height + 2): for j in range(1, width + 1): if self.field[i][j]: GameWindow.draw_cell('red', self.start_y, 0, 0, i, j) def add_figure(self, figure): for i in range(len(figure.figure)): for j in range(len(figure.figure[i])): if figure.figure[i][j]: self.field[i + figure.x][j + figure.y] = 1 def check_line(self): self.score_up = 0 self.k = 0 for i in range(2, height + 2): if 0 not in self.field[i]: self.field.pop(i) self.field.insert(2, ([1] + [0] * width + [1])) self.k += 1 self.lines += 1 self.figure_last_x = i self.score_plus = 100 * (self.k ** 2 - (self.k - 1) ** 2) + 25 * (height - i + 1) self.score_up += self.score_plus self.score += self.score_plus self.hiscore = max(self.hiscore, self.score) def restart(self): self.game = True self.field = [[1] * (width // 2 - 1) + [0] * 4 + [1] * (width // 2 - 1 + width % 2)] * 2 + \ [([1] + [0] * width + [1]) for i in range(height)] + \ [[1] * (width + 2)] self.lines = self.score = 0 class Figure: def __init__(self, start_y, field): self.x = 0 self.y = width // 2 - 1 self.press_down = False self.start_x, self.start_y = cell_size, start_y self.figure = '' self.next_figure = self.new_figure() self.field = field self.auto_down_speed = 1000 def draw(self): for i in range(len(self.figure)): for j in range(len(self.figure[i])): if self.figure[i][j] and (((self.x + i - 1) * cell_size) &gt; 0): GameWindow.draw_cell('black', self.start_y, self.x, self.y, i, j) def can_move(self, side): new_x = self.x new_y = self.y if side == "d": new_x += 1 elif side == "l": new_y -= 1 elif side == "r": new_y += 1 for i in range(len(self.figure)): for j in range(len(self.figure[i])): if self.figure[i][j] and self.field.field[new_x + i][new_y + j]: return False return True def move_down(self): self.x += 1 def move_left(self): self.y -= 1 def move_right(self): self.y += 1 def rotate(self, n=1): for i in range(n): self.figure = list(zip(*reversed(self.figure))) def can_rotate(self): new_form = list(zip(*reversed(self.figure))) for i in range(len(new_form)): for j in range(len(new_form[i])): if new_form[i][j] and self.field.field[self.x + i][self.y + j]: return False return True def new_figure(self): self.next_figure = choice(list(figures.values())) for i in range(randint(1, 4)): self.next_figure = list(zip(*reversed(self.next_figure))) return self.next_figure def move_figure(self, game): if not game.pressed_button: self.auto_down_speed = int(0.66 ** (self.field.score // div) * 1000) pygame.time.set_timer(game.AUTODOWN, self.auto_down_speed) if self.can_move("d"): self.move_down() else: self.field.figure_last_y = self.y self.field.add_figure(self) self.field.check_line() self.figure = self.next_figure self.x = 0 self.y = width // 2 - 1 self.new_figure() self.game_over() def game_over(self): global PAUSE, n_t for i in range(len(self.figure)): for j in range(len(self.figure[i])): if self.figure[i][j] and self.field.field[self.x + i][self.y + j]: self.field.game = False PAUSE = True n_t = 0 def restart(self): self.auto_down_speed = 1000 self.x = 0 self.y = width // 2 - 1 self.figure = self.new_figure() class GameWindow: def __init__(self, field, figure, autodown): self.field = field self.menu_left_line = int((width + 2.5) * cell_size + field.start_y) self.score_sum = pygame.font.SysFont(font, cell_size, 1).render('0' * 6, 1, colors['green']) self.speed = 1 self.AUTODOWN = autodown self.figure = figure self.up = pygame.K_UP self.down = pygame.K_DOWN self.left = pygame.K_LEFT self.right = pygame.K_RIGHT self.bind_key_up_c = self.bind_key_down_c = self.bind_key_left_c = self.bind_key_right_c = colors['keybind_inactive'] self.bind_key_up = self.bind_key_down = self.bind_key_left = self.bind_key_right = False self.pressed_button = False self.blink_start = 150 self.blink_step = 2 self.frames = 0 def draw_window(self): self.speed = 1 + self.field.score // div pygame.draw.rect(screen, (0, 200, 100), (self.field.start_y, self.field.start_x, width * cell_size, height * cell_size)) for i in range(height): screen.blit(pygame.font.SysFont(font, int(cell_size * 0.7), True) .render((str((height - i))), 1, (200, 100, 100)), (3 + self.field.start_y - cell_size, cell_size * (i + 1))) screen.blit(pygame.font.SysFont(font, int(cell_size * 0.7), True) .render(("+" + str((height - i - 1) * 25)), 1, (200, 100, 100)), ((width + 1) * cell_size + 3 + self.field.start_y - cell_size, cell_size * (i + 1))) if height &gt; 14: font_size = int(cell_size * 1) screen.blit(pygame.font.SysFont(font, font_size, True). render("next figure", 1, colors['green']), (self.menu_left_line, int(cell_size * (5 - 0.25)))) labels = ['hi-score:', 'level:'] numbers = [0, 2, 3, 4, 5.9, 9.75, 3, 0, 10.75, 3] else: font_size = int(cell_size * 0.66) labels = ['hiscore:', 'lv:'] numbers = [2.25, 1, 1.5, 1.5, 2, 6, 2, 2.75, 6, 3.75] self.score_sum = pygame.font.SysFont(font, font_size, 1).\ render('{:06d}'.format(self.field.score), 1, colors['green']) hiscore = pygame.font.SysFont(font, font_size, 1).\ render('{:06d}'.format(self.field.hiscore), 1, colors['green']) screen.blit(pygame.font.SysFont(font, font_size, True).render("score:", 1, colors['green']), (self.menu_left_line, int(cell_size * (1 - 0.25)))) screen.blit(self.score_sum, (self.menu_left_line + int(cell_size * numbers[0]), int(cell_size * (numbers[1] - 0.25)))) screen.blit(pygame.font.SysFont(font, font_size, True).render(labels[0], 1, colors['green']), (self.menu_left_line, int(cell_size * (numbers[2] - 0.25)))) screen.blit(hiscore, (self.menu_left_line + int(cell_size * numbers[0]), int(cell_size * (numbers[3] - 0.25)))) pygame.draw.rect(screen, (0, 200, 100), (self.menu_left_line, int(cell_size * numbers[4]), cell_size * 4, cell_size * 4)) screen.blit(pygame.font.SysFont(font, font_size, True).render("lines:", 1, colors['green']), (self.menu_left_line, int(cell_size * numbers[5]))) screen.blit(pygame.font.SysFont(font, font_size, True).render(str(self.field.lines), 1, colors['green']), (self.menu_left_line + int(cell_size * numbers[6]), int(cell_size * numbers[5]))) screen.blit(pygame.font.SysFont(font, font_size, True).render(labels[1], 1, colors['green']), (self.menu_left_line + int(cell_size * numbers[7]), int(cell_size * numbers[8]))) screen.blit(pygame.font.SysFont(font, font_size, True).render(str(self.speed), 1, colors['green']), (self.menu_left_line + int(cell_size * numbers[9]), int(cell_size * numbers[8]))) def button_color(self, button, mouse): if button.collidepoint(mouse[0], mouse[1]): return colors['menu_active'] return colors['menu_inactive'] def draw_menu(self, mouse, click): global PAUSE, done b0x1 = (cell_size * 2 + self.field.start_y) if width &gt; 7 else self.field.start_y b0x2 = (cell_size * (width - 4)) if width &gt; 7 else (width * cell_size) b0y1 = (cell_size * 3) if height &gt; 9 else cell_size b1y1 = (cell_size * 6) if height &gt; 9 else (cell_size * 3) b2y1 = (cell_size * 9) if height &gt; 9 else (cell_size * 5) b0y2 = cell_size * 2 button_0 = pygame.Rect(b0x1, b0y1, b0x2, b0y2) button_1 = pygame.Rect(b0x1, b1y1, b0x2, b0y2) button_2 = pygame.Rect(b0x1, b2y1, b0x2, b0y2) if PAUSE and self.field.game: pygame.draw.rect(screen, self.button_color(button_0, mouse), button_0) screen.blit(pygame.font.SysFont(font, cell_size, True).render("Continue", 1, (0, 0, 100)), (int(self.field.start_y + width / 2 * cell_size - cell_size * 1.75), int(b0y1 + cell_size / 2))) if button_0.collidepoint(mouse[0], mouse[1]) and click[0]: PAUSE = False pygame.time.set_timer(self.AUTODOWN, self.figure.auto_down_speed) self.pressed_button = False pygame.draw.rect(screen, self.button_color(button_1, mouse), button_1) screen.blit(pygame.font.SysFont(font, cell_size, True).render(" Start " if not self.field.game else "Restart", 1, (0, 0, 100)), (int(self.field.start_y + width / 2 * cell_size - cell_size * 1.25), int(b1y1 + cell_size / 2))) pygame.draw.rect(screen, self.button_color(button_2, mouse), button_2) screen.blit(pygame.font.SysFont(font, cell_size, True).render("EXIT", 1, (0, 0, 100)), (int(self.field.start_y + width / 2 * cell_size - cell_size * 0.9), int(b2y1 + cell_size / 2))) if button_1.collidepoint(mouse[0], mouse[1]) and click[0]: if not self.field.game: PAUSE = False self.field.restart() self.figure.restart() pygame.time.set_timer(self.AUTODOWN, self.figure.auto_down_speed) elif button_2.collidepoint(mouse[0], mouse[1]) and click[0]: done = True @staticmethod def draw_cell(color, start_y, x, y, i, j): pygame.draw.rect(screen, colors[color], [int((y + j - 0.65) * cell_size) + start_y, int((x + i - 0.65) * cell_size), int(cell_size * 0.3), int(cell_size * 0.3)]) pygame.draw.lines(screen, colors[color], 1, [((y + j - 1) * cell_size + cell_size_1 + start_y, (x + i - 1) * cell_size + cell_size_1), ((y + j + 0) * cell_size - cell_size_3 + start_y, (x + i - 1) * cell_size + cell_size_1), ((y + j + 0) * cell_size - cell_size_3 + start_y, (x + i) * cell_size - cell_size_3), ((y + j - 1) * cell_size + cell_size_1 + start_y, (x + i) * cell_size - cell_size_3)], int(cell_size / 5)) def draw_next_figure(self): for i in range(len(self.figure.next_figure)): for j in range(len(self.figure.next_figure[i])): if self.figure.next_figure[i][j]: if height &gt; 14: start_x = 6.9 else: start_x = 3 GameWindow.draw_cell('white', self.field.start_y, start_x, (width + 2.5) + self.field.start_x / cell_size, i, j) def key_press(self): global done for event in event_list: if event.type == pygame.QUIT: done = True elif not PAUSE and event.type == pygame.KEYDOWN: if event.key == self.down: if self.figure.auto_down_speed &gt; 100: pygame.time.set_timer(self.AUTODOWN, 50) self.pressed_button = True self.figure.move_figure(self) elif event.key == self.left and self.figure.can_move("l"): self.figure.move_left() elif event.key == self.right and self.figure.can_move("r"): self.figure.move_right() elif event.key == self.up and self.figure.can_rotate(): self.figure.rotate() elif PAUSE: pass elif event.type == pygame.KEYUP: if event.key == self.down: pygame.time.set_timer(self.AUTODOWN, self.figure.auto_down_speed) self.pressed_button = False elif event.type == self.AUTODOWN: self.figure.move_figure(self) def notification(self, notification_times): global n_t if height &gt; 14: not_y_pos = cell_size * 9 not_times = notification_times if n_t &lt; not_times: not_field = pygame.Rect(int(self.field.start_y + (width - 3) * cell_size - 2), int(not_y_pos + cell_size * 3 + 2), cell_size * 5, cell_size * 3) if self.blink_start &gt; 200 or self.blink_start &lt; 100: self.blink_step *= -1 n_t += 1 self.blink_start += self.blink_step not_blink_color = pygame.Color(100, self.blink_start, 100) pygame.draw.rect(screen, (0, 100, 100), not_field) screen.blit(pygame.font.SysFont(font, cell_size, True).render("You can", 1, not_blink_color), (int(self.field.start_y + (width - 3) * cell_size), int(not_y_pos + cell_size * 3))) screen.blit(pygame.font.SysFont(font, cell_size, True).render("change =&gt;", 1, not_blink_color), (int(self.field.start_y + (width - 3) * cell_size), int(not_y_pos + cell_size * 4))) screen.blit(pygame.font.SysFont(font, cell_size, True).render("the controls", 1, not_blink_color), (int(self.field.start_y + (width - 3) * cell_size), int(not_y_pos + cell_size * 5))) else: pass def key_bind(self): global done if height &gt; 14: numbers = [2, 12, 1, 0, 2, 0, 3] else: numbers = [1.25, 6.75, 0.75, 1.25, 0.5, 2.5, 0.5] b3x1 = int(cell_size * (width + 2.5) + self.field.start_y) b3x2 = int(cell_size * numbers[0]) b3y1 = int(cell_size * numbers[1]) b3y2 = int(cell_size * numbers[2]) up_field = pygame.Rect(b3x1 + int(cell_size * numbers[3]), b3y1, b3x2, b3y2) down_field = pygame.Rect(b3x1 + int(cell_size * numbers[3]), b3y1 + cell_size, b3x2, b3y2) left_field = pygame.Rect(b3x1, b3y1 + int(cell_size * numbers[4]), b3x2, b3y2) right_field = pygame.Rect(b3x1 + int(cell_size * numbers[5]), b3y1 + int(cell_size * numbers[6]), b3x2, b3y2) if PAUSE: for event in event_list: if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: if up_field.collidepoint(event.pos): self.bind_key_up = not self.bind_key_up self.bind_key_down = self.bind_key_left = self.bind_key_right = False elif down_field.collidepoint(event.pos): self.bind_key_up = self.bind_key_left = self.bind_key_right = False self.bind_key_down = not self.bind_key_down elif left_field.collidepoint(event.pos): self.bind_key_up = self.bind_key_down = self.bind_key_right = False self.bind_key_left = not self.bind_key_left elif right_field.collidepoint(event.pos): self.bind_key_up = self.bind_key_down = self.bind_key_left = False self.bind_key_right = not self.bind_key_right else: self.bind_key_up = self.bind_key_down = self.bind_key_left = self.bind_key_right = False self.bind_key_up_c = colors['keybind_active'] if self.bind_key_up else colors['keybind_inactive'] self.bind_key_down_c = colors['keybind_active'] if self.bind_key_down else colors['keybind_inactive'] self.bind_key_left_c = colors['keybind_active'] if self.bind_key_left else colors['keybind_inactive'] self.bind_key_right_c = colors['keybind_active'] if self.bind_key_right else colors['keybind_inactive'] if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN or event.key == pygame.K_ESCAPE: self.bind_key_up = self.bind_key_down = self.bind_key_left = self.bind_key_right = False self.bind_key_up_c = self.bind_key_down_c = self.bind_key_left_c = self.bind_key_right_c = colors['keybind_inactive'] if self.bind_key_up: self.up = event.key elif self.bind_key_down: self.down = event.key elif self.bind_key_left: self.left = event.key elif self.bind_key_right: self.right = event.key pygame.draw.rect(screen, self.bind_key_up_c, up_field, 2) pygame.draw.rect(screen, self.bind_key_down_c, down_field, 2) pygame.draw.rect(screen, self.bind_key_left_c, left_field, 2) pygame.draw.rect(screen, self.bind_key_right_c, right_field, 2) if height &gt; 14: screen.blit(pygame.font.SysFont(font, int(cell_size * 0.75), True).render("Up", 1, self.bind_key_up_c), (b3x1 + int(2.5 * cell_size), b3y1)) screen.blit(pygame.font.SysFont(font, int(cell_size * 0.75), True).render("Down", 1, self.bind_key_down_c), (b3x1 + int(2.5 * cell_size), b3y1 + cell_size)) screen.blit(pygame.font.SysFont(font, int(cell_size * 0.75), True).render("Left", 1, self.bind_key_left_c), (b3x1 + int(2.5 * cell_size), b3y1 + cell_size * 2)) screen.blit(pygame.font.SysFont(font, int(cell_size * 0.75), True).render("Right", 1, self.bind_key_right_c), (b3x1 + int(2.5 * cell_size), b3y1 + cell_size * 3)) numbers = [0.75, 0.1, 0.1, 2, 0.1, 3] else: numbers = [0.6, 1.4, 0.15, 0.5, 2.65, 0.5] screen.blit(pygame.font.SysFont(font, int(cell_size * numbers[0]), True). render('{:.4}'.format(pygame.key.name(self.up)), 1, self.bind_key_up_c), (b3x1 + int(cell_size * numbers[1]), b3y1)) screen.blit(pygame.font.SysFont(font, int(cell_size * numbers[0]), True). render('{:.4}'.format(pygame.key.name(self.down)), 1, self.bind_key_down_c), (b3x1 + int(cell_size * numbers[1]), b3y1 + cell_size)) screen.blit(pygame.font.SysFont(font, int(cell_size * numbers[0]), True). render('{:.4}'.format(pygame.key.name(self.left)), 1, self.bind_key_left_c), (b3x1 + int(cell_size * numbers[2]), b3y1 + int(cell_size * numbers[3]))) screen.blit(pygame.font.SysFont(font, int(cell_size * numbers[0]), True). render('{:.4}'.format(pygame.key.name(self.right)), 1, self.bind_key_right_c), (b3x1 + int(cell_size * numbers[4]), b3y1 + int(cell_size * numbers[5]))) def fly_points(self): if self.field.k and self.frames &lt; 80 and self.field.score_up: score_plus_fly = pygame.font.SysFont(font, int(cell_size * (1 + 1 / 4 * self.field.k))) \ .render(("+" + str(self.field.score_up)), 0, (100, 100, 100, 10)) score_plus_fly.set_alpha(160 - self.frames * 2) screen.blit(score_plus_fly, ((self.field.figure_last_y * cell_size + self.figure.start_y), ((self.field.figure_last_x - 2) * cell_size - self.frames / 2))) self.frames += 1 else: self.frames = self.field.k = self.field.score_up = 0 def main(players=1, width_field=10, height_field=15, cell_size_pixels=20, divider=300): global PAUSE, done, screen global event_list global colors, figures, font global width, height global cell_size, cell_size_1, cell_size_3, div global n_t PAUSE = True done = False width, height = width_field, height_field cell_size = cell_size_pixels cell_size_3 = int(cell_size / 8) cell_size_1 = int(cell_size / 16) div = divider n_t = 0 font = "Arial" colors = {'black': pygame.Color(0, 0, 0), 'white': pygame.Color(255, 255, 255), 'green': pygame.Color(100, 100, 100), 'red': pygame.Color(255, 100, 0), 'keybind_inactive': pygame.Color(100, 100, 0), 'keybind_active': pygame.Color(200, 0, 0), 'menu_inactive': pygame.Color(0, 100, 200), 'menu_active': pygame.Color(0, 200, 200)} figures = {'O': [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]], 'L': [[0, 0, 0], [1, 1, 1], [0, 0, 1]], 'J': [[0, 0, 1], [1, 1, 1], [0, 0, 0]], 'T': [[0, 1, 0], [1, 1, 0], [0, 1, 0]], 'I': [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]], 'Z': [[1, 0], [1, 1], [0, 1]], 'S': [[0, 1], [1, 1], [1, 0]]} pygame.init() size = (cell_size * (width + 9) * players, cell_size * (height + 2)) screen = pygame.display.set_mode(size) pygame.display.set_caption("Tetris") clock = pygame.time.Clock() players_dic = {} for player in range(players): players_dic[player] = {'field': Field(cell_size + cell_size * (width + 9) * player), 'figure': '', 'game': ''} players_dic[player]['figure'] = Figure((cell_size + cell_size * (width + 9) * player), players_dic[player]['field']) players_dic[player]['game'] = GameWindow(players_dic[player]['field'], players_dic[player]['figure'], (pygame.USEREVENT + player)) while not done: screen.fill((0, 255, 0)) mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() event_list = pygame.event.get() for player_number in range(players): players_dic[player_number]['game'].draw_window() players_dic[player_number]['game'].key_bind() players_dic[player_number]['field'].draw() if players_dic[player_number]['field'].game: players_dic[player_number]['figure'].draw() players_dic[player_number]['game'].fly_points() players_dic[player_number]['game'].draw_next_figure() players_dic[player_number]['game'].key_press() if not players_dic[player_number]['field'].game or PAUSE: players_dic[player_number]['game'].draw_menu(mouse, click) players_dic[player_number]['game'].notification(4) for event in event_list: if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: if PAUSE: PAUSE = False for player_number in range(players): pygame.time.set_timer(players_dic[player_number]['game'].AUTODOWN, players_dic[player_number]['figure'].auto_down_speed) players_dic[player_number]['game'].pressed_button = False else: PAUSE = True n_t = 0 pygame.display.flip() clock.tick(60) pygame.quit() main(3, 10, 15, 20, 1000) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T09:58:32.130", "Id": "211089", "Score": "3", "Tags": [ "python", "python-3.x", "tetris" ], "Title": "First project \"Game Tetris\", Python 3.4" }
211089
<p>Lets say I have <code>Car</code>s with <code>Feature</code>s, and I have been given a <code>List</code> of features to look for in the <code>Car</code>s available with me. Though I could have done that using for-loop, what are the suggestions for below? Is this production-worthy?</p> <pre><code>import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class LookupTest { public static void main(String[] args) { Feature ft11 = new Feature(1); Feature ft12 = new Feature(2); Feature ft13 = new Feature(4); Car fer = new Car("Ferrari", ft11, ft12, ft13); Feature ft21 = new Feature(1); Feature ft22 = new Feature(2); Feature ft23 = new Feature(8); Car suz = new Car("Suzuki", ft21, ft22, ft23); List&lt;Car&gt; cars = Arrays.asList(fer, suz); List&lt;Integer&gt; lookForTypes = Arrays.asList(4); // look whether any car has feature-type 4 if (CollectionUtils.isNotEmpty(lookForTypes)) { /* code block in question : start */ boolean atLeastOneTypeFound = cars .parallelStream() .anyMatch(holding -&gt; holding.getAmounts() .parallelStream() .anyMatch(feature -&gt; { return lookForTypes.contains(feature.type); })); /* code block in question : end */ System.out.println("atLeastOneTypeFound=" + atLeastOneTypeFound); } } } class Car { List&lt;Feature&gt; featureList; String name; public Car(String name, Feature... features) { featureList = Arrays.asList(features); this.name = name; } public List&lt;Feature&gt; getAmounts() { return featureList; } public String getName() { return name; } } class Feature { int type; public Feature(int type) { this.type = type; } public int getType() { return type; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:00:16.193", "Id": "408137", "Score": "0", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:49:19.330", "Id": "408200", "Score": "0", "body": "Ok, that was a typo actually." } ]
[ { "body": "<p>If you don't need the <code>Car</code>, you can also flatMap to have the features and then distinct them before searching.</p>\n\n<pre><code>cars.stream()\n .flatMap(car -&gt; car.getAmounts().stream())\n .map(Feature::getType)\n .distinct() // As spotted by @Pimgd in the comments this is useless\n .anyMatch(lookForTypes::contains);\n</code></pre>\n\n<p>But if you want to improve the readability of your code you should better consider to move a part of this \"logic\" into your objects :</p>\n\n<pre><code>cars.stream()\n .anyMatch(car -&gt; car.hasAtLeastOneFeature(lookForTypes);\n\n// ...\n\nCar {\n boolean hasAtLeastOneFeature(List&lt;Integer&gt; features) {\n // Note that I renamed getAmounts to getFeatures\n return getFeatures().stream()\n .anyMatch(feature -&gt; features.contains(feature.getType());\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T14:42:56.023", "Id": "408135", "Score": "2", "body": "Why distinct before searching? ``anyMatch`` would stop upon finding a hit, so what's the point in making a list of uniques first?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T03:14:55.680", "Id": "408253", "Score": "0", "body": "What is the difference between doing `.parallelStream().anyMatch()` and your `flatMap(stream) -> map() -> anyMatch()` implementation? I dont need the `Car`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T06:55:33.370", "Id": "408264", "Score": "0", "body": "@Pimgd indeed, there is no gain to `distinct` first. @xploreraj using `flatMap` you avoid the nested `Stream<Stream>` so that your code is a bit more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:49:34.117", "Id": "408434", "Score": "0", "body": "@gervais.b But is it not like `stream` as opposed to `parallelStream` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T08:46:05.303", "Id": "408498", "Score": "0", "body": "You can use `flatMap` on with `stream` and `parallelStream` without changes. I used `stream` in my sample because the word is shorter." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:17:42.577", "Id": "211102", "ParentId": "211091", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T11:03:50.967", "Id": "211091", "Score": "0", "Tags": [ "java", "stream" ], "Title": "Nested stream to check the truth condition at first instance" }
211091
<p>I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. Can someone suggest a better way to do this?</p> <pre><code>s=input("Enter the string:") temp={} result=" " for x in s: if x in temp: temp[x]=temp[x]+1 else: temp[x]=1 for key,value in temp.items(): result+=str(key)+str(value) print(result) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:25:56.003", "Id": "408128", "Score": "4", "body": "Your code does not seem to actually solve the problem you stated. The order of letters is not preserved and if a letter only occures once you add a `1` instead of just outputting it (`\"aba\" -> \"a2b1\"` instead of `\"aba\" -> \"aba\"`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:24:32.570", "Id": "408187", "Score": "2", "body": "In addition to the problem Graipher reported, there is also unexepected indentation on the last line..." } ]
[ { "body": "<p>This could be one of the way to do it:</p>\n\n<pre><code>count = 1\nfor i in range(1, len(input) + 1):\n if i == len(input):\n print(input[i - 1] + str(count), end=\"\")\n break\n else:\n if input[i - 1] == input[i]:\n count += 1\n else:\n print(input[i - 1] + str(count), end=\"\")\n count = 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:39:17.857", "Id": "408105", "Score": "0", "body": "Thanks, something wrong with my code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:40:23.033", "Id": "408106", "Score": "0", "body": "Not really, just suggested you a better way to perform the same per your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:19:26.283", "Id": "408118", "Score": "5", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:37:01.917", "Id": "211096", "ParentId": "211094", "Score": "-2" } }, { "body": "<p>In the <code>itertools</code> module there is the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>groupby</code></a> function that groups together runs of the same values.</p>\n\n<p>You can use it like this here:</p>\n\n<pre><code>from itertools import groupby\n\ndef compress(s):\n out = []\n for name, group in groupby(s):\n length_of_run = len(list(group))\n if length_of_run == 1:\n out.append(name)\n else:\n out.append(f\"{name}{length_of_run}\")\n return \"\".join(out)\n</code></pre>\n\n<p>This also uses the more modern <a href=\"https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/\" rel=\"nofollow noreferrer\">f-strings</a> instead of manually building the string with <code>str</code> calls and <code>+</code> and puts everything into a function that you can reuse.</p>\n\n<p>It also has the advantage that it directly iterates over the input, instead of over its indices (have a look at <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Loop like a Native!</a>). This makes it work also for a generator, which does not have a length:</p>\n\n<pre><code>from itertools import islice, cycle\n\ncompress(islice(cycle('a'), 10))\n# 'a10'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:08:08.610", "Id": "211099", "ParentId": "211094", "Score": "2" } }, { "body": "<h1>Encapsulate your code into functions</h1>\n\n<p>Your code is neither reusable nor testable, wrap it into a function and call it from under an <a href=\"https://stackoverflow.com/q/419163/5069029\"><code>if __name__ == '__main__'</code></a> guard. This will allow you to test it more easily. You will also be able to return values instead of printing them, this will make the code more reusable:</p>\n\n<pre><code>def compress(string):\n temp={}\n result=\" \"\n for x in string:\n if x in temp:\n temp[x] = temp[x]+1\n else:\n temp[x] = 1\n for key, value in temp.items():\n result += str(key) + str(value)\n\n return result\n\n\nif __name__ == '__main__':\n s = input(\"Enter the string:\")\n print(compress(s))\n</code></pre>\n\n<p>You can then jump into an interactive shell and type:</p>\n\n<pre><code>&gt;&gt;&gt; from your_file_name import compress\n&gt;&gt;&gt; compress('aaabbccccddefg')\n a3b2c4d2e1f1g1\n&gt;&gt;&gt; compress('b'*42)\n b42\n</code></pre>\n\n<h1>Use existing data structures</h1>\n\n<p><a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter</code></a> offers simplified ways of counting elements of an iterable:</p>\n\n<pre><code>from collections import Counter\n\n\ndef compress(string):\n temp = Counter()\n result = \" \"\n for x in string:\n temp[x] += 1\n\n for key, value in temp.items():\n result += str(key) + str(value)\n return result\n\n\nif __name__ == '__main__':\n s = input(\"Enter the string:\")\n print(compress(s))\n</code></pre>\n\n<p>You can even simplify further as <code>Counter</code> can take any iterable in its constructor. You can also use <code>str.join</code> to simplify even further:</p>\n\n<pre><code>from collections import Counter\n\n\ndef compress(string):\n counts = Counter(string)\n return ''.join(letter+str(count) for letter, count in counts.items())\n\n\nif __name__ == '__main__':\n print(compress(input(\"Enter the string: \")))\n</code></pre>\n\n<h1>Possible bug</h1>\n\n<p>To me, compressing a string mean having a mean to decompress it back. Using a dictionnary keyed by each letter as you do, you lost an important information: which letter is next to which one. Also <code>'aabaabaabaa'</code> will be compressed to <code>'a8b3'</code> which, to me, doesn't make sense and would be better as <code>'a2b1a2b1a2b1a2'</code>. But I might be wrong. In this case, <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a> is much more usefull as it will keep the ordering and avoid aggregating separate groups of letters:</p>\n\n<pre><code>import itertools\n\n\ndef compress(string):\n return ''.join(\n letter + str(len(list(group)))\n for letter, group in itertools.groupby(string))\n\n\nif __name__ == '__main__':\n print(compress(input(\"Enter the string: \")))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:21:49.397", "Id": "408121", "Score": "0", "body": "And then encoding `'f'` as `'f1'` is the opposite of compressing. But if you find a nice way to write it as a comprehension that would be nice, I could not think of any." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:22:45.493", "Id": "408123", "Score": "1", "body": "@Graipher For `'f'` -> `'f1'` I chose to keep the original behaviour" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:23:56.790", "Id": "408124", "Score": "2", "body": "@Graipher But something like `letter + str(length := len(list(group))) if length > 1 else ''` could work in upcomming Python 3.8" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:24:08.757", "Id": "408125", "Score": "1", "body": "The more I look at it, the code of the OP does not solve the stated problem at all..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:24:39.917", "Id": "408126", "Score": "0", "body": "Yeah, I was thinking along those lines as well. But I only have 3.6 installed :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:18:13.490", "Id": "211103", "ParentId": "211094", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:33:54.890", "Id": "211094", "Score": "3", "Tags": [ "python", "strings" ], "Title": "String compression function in python code" }
211094
<p>This one is kind of involved. Is there a simpler way to implement this prefix code in base python, my existing code goes below but any help in modification or review will be helpful.</p> <pre><code># Lagged fibonacci numbers the sequence starts: 1,2,3,5,8,11 def fibonacci(n): a = 1 b = 1 out = [] for i in range(n): out.append(a) a,b = a+b,a return out # There has to be a better way to do this, right? # Go through the list for the first few fibonacci numbers from greatest to # make a list of fibonacci numbers that add up to each code number (1,2,3...) # The code is then the indexes of those fibonacci numbers, with leading zeroes # removed, reversed, with an additional "1" at the end. def makeCodebook(decode=False): F = fibonacci(10) F.reverse() codes = [] for x in range(1,27): while x != 0: code = [] for f in F: if f &lt;= x: code.append("1") x = x-f else: code.append("0") while code[0] == "0": code.pop(0) code.reverse() code.append("1") codes.append("".join(code)) # Matchup codes with letters D = {} alpha = "ETAOINSRHLDCUMFPGWYBVKXJQZ" if decode == False: for a,b in zip(alpha,codes): D[a] = b if decode == True: for a,b in zip(alpha,codes): D[b] = a return D def prefixCode(text,decode=False): # Build the codebook D = makeCodebook(decode=decode) # When encoding we simply translate each letter to its code if decode == False: out = [] for letter in text: out.append(D[letter]) return "".join(out) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:16:08.593", "Id": "408116", "Score": "4", "body": "Can you put the part that is currently only a comment into the body of the question, so reviewers don't have to search for it? Also some example in- and output would help a lot!" } ]
[ { "body": "<p>When you need to loop a fixed number of time, but don't actually need the loop index, it is customary to use <code>_</code> as the loop index. So, in <code>fibonacci(n)</code>, you would write <code>for _ in range(n):</code>.</p>\n\n<p>Your <code>fibonacci()</code> generator is generating too many values. Your last code value is 26, so any fibonacci value greater than 26 is unnecessary. Instead of asking for a fixed number of values, ask for values up to a specific limit.</p>\n\n<pre><code>def fibonacci_up_to(last):\n a, b = 1, 1\n out = []\n while a &lt;= last:\n out.append(a)\n a, b = a+b, a\n return out\n</code></pre>\n\n<p>And use <code>F = fibonacci_up_to(26)</code></p>\n\n<p>The following is an incorrect comment:</p>\n\n<pre><code># Lagged fibonacci numbers the sequence starts: 1,2,3,5,8,11\n</code></pre>\n\n<p>The fibonacci sequence doesn't contain an <code>11</code>; the number, following after <code>5</code> and <code>8</code> would be <code>5+8=13</code>!</p>\n\n<hr>\n\n<p>In <code>makeCodebook()</code>:</p>\n\n<p>It is usually clearer to write <code>x = x-f</code> as <code>x -= f</code></p>\n\n<p>Instead of always appending <code>\"1\"</code> to the end of <code>code</code> after reversing it, you could simply initialize <code>code = [\"1\"]</code> at the start.</p>\n\n<p>The <code>while x != 0:</code> loop is unnecessary. After the <code>for f in F:</code> loop, <code>x</code> will have become zero, or there is a logic error in constructions of the <code>code</code> for <code>x</code>. Remove <code>while x != 0:</code>, and optionally add an <code>assert</code> if you are unsure <code>x</code> actually reaches zero.</p>\n\n<p>Construction your code dictionary <code>D</code>:</p>\n\n<pre><code>D = {}\nfor a,b in zip(alpha, codes):\n D[a] = b\n</code></pre>\n\n<p>can be re-written with list-comprehension as:</p>\n\n<pre><code>D = { a: b for a, b in zip(alpha, codes) }\n</code></pre>\n\n<p>Or, as pointed out by @Graipher in the comments, simply:</p>\n\n<pre><code>D = dict(zip(alpha, codes))\n</code></pre>\n\n<p>Using <code>if decode == False:</code> followed by <code>if decode == True:</code> is unnecessary verbose. <code>if decode == False:</code> can simply be <code>if not decode:</code>, and the reverse condition should simply be <code>else:</code>. Or better, eliminate the negated logic, by swapping the statement order:</p>\n\n<pre><code>if decode:\n D = { code: letter for letter, code in zip(alpha, codes) }\nelse:\n D = { letter: code for letter, code in zip(alpha, codes) }\n</code></pre>\n\n<p>Or, leveraging @Graipher's simplification from the comments and Python's <code>x if cond else y</code> expression, the above can be written in one line. Whether this is clearer or more obfuscated is a matter of taste:</p>\n\n<pre><code>D = dict(zip(codes, alpha)) if decode else dict(zip(alpha, codes))\n</code></pre>\n\n<hr>\n\n<p>In <code>prefixCode()</code>:</p>\n\n<p>Constructing the <code>out</code> array can be done with list comprehension:</p>\n\n<pre><code>out = [ D[letter] for letter in text ]\n</code></pre>\n\n<p>but this <code>out</code> array is just a temporary used as an argument in the next statement, so you should combined them:</p>\n\n<pre><code>return \"\".join( D[letter] for letter in text )\n</code></pre>\n\n<p>Your function has (or will have) two entirely different execution paths with almost no common functionality, one for encoding, and (eventually) one for decoding. Write this as two functions, not as one function with a <code>decode</code> parameter to choose between the paths:</p>\n\n<pre><code>def encode(text):\n # ...\n\ndef decode(text):\n # ...\n</code></pre>\n\n<hr>\n\n<p>Use <code>pylint</code> or similar to check your code for <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> compatibility. Including things such as:</p>\n\n<ul>\n<li>use spaces after commas: <code>zip(alpha, codes)</code> not <code>zip(alpha,codes)</code></li>\n<li>use spaces around operators: <code>x - f</code> not <code>x-f</code></li>\n<li>use <code>lower_case_function_names()</code>, not <code>mixedCaseFunctionNames()</code></li>\n<li>use <code>lower_case_variables</code> not uppercase identifiers like <code>D</code> and <code>F</code></li>\n</ul>\n\n<hr>\n\n<p>Generating your codebook:</p>\n\n<p>This can be simplified by (for the moment, ignore the final terminating <code>1</code>) noting that the code for a Fibonacci number is simply a number of placeholder <code>0</code>'s followed by a <code>1</code>, and the code for a number like 17 (=<code>13+4</code>) will be the code for 4 (<code>101</code>), followed by a number of placeholder <code>0</code>'s, and then a <code>1</code> for the largest Fibonacci value smaller than the number (<code>13</code>). After building all of the codes, add the final <code>1</code> terminator to each.</p>\n\n<pre><code>def codebook(key):\n codes = [\"\"]\n a, b = 1, 1\n digits = 0\n\n for x in range(1, len(key)+1):\n if x &gt;= a:\n a, b = a+b, a\n digits += 1\n\n prefix = codes[x-b]\n codes.append(prefix + \"0\"*(digits - len(prefix) - 1) + \"1\")\n\n return { letter: code+'1' for letter, code in zip(key, codes[1:]) }\n\nletter_to_code = codebook(\"ETAOINSRHLDCUMFPGWYBVKXJQZ\")\n\ncode_to_letter = { code: letter for letter, code in letter_to_code.items() }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:06:19.577", "Id": "408359", "Score": "1", "body": "Instead of `D = { a: b for a,b in zip(alpha, codes) }` you can just use `D = dict(zip(alpha, codes))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:21:26.297", "Id": "408409", "Score": "0", "body": "@Graipher Excellent point. `dict(zip(alpha, codes))` is around 14% faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:40:47.610", "Id": "408432", "Score": "0", "body": "Hm, I thought it was just easier to read, good to know!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:10:21.063", "Id": "211131", "ParentId": "211098", "Score": "1" } }, { "body": "<p>Your <code>fibonacci</code> doesn't need the variables <code>a</code> and <code>b</code>; <code>out</code> is already tracking them.</p>\n\n<pre><code>def fibonacci(n):\n out = [1,2]\n for i in range(n-2):\n out.append(out[i]+out[i+1])\n return out\n</code></pre>\n\n<p>You should build both the encoding and coding codebooks at the same time, so you don't have to run the same function twice to get both.</p>\n\n<p>You can build your codebooks as you find the codes:</p>\n\n<pre><code>def makeCodebook():\n alpha = \"ETAOINSRHLDCUMFPGWYBVKXJQZ\"\n F = fibonacci(10)\n F.reverse()\n D = {}\n E = {}\n for x,letter in enumerate(alpha,1):\n while x != 0:\n code = []\n for f in F:\n if f &lt;= x:\n code.append(\"1\")\n x = x-f\n else:\n code.append(\"0\")\n\n while code[0] == \"0\":\n\n code.pop(0)\n code.reverse()\n code.append(\"1\")\n D[code] = letter\n E[letter] = code\n return D,E\n</code></pre>\n\n<p>Note that this eliminates the need to keep a <code>codes</code> list.</p>\n\n<p>Then you can have</p>\n\n<pre><code>def prefixCode(text,decode=False):\n D, E = makeCodebook(decode=decode)\n if not decode:\n return \"\".join([E[letter] for letter in text])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:41:58.013", "Id": "408244", "Score": "1", "body": "You’ve changed the `fibonacci()` function so that it now produces 12 values, when given the argument 10. Worse, it produces the sequence starting with `1, 1, 2, 3, 5 …` instead of the “lagged” version starting `1, 2, 3, 5 …`, which breaks the codebook generation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T02:57:47.007", "Id": "408252", "Score": "1", "body": "Other bugs you’ve introduced: `codes` is no longer defined, so `codes.append( )` is an error. `alpha[26]` is an index out of range, and `alpha[0]` (the letter `”E”`) is not added to the encode/decode dictionaries. It would be better (and more importantly, correct) to use `for x, letter in enumerate(alpha, 1):` to loop over the letters of `alpha`, providing a 1-based index for each." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T21:35:02.777", "Id": "408445", "Score": "0", "body": "Finally, `D, E = makeCodebook(decode=decode)` is an error since `makeCodebook()` no longer takes a `decode` argument." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T22:37:45.133", "Id": "211144", "ParentId": "211098", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:06:14.120", "Id": "211098", "Score": "1", "Tags": [ "python" ], "Title": "Fibonacci prefix code" }
211098
<p>I'm computing the gradient of an image manually (without using built in functions) and I want to make it faster but keeping the same performance. I'm very open to any suggestions.. currently learning c++ optimzation and STL lib in recent c++.</p> <p>Here is my code, my main concern is <code>gradiantAndDirection</code> function that I need to optimize. The <code>TimerAvrg struct</code> is how I compute the running time of that function:</p> <pre><code>#include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/imgproc.hpp&gt; #include &lt;iostream&gt; #include &lt;chrono&gt; struct TimerAvrg { std::vector&lt;double&gt; times; size_t curr=0,n; std::chrono::high_resolution_clock::time_point begin,end; TimerAvrg(int _n=30) { n=_n; times.reserve(n); } inline void start() { begin= std::chrono::high_resolution_clock::now(); } inline void stop() { end= std::chrono::high_resolution_clock::now(); double duration=double(std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end-begin).count())*1e-6; if ( times.size()&lt;n) times.push_back(duration); else{ times[curr]=duration; curr++; if (curr&gt;=times.size()) curr=0;} } double getAvrg() { double sum=0; for(auto t:times) sum+=t; return sum/double(times.size()); } }; //Those variables will be in a class with gradiantAndDirection uchar *dirImg; int gradThresh = 20; void gradiantAndDirection(cv::Mat&amp; GxGy, const cv::Mat &amp;grey) { cv::Mat smoothImage; GaussianBlur(grey, smoothImage, cv::Size(5, 5), 1.0); uchar *smoothImg = smoothImage.data; GxGy.create( grey.size(),CV_16SC1); short* gradImg = (short*)GxGy.data; dirImg = new unsigned char[grey.cols*grey.rows]; //Initialization of row = 0, row = height-1, column=0, column=width-1 for (int j = 0; j&lt;grey.cols; j++) gradImg[j] = gradImg[(grey.rows - 1)*grey.cols + j] = gradThresh - 1; for (int i = 1; i&lt;grey.rows - 1; i++) gradImg[i*grey.cols] = gradImg[(i + 1)*grey.cols - 1] = gradThresh - 1; for (int i = 1; i&lt;grey.rows - 1; i++) { for (int j = 1; j&lt;grey.cols - 1; j++) { int com1 = smoothImg[(i + 1)*grey.cols + j + 1] - smoothImg[(i - 1)*grey.cols + j - 1]; int com2 = smoothImg[(i - 1)*grey.cols + j + 1] - smoothImg[(i + 1)*grey.cols + j - 1]; int gx; int gy; gx = abs(com1 + com2 + (smoothImg[i*grey.cols + j + 1] - smoothImg[i*grey.cols + j - 1])); gy = abs(com1 - com2 + (smoothImg[(i + 1)*grey.cols + j] - smoothImg[(i - 1)*grey.cols + j])); int sum; if(0) sum = gx + gy; else sum = (int)sqrt((double)gx*gx + gy*gy); int index = i*grey.cols + j; gradImg[index] = sum; if (sum &gt;= gradThresh) { if (gx &gt;= gy) dirImg[index] = 1;//1 vertical else dirImg[index] = 2;//2 Horizontal } } } } int main( int argc, char** argv ) { cv::Mat image; image = cv::imread(argv[1], cv::IMREAD_GRAYSCALE); float sum=0; cv::Mat GxGy; for(int alpha = 0; alpha &lt;20 ; alpha++) { TimerAvrg Fps; Fps.start(); gradiantAndDirection(GxGy, image); Fps.stop(); sum = sum + Fps.getAvrg()*1000; } std::cout &lt;&lt; "\rTime detection=" &lt;&lt; sum/19 &lt;&lt; " milliseconds" &lt;&lt; std::endl; cv::resize(GxGy,GxGy,cv::Size(image.cols/2,image.rows/2)); cv::Mat result8UC1; cv::convertScaleAbs(GxGy, result8UC1); cv::imshow( "Display window",result8UC1); cv::waitKey(0); return 0; } </code></pre> <p>I compile my code under Ubuntu 16.04 gcc 8.1.0</p> <pre><code>g++ -std=c++1z -fomit-frame-pointer -O3 -ffast-math -mmmx -msse -msse2 -msse3 -DNDEBUG -Wall improve_code.cpp -o improve_code -fopenmp `pkg-config --cflags --libs opencv` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:54:02.343", "Id": "408327", "Score": "1", "body": "What do you mean by \"make it faster but keeping the same performance\" - isn't that a contradiction?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:59:04.497", "Id": "408331", "Score": "0", "body": "@TobySpeight I think we can make a faster program but sometimes we loose the optimal performance like calling \"a.empty()\" instead of \"a.size() == 0\" .." } ]
[ { "body": "<h1>Include what you use</h1>\n\n<p>We use <code>std::abs</code> and <code>std::vector</code> but the code lacks the necessary includes:</p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;vector&gt;\n</code></pre>\n\n<h1>Perform a single task well</h1>\n\n<p>Why do we perform the Gaussian blur? What if the input is already sufficiently blurred, or if it needs a bigger kernel?</p>\n\n<p>If we make the caller responsible for this preparation step, we give it more control, and we can focus on a single responsibility in this function.</p>\n\n<h1>Fix the memory leak</h1>\n\n<p>This allocation is never released:</p>\n\n<pre><code>dirImg = new unsigned char[grey.cols*grey.rows];\n</code></pre>\n\n<p>In fact, this entire (global) array seems only to be assigned to, and never used, so we could remove it entirely.</p>\n\n<h1>Simplified indexing</h1>\n\n<p>It might be easier to use <code>index</code> throughout, and add rows or columns directly with ±<code>grey.cols</code> and ±<code>1</code>:</p>\n\n<pre><code> const int index = i*grey.cols + j;\n int com1 = smoothImg[index + grey.cols + 1] - smoothImg[index - grey.cols - 1];\n int com2 = smoothImg[index - grey.cols + 1] - smoothImg[index + grey.cols - 1];\n int gx = std::abs(com1 + com2\n + smoothImg[index + 1] - smoothImg[index + 1]);\n int gy = std::abs(com1 - com2\n + smoothImg[index + grey.cols] - smoothImg[index - grey.cols]);\n</code></pre>\n\n<h1>Use the standard library</h1>\n\n<p>There's no need to (badly) re-write <code>std::hypot()</code> for the computation of <code>sum</code> (also, drop the <code>if (0)</code> - that's always false).</p>\n\n<pre><code> const int sum = std::hypot(gx, gy);\n</code></pre>\n\n<h1>Saturate, don't overflow</h1>\n\n<p>The <code>std::hypot()</code> value could conceivably be larger than the range of <code>int</code>, or of <code>gradImg[]</code> (depending on the relative sizes of the target's integer types) - in such cases, we should <code>std::clamp</code> the value to the possible range, rather than suffering Undefined Behaviour.</p>\n\n<h1>Spelling</h1>\n\n<p>Prefer standard spelling: <strong>gradient</strong>, not <s>gradiant</s>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:22:06.133", "Id": "211196", "ParentId": "211101", "Score": "3" } } ]
{ "AcceptedAnswerId": "211196", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T13:15:44.633", "Id": "211101", "Score": "2", "Tags": [ "c++", "performance", "opencv" ], "Title": "Optimizing gradient function in C++" }
211101
<p>I made a vanilla Javascript shopping cart using sessionStorage. This way users can navigate pages without losing data. The checkout form sends to paypal. A self invoking function initializes event listeners and prototypes. Private functions are preceded by an underscore. Your review is very much appreciated.</p> <p>The only issue I have is using <code>this.element</code>. I wanted to use it when I make <code>getElementById()</code> calls but, javascript wants <code>document</code> as it is the owner of the element. How can I make use of my <code>this.element</code> property?</p> <p><strong>javascript-shop.js</strong></p> <pre><code>(function() { var Shop = function( element ) { this.element = document.getElementById(element) ; this.init() ; } ; Shop.prototype = { // Properties init : function() { this.cartPrefix = "winery-" ; this.cartName = this.cartPrefix + "cart" ; this.shippingRates = this.cartPrefix + "shipping-rates" ; this.total = this.cartPrefix + "total" ; this.storage = sessionStorage ; this.formCart = document.getElementById("shopping-cart") ; this.formAddToCart = document.getElementsByClassName("add-to-cart") ; this.checkoutCart = document.getElementById("checkout-cart") ; this.checkoutOrderForm = document.getElementById("checkout-order-form") ; this.shipping = document.getElementById("sshipping") ; this.subTotal = document.getElementById("stotal") ; this.shoppingCartActions = document.getElementById("shopping-cart-actions") ; this.updateCartBtn = document.getElementById("update-cart") ; this.emptyCartBtn = document.getElementById("empty-cart") ; this.userDetails = document.getElementById("user-details-content") ; this.paypalForm = document.getElementById("paypal-form") ; this.currency = "&amp;euro;" ; this.currencyString = "€" ; this.paypalCurrency = "EUR" ; this.paypalBusinessEmail = "yourbusiness@email.com" ; this.paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr" ; this.requiredFields = { expression : { value : /^([\w-\.]+)@((?:[\w]+\.)+)([a-z]){2,4}$/ } , str : { value : "" } } ; this.createCart() ; this.handleAddToCartForm() ; this.handleCheckoutOrderForm() ; this.emptyCart() ; this.updateCart() ; this.displayCart() ; this.displayUserDetails() ; this.populatePaypalForm() ; } , // Public functions createCart : function() { var self = this ; if ( self.storage.getItem(self.cartName) == null ) { var cart = {} ; cart.items = [] ; self.storage.setItem(self.cartName , self._toJSONString(cart)) ; self.storage.setItem(self.shippingRates , "0") ; self.storage.setItem(self.total , "0") ; } } , handleAddToCartForm : function() { var self = this ; var sform = Array.from(self.formAddToCart) ; // forEach only accepts arrays, not array-like objects sform.forEach(function( form ) { var product = form.parentElement ; var name = product.getElementsByClassName("product-name")[0] ; var price = product.getElementsByClassName("product-price")[0] ; name = name.innerHTML ; price = self._convertString(price.innerHTML) ; form.addEventListener("submit", function() { var qty = form.getElementsByClassName("qty")[0] ; qty = self._convertString(qty.value) ; var subTotal = qty * price ; var total = self._convertString(self.storage.getItem(self.total)) ; var sTotal = total + subTotal ; self.storage.setItem(self.total , sTotal) ; self._addToCart({ product : name , price : price , qty : qty }) ; var shipping = self._convertString(self.storage.getItem(self.shippingRates)) ; var shippingRates = self._calculateShipping(qty) ; var totalShipping = shipping + shippingRates ; self.storage.setItem(self.shippingRates , totalShipping) ; } , true) ; } ) ; } , displayCart : function() { var self = this ; if ( self.formCart || self.checkoutCart ) { var cart = self._toJSONObject(self.storage.getItem(self.cartName)) ; var items = cart.items ; if ( self.formCart ) { var tableCart = self.formCart ; } else { var tableCart = self.checkoutCart ; } var tableCartBody = tableCart.getElementsByTagName("tbody")[0] ; var x ; var len = items.length ; for ( x = 0 ; x &lt; len ; x++ ) { var item = items[x] ; var price = self.currency + " " + item.price ; var html = "&lt;tr&gt;" ; html += "&lt;td class='pname'&gt;" + item.product + "&lt;/td&gt;" ; html += "&lt;td class='pqty'&gt;" + item.qty + "&lt;/td&gt;" ; html += "&lt;td class='pprice'&gt;" + item.price + "&lt;/td&gt;" ; html += "&lt;/tr&gt;" ; tableCartBody.innerHTML += html ; } if ( self.formCart ) { var total = self.storage.getItem(self.total) ; this.subTotal.innerHTML = self.currency + " " + total ; } else if ( self.checkoutCart ) { var total = self.storage.getItem(self.total) ; var shipping = self.storage.getItem(self.shippingRates) ; var subTotal = self._convertString(total) + self._convertString(shipping) ; this.subTotal.innerHTML = self.currency + " " + self._convertString(subTotal) ; this.shipping.innerHTML = self.currency + " " + shipping ; } } } , updateCart : function() { var self = this ; if ( self.updateCartBtn ) { self.updateCartBtn.addEventListener("click", function() { var formCart = self.formCart ; var tbody = formCart.getElementsByTagName("tbody")[0] ; var rows = tbody.getElementsByTagName("tr") ; var cart = self.storage.getItem(self.cartName) ; var shippingRates = self.storage.getItem(self.shippingRates) ; var total = self.storage.getItem(self.total) ; var updatedTotal = 0 ; var totalQty = 0 ; var updatedCart = {} ; updatedCart.items = [] ; rows = Array.from(rows) ; rows.forEach(function( row ) { var pname = row.getElementsByClassName("pname")[0].innerHTML ; var pqty = row.getElementsByClassName("pqty")[0].innerHTML ; var pprice = row.getElementsByClassName("pprice")[0].innerHTML ; pqty = self._convertString(pqty) ; pprice = self._convertString(self._extractPrice(pprice)) ; var cartObj = { product : pname , price : pprice , qty : pqty } ; updatedCart.items.push(cartObj) ; var subTotal = pqty * pprice ; updatedTotal += subTotal ; totalQty += pqty ; } , true) ; self.storage.setItem(self.total , self._convertNumber(updatedTotal)) ; self.storage.setItem(self.shippingRates , self._convertNumber(self._calculateShipping(totalQty))) ; self.storage.setItem(self.cartName , self._toJSONString(updatedCart)) ; } , true) ; } } , emptyCart : function() { var self = this ; if ( self.emptyCartBtn ) { self.emptyCartBtn.addEventListener("click", function() { self._emptyCart() ; } , true) ; } } , handleCheckoutOrderForm : function() { var self = this ; if ( self.checkoutOrderForm ) { var sameAsBilling = document.getElementById("same-as-billing") ; var fieldset = document.getElementById("fieldset-shipping") ; sameAsBilling.addEventListener("change", function() { self._slide(fieldset , sameAsBilling.checked) ; } , true) ; this.checkoutOrderForm.addEventListener("submit", function() { var valid = self._validateForm(this) ; if ( !valid ) { return valid ; } else { self._saveFormData(this) ; } } , true) ; } } , displayUserDetails : function() { var self = this ; if ( self.userDetails ) { var name = self.storage.getItem("billing-name") ; var email = self.storage.getItem("billing-email") ; var city = self.storage.getItem("billing-city") ; var address = self.storage.getItem("billing-address") ; var zip = self.storage.getItem("billing-zip") ; var country = self.storage.getItem("billing-country") ; if ( this.storage.getItem("shipping-name") == null ) { var html = "&lt;div class='detail'&gt;" ; html += "&lt;h2&gt;Billing and Shipping&lt;/h2&gt;" ; html += "&lt;ul&gt;" ; html += "&lt;li&gt;" + name + "&lt;/li&gt;" ; html += "&lt;li&gt;" + email + "&lt;/li&gt;" ; html += "&lt;li&gt;" + city + "&lt;/li&gt;" ; html += "&lt;li&gt;" + address + "&lt;/li&gt;" ; html += "&lt;li&gt;" + zip + "&lt;/li&gt;" ; html += "&lt;li&gt;" + country + "&lt;/li&gt;" ; html += "&lt;ul&gt;&lt;/div&gt;" ; } else { var sName = self.storage.getItem("shipping-name") ; var sEmail = self.storage.getItem("shipping-email") ; var sCity = self.storage.getItem("shipping-city") ; var sAddress = self.storage.getItem("shipping-address") ; var sZip = self.storage.getItem("shipping-zip") ; var sCountry = self.storage.getItem("shipping-country") ; var html = "&lt;div class='detail'&gt;" ; html += "&lt;h2&gt;Billing&lt;/h2&gt;" ; html += "&lt;ul&gt;" ; html += "&lt;li&gt;" + name + "&lt;/li&gt;" ; html += "&lt;li&gt;" + email + "&lt;/li&gt;" ; html += "&lt;li&gt;" + city + "&lt;/li&gt;" ; html += "&lt;li&gt;" + address + "&lt;/li&gt;" ; html += "&lt;li&gt;" + zip + "&lt;/li&gt;" ; html += "&lt;li&gt;" + country + "&lt;/li&gt;" ; html += "&lt;ul&gt;&lt;/div&gt;" ; html += "&lt;div class='detail right'&gt;" ; html += "&lt;h2&gt;Shipping&lt;/h2&gt;" ; html += "&lt;ul&gt;" ; html += "&lt;li&gt;" + sName + "&lt;/li&gt;" ; html += "&lt;li&gt;" + sEmail + "&lt;/li&gt;" ; html += "&lt;li&gt;" + sCity + "&lt;/li&gt;" ; html += "&lt;li&gt;" + sAddress + "&lt;/li&gt;" ; html += "&lt;li&gt;" + sZip + "&lt;/li&gt;" ; html += "&lt;li&gt;" + sCountry + "&lt;/li&gt;" ; html += "&lt;ul&gt;&lt;/div&gt;" ; } self.userDetails.innerHTML = html ; } } , populatePaypalForm : function() { var self = this ; if ( self.paypalForm ) { var form = self.paypalForm ; var cart = self._toJSONObject(self.storage.getItem(self.cartName)) ; var shipping = self.storage.getItem(self.shippingRates) ; var numShipping = self._convertString(shipping) ; var cartItems = cart.items ; var singShipping = Math.floor(numShipping / cartItems.length) ; form.getAttributeNode("action").value = self.paypalURL ; var business = document.getElementsByName("business")[0] ; business.value = self.paypalBusinessEmail ; var currencyCode = document.getElementsByName("currency_code")[0] ; currencyCode.value = self.paypalCurrency ; var x ; var len = cartItems.length ; for ( x = 0 ; x &lt; len ; x++ ) { var cartItem = cartItems[x] ; var n = x + 1 ; var name = cartItem.product ; var price = cartItem.price ; var qty = cartItem.qty ; var paypalBtn = document.getElementById("paypal-btn") ; var div1 = document.createElement("div") ; div1.innerHTML = "&lt;input type ='hidden' name='quantity_" + n + "' value='" + qty + "' /&gt;" ; form.insertBefore(div1 , paypalBtn) ; var div2 = document.createElement("div") ; div2.innerHTML = "&lt;input type ='hidden' name='item_name_" + n + "' value='" + name + "' /&gt;" ; form.insertBefore(div2 , paypalBtn) ; var div3 = document.createElement("div") ; div3.innerHTML = "&lt;input type ='hidden' name='item_number_" + n + "' value='SKU " + name + "' /&gt;" ; form.insertBefore(div3 , paypalBtn) ; var div4 = document.createElement("div") ; div4.innerHTML = "&lt;input type ='hidden' name='amount_" + n + "' value='" + self._formatNumber(price , 2) + "' /&gt;" ; form.insertBefore(div4 , paypalBtn) ; var div5 = document.createElement("div") ; div5.innerHTML = "&lt;input type ='hidden' name='shipping_" + n + "' value='" + self._formatNumber(singShipping , 2) + "' /&gt;" ; form.insertBefore(div5 , paypalBtn) ; } } } , // Private functions _slide : function( th , checked ) { if ( checked ) { th.style.display = "none" ; } else { th.style.display = "block" ; } } , _emptyCart : function() { this.storage.clear() ; } , _formatNumber : function( num , places ) { var n = num.toFixed(places) ; return n ; } , _extractPrice : function( element ) { var self = this ; var text = element.innerHTML() ; var price = text.replace(self.currencyString , "") ; price = price.replace(" " , "") ; price = price.trim() ; return price ; } , _convertString : function( numStr ) { var num ; if ( /^[-+]?[0-9]+.[0-9]+$/.test(numStr) ) { num = parseFloat(numStr) ; } else if ( /^d+$/.test(numStr) ) { num = parseInt(numStr) ; } else { num = Number(numStr) ; } if ( !isNaN(num) ) { return num ; } else { console.log(num + " cannot be converted into a number.") ; return false ; } } , _convertNumber : function( n ) { var str = n.toString() ; return str ; } , _toJSONObject : function( str ) { var obj = JSON.parse(str) ; return obj ; } , _toJSONString : function( obj ) { var str = JSON.stringify(obj) ; return str ; } , _addToCart : function( values ) { var self = this ; var cart = self.storage.getItem(self.cartName) ; var cartObject = self._toJSONObject(cart) ; var items = cartObject.items ; items.push(values) ; self.storage.setItem(self.cartName , self._toJSONString(cartObject)) ; } , _calculateShipping : function( qty ) { var shipping = 0 ; if ( qty &gt;= 6 ) { shipping = 10 ; } if ( (qty &gt;= 12) &amp;&amp; (qty &lt;= 30) ) { shipping = 20 ; } if ( (qty &gt;= 30) &amp;&amp; (qty &lt;= 60) ) { shipping = 30 ; } if ( qty &gt; 60 ) { shipping = 0 ; } return shipping ; } , _validateForm : function( form ) { var self = this ; var fields = self.requiredFields ; var visibleSet = form.getElementsByTagName("fieldset") ; var valid = true ; visibleSet = Array.from(visibleSet) ; visibleSet.forEach(function( fieldset ) { var inputs = fieldset.getElementsByTagName("input") ; inputs = Array.from(inputs) ; inputs.forEach(function( input ) { var type = input.getAttribute("data-type") ; var msg = input.getAttribute("data-message") ; if ( type == "string" ) { if ( input.value == fields.str.value ) { var error_msg = document.createElement("span") ; var error_msg_class = document.createAttribute("class") ; error_msg_class.value = "message" ; error_msg.setAttributeNode(error_msg_class) ; var error_msg_txt = document.createTextNode(msg) ; error_msg.appendChild(error_msg_txt) ; this.insertBefore(error_msg , input) ; valid = false ; } } else { if ( !fields.expression.value.test(input.value) ) { var error_msg = document.createElement("span") ; var error_msg_class = document.createAttribute("class") ; error_msg_class.value = "message" ; error_msg.setAttributeNode(error_msg_class) ; var error_msg_txt = document.createTextNode(msg) ; error_msg.appendChild(error_msg_txt) ; this.insertBefore(error_msg , input) ; valid = false ; } } } ) ; } ) ; return valid ; } , _saveFormData : function( form ) { var self = this ; var sameAsBilling = document.getElementById("same-as-billing") ; var visibleSet = form.getElementsByTagName("fieldset") ; visibleSet = Array.from(visibleSet) ; visibleSet.forEach(function( set ) { if ( set.id == "fieldset-billing" ) { var name = document.getElementById("name").value ; var email = document.getElementById("email").value ; var city = document.getElementById("city").value ; var address = document.getElementById("address").value ; var zip = document.getElementById("zip").value ; var country = document.getElementById("country").value ; self.storage.setItem("billing-name" , name) ; self.storage.setItem("billing-email" , email) ; self.storage.setItem("billing-city" , city) ; self.storage.setItem("billing-address" , address) ; self.storage.setItem("billing-zip" , zip) ; self.storage.setItem("billing-country" , country) ; } else { if ( !sameAsBilling.checked ) { var sName = document.getElementById("sname").value ; var sEmail = document.getElementById("semail").value ; var sCity = document.getElementById("scity").value ; var sAddress = document.getElementById("saddress").value ; var sZip = document.getElementById("szip").value ; var sCountry = document.getElementById("scountry").value ; self.storage.setItem("shipping-name" , sName) ; self.storage.setItem("shipping-email" , sEmail) ; self.storage.setItem("shipping-city" , sCity) ; self.storage.setItem("shipping-address" , sAddress) ; self.storage.setItem("shipping-zip" , sZip) ; self.storage.setItem("shipping-country" , sCountry) ; } } } ) ; } } ; (function() { var shop = new Shop("site") ; })() ; })() ; </code></pre> <p><strong>cart.html</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Shopping Cart&lt;/title&gt; &lt;meta name="author" content="Jeffrey B. Madden" /&gt; &lt;meta name="generator" content="othermindparadigm" /&gt; &lt;meta http-equiv="content-type" content="text/html;charset=utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="cart.html" method="post" id="shopping-cart"&gt; &lt;table class="shopping-cart"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Item&lt;/th&gt; &lt;th&gt;Qty&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;&lt;b&gt;Sub Total: &lt;/b&gt;&lt;span id="stotal"&gt;&lt;/span&gt;&lt;/p&gt; &lt;ul id="shopping-cart-actions"&gt; &lt;li&gt;&lt;input type="submit" name="update" id="update-cart" class="btn" value="Update cart" /&gt;&lt;/li&gt; &lt;li&gt;&lt;input type="submit" name="delete" id="empty-cart" class="btn" value="Empty cart" /&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html" class="btn"&gt;Continue Shopping&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="checkout.html" class="btn"&gt;Go To Checkout&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/form&gt; &lt;script type="text/javascript" src="js/javascript-shop.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>checkout.html</strong></p> <pre><code>&lt;html&gt; &lt;!-- All code written by Jeffrey B. Madden 2019. --&gt; &lt;head&gt; &lt;title&gt;Checkout&lt;/title&gt; &lt;meta name="author" content="Jeffrey B. Madden" /&gt; &lt;meta name="generator" content="othermindparadigm" /&gt; &lt;meta http-equiv="content-type" content="text/html;charset=utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="checkout-cart" class="shopping-cart"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Item&lt;/th&gt; &lt;th&gt;Qty&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;div id="pricing"&gt; &lt;p id="shipping"&gt;&lt;b&gt;Shipping: &lt;/b&gt;&lt;span id="sshipping"&gt;&lt;/span&gt;&lt;/p&gt; &lt;p id="sub-total"&gt;&lt;b&gt;Total: &lt;/b&gt;&lt;span id="stotal"&gt;&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;form action="order.html" method="post" id="checkout-order-form"&gt; &lt;h2&gt;Your Details&lt;/h2&gt; &lt;fieldset id="fieldset-billing"&gt; &lt;legend&gt;Billing&lt;/legend&gt; &lt;div&gt; &lt;label for="name"&gt;Name&lt;/label&gt; &lt;input type="text" name="name" id="name" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="email"&gt;Email&lt;/label&gt; &lt;input type="text" name="email" id="email" data-type="expression" data-message="Not a valid email address" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="city"&gt;City&lt;/label&gt; &lt;input type="text" name="city" id="city" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="address"&gt;Address&lt;/label&gt; &lt;input type="text" name="address" id="address" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="zip"&gt;ZIP Code&lt;/label&gt; &lt;input type="text" name="zip" id="zip" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="country"&gt;Country&lt;/label&gt; &lt;select name="country" id="country" data-type="string" data-message="This field may not be empty"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;option value="US"&gt;USA&lt;/option&gt; &lt;option value="IT"&gt;Italy&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;div id="shipping-same"&gt;Same as billing &lt;input type="checkbox" id="same-as-billing" value="" /&gt;&lt;/div&gt; &lt;fieldset id="fieldset-shipping"&gt; &lt;legend&gt;Shipping&lt;/legend&gt; &lt;div&gt; &lt;label for="name"&gt;Name&lt;/label&gt; &lt;input type="text" name="name" id="sname" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="email"&gt;Email&lt;/label&gt; &lt;input type="text" name="email" id="semail" data-type="expression" data-message="Not a valid email address" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="city"&gt;City&lt;/label&gt; &lt;input type="text" name="city" id="scity" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="address"&gt;Address&lt;/label&gt; &lt;input type="text" name="address" id="saddress" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="zip"&gt;ZIP Code&lt;/label&gt; &lt;input type="text" name="zip" id="szip" data-type="string" data-message="This field may not be empty" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="country"&gt;Country&lt;/label&gt; &lt;select name="country" id="scountry" data-type="string" data-message="This field may not be empty"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;option value="US"&gt;USA&lt;/option&gt; &lt;option value="IT"&gt;Italy&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;p&gt;&lt;input type="submit" id="submit-order" class="btn" value="Submit" /&gt;&lt;/p&gt; &lt;/form&gt; &lt;script type="text/javascript" src="js/javascript-shop.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>index.html</strong></p> <pre><code>&lt;html&gt; &lt;!-- All code written by Jeffrey B. Madden 2019. --&gt; &lt;head&gt; &lt;title&gt;Index&lt;/title&gt; &lt;meta name="author" content="Jeffrey B. Madden" /&gt; &lt;meta name="generator" content="othermindparadigm" /&gt; &lt;meta http-equiv="content-type" content="text/html;charset=utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="site"&gt; &lt;div class="product-description"&gt; &lt;h3 class="product-name"&gt;Wine #1&lt;/h3&gt; &lt;p class="product-price"&gt;5.00&lt;/p&gt; &lt;form action="cart.html" method="post" class="add-to-cart"&gt; &lt;div&gt; &lt;label for="qty-1"&gt;Quantity&lt;/label&gt; &lt;input type="text" name="qty-1" id="qty-1" class="qty" value="1" /&gt; &lt;p&gt;&lt;input type="submit" value="Add to cart" class="btn" /&gt;&lt;/p&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="product-description"&gt; &lt;h3 class="product-name"&gt;Wine #2&lt;/h3&gt; &lt;p class="product-price"&gt;7.00&lt;/p&gt; &lt;form action="cart.html" method="post" class="add-to-cart"&gt; &lt;div&gt; &lt;label for="qty-1"&gt;Quantity&lt;/label&gt; &lt;input type="text" name="qty-1" id="qty-1" class="qty" value="1" /&gt; &lt;p&gt;&lt;input type="submit" value="Add to cart" class="btn" /&gt;&lt;/p&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="js/javascript-shop.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>order.html</strong></p> <pre><code>&lt;html&gt; &lt;!-- All code written by Jeffrey B. Madden 2019. --&gt; &lt;head&gt; &lt;title&gt;Order&lt;/title&gt; &lt;meta name="author" content="Jeffrey B. Madden" /&gt; &lt;meta name="generator" content="othermindparadigm" /&gt; &lt;meta http-equiv="content-type" content="text/html;charset=utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Your Order&lt;/h1&gt; &lt;table id="checkout-cart" class="shopping-cart"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Item&lt;/th&gt; &lt;th&gt;Qty&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;div id="pricing"&gt; &lt;p id="shipping"&gt;&lt;b&gt;Shipping: &lt;/b&gt;&lt;span id="sshipping"&gt;&lt;/span&gt;&lt;/p&gt; &lt;p id="sub-total"&gt;&lt;b&gt;Total: &lt;/b&gt;&lt;span id="stotal"&gt;&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id="user-details"&gt; &lt;h2&gt;Your Data&lt;/h2&gt; &lt;div id="user-details-content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;form action="" method="post" id="paypal-form"&gt; &lt;input type="hidden" name="cmd" value="_cart" /&gt; &lt;input type="hidden" name="upload" value="1" /&gt; &lt;input type="hidden" name="business" value="" /&gt; &lt;input type="hidden" name="currency_code" value="" /&gt; &lt;input type="submit" id="paypal-btn" class="btn" value="Pay with Paypal" /&gt; &lt;/form&gt; &lt;script type="text/javascript" src="js/javascript-shop.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:10:28.113", "Id": "408160", "Score": "2", "body": "[Broken code](https://CodeReview.meta.StackExchange.com/a/3650) is off-topic for this site. Please [follow the tour](https://CodeReview.StackExchange.com/tour) and read [\"How do I ask a good question?\"](https://CodeReview.StackExchange.com/help/how-to-ask), [\"What topics can I ask about here?\"](https://CodeReview.StackExchange.com/help/on-topic) and [\"What types of questions should I avoid asking?\"](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:47:39.267", "Id": "408169", "Score": "0", "body": "That was working code but, I added full code anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:02:39.000", "Id": "408173", "Score": "0", "body": "If your intention is only to get suggested improvements for *working* code, then you should edit your title and your question body to reflect that, and remove the code that is not working as intended. If your main goal is to fix a bug or add functionality, then I'm afraid your question is fundamentally at odds with the purpose of this site, as our [help/on-topic] explains." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:21:32.730", "Id": "408180", "Score": "2", "body": "@Graham changed title, context, and code added. Is that better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:25:54.590", "Id": "408181", "Score": "1", "body": "Looks good to me. As long as everything works as intended to the best of your knowledge, you're good to go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:28:44.867", "Id": "408182", "Score": "0", "body": "@Graham everything does work. the only issue I have is using `this.element`. I wanted to use it when I make `getElementById()` calls but, javascript wants `document` as it is the owner of the element. How can I make use of my `this.element` property?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:42:41.953", "Id": "408183", "Score": "0", "body": "Unfortunately, I'm not familiar enough with Javascript to answer that, but I would recommend doing some searches on Stack Overflow and asking a question there if you can't find an answer (though it sounds like something that might have been asked before). Just remember to read the [How to ask](https://stackoverflow.com/help/how-to-ask) page before asking if you decide to ask a question there." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T14:56:42.083", "Id": "211111", "Score": "2", "Tags": [ "javascript", "html" ], "Title": "My first vanilla Javascript shopping cart" }
211111
<p>I'm sure everyone here knows what <a href="https://en.wikipedia.org/wiki/Fizz_buzz" rel="noreferrer">FizzBuzz</a> is. I would like constructive criticism for my solution.</p> <p>I'm a beginner to programming as a whole and this isn't my first solution, but it's what I think is my best solution. I'd like to see if this is a reasonable solution, or is just plain terrible.</p> <pre><code>for(var i=1;i&lt;=100;i++) { var output = ""; if(i % 15 == 0) {output = "FizzBuzz"} else if(i % 3 == 0) {output = "Fizz"} else if(i % 5 == 0) {output = "Buzz"} else {output = i;} console.log(output); } </code></pre> <p>The output is correct. It's your standard FizzBuzz output.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:36:18.150", "Id": "408150", "Score": "5", "body": "It's hard to give constructive criticism on such a small, simple function. It's a reasonable solution and the only things I could pick out being _wrong_ would be me being extremely picky or a personal preference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:37:44.577", "Id": "408151", "Score": "7", "body": "You could go with `var output = i;` and then remove that final `else` block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:39:36.473", "Id": "408322", "Score": "0", "body": "One possible issue is you are relying on a standard fizzbuzz using 3 and 5 (hence checking for 3 * 5 as 15). Someone might give you a test using 2 and 4 to see if you fell into the trap of checking for 8." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:39:53.997", "Id": "408368", "Score": "0", "body": "It would be better to include the actual spec you are following. The FizzBuzz solution looks fine. Any extra points goes to how you follow the nuance of the spec. If you really wanted to get fancy, you could do it without the explicit \"FizzBuzz\" part of the algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:45:46.167", "Id": "410408", "Score": "0", "body": "This question is [being discussed on meta](https://codereview.meta.stackexchange.com/q/9068/120114)." } ]
[ { "body": "<p>I think it's fine as is, though some folks like to return early instead of using a series of if..else. For example:</p>\n\n<pre><code>function calc(i) {\n if(i % 15 == 0) return \"FizzBuzz\";\n if(i % 3 == 0) return \"Fizz\";\n if(i % 5 == 0) return \"Buzz\";\n return i;\n}\n\nfor(var i=1;i&lt;=100;i++) {\n console.log(calc(i));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T18:59:14.383", "Id": "408426", "Score": "1", "body": "\"Returning early\" is often called \"multiple exit points\" and is sometimes considered poor practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T11:22:59.917", "Id": "408501", "Score": "8", "body": "\"Returning early\" is often called \"validation\" and is often considered good practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T17:25:45.203", "Id": "408535", "Score": "3", "body": "Returning early has many names and people get very worked up about whether their way is best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T12:44:47.997", "Id": "408719", "Score": "1", "body": "@MobyDisk That advice is originally from Assembly, and referred to \"places to exit _to_\", not \"places to exit _from_\". That removes the \"it's always been done this way, so there must've been a reason\" argument. Before applying your revised version of this advice to a particular scenario, check whether it _actually makes sense_. In this case, it doesn't." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:51:58.690", "Id": "211115", "ParentId": "211113", "Score": "16" } }, { "body": "<blockquote>\n<p>I'd like to see if this is a reasonable solution, or is just plain terrible.</p>\n</blockquote>\n<p>I wouldn't say it is &quot;<em>terrible</em>&quot; - mostly because it works and doesn't appear to be very inefficient. However, there are some improvements that can be made.</p>\n<ul>\n<li><p><strong>use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity\" rel=\"nofollow noreferrer\">strict equality</a> comparison</strong> - i.e. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity\" rel=\"nofollow noreferrer\"><code>===</code></a> when comparing values. That way it won't need to convert the types.</p>\n</li>\n<li><p><strong>Style Guide</strong> Consider following a <a href=\"https://codeburst.io/5-javascript-style-guides-including-airbnb-github-google-88cbc6b2b7aa\" rel=\"nofollow noreferrer\">style guide</a>. Many common style guides advise separating keywords with a space - e.g. <code>if (</code> instead of <code>if(</code>.</p>\n</li>\n<li><p><strong>Use consistent indentation</strong> The first and last lines within the <code>for</code> loop are not indented, while the other lines between them are, though maybe it was the case that your code was indented properly but when you pasted here it was thrown off because of the markdown formatting...</p>\n</li>\n<li><p><strong>Abstract logic into a function</strong> As <a href=\"https://codereview.stackexchange.com/a/211115/120114\">Paul's answer</a> suggests: you can put the core logic into a function that returns the output but doesn't handle outputting the value (e.g. to the console). This allows such code to be atomic and testable - congruent with the <a href=\"https://deviq.com/single-responsibility-principle/\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. Also, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return\" rel=\"nofollow noreferrer\"><code>return</code></a> statement can eliminate the need for <code>else</code> keywords within a function. One drawback is that calling a function on each iteration may slow down operations but should be negligible for a set of numbers 1 through 100.</p>\n</li>\n</ul>\n<h3>Updated Code</h3>\n<p>Consider the modified code below, utilizing the feedback above. I also used this code in the code contained in my recent question: <a href=\"https://codereview.stackexchange.com/q/211731/120114\">Fizzbuzz with dynamic height container</a></p>\n<p><strong>Note</strong>: the inline console in the snippets is truncated to ~50 lines, but the complete console log should be visible in your browser console.</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 fizzBuzz(value) {\n if (value % 15 === 0) { return \"FizzBuzz\"; }\n if (value % 3 === 0) { return \"Fizz\"; }\n if (value % 5 === 0) { return \"Buzz\"; }\n return value;\n}\nfor (let i = 1; i &lt;= 100; i++) {\n console.log(fizzBuzz(i));\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>One option I did consider is to minimize the number of modulo operations, append to the output string instead of outputting it. If you are trying to optimize for speed, this might not be the approach to take because appending to the string may be much slower than doing an extra couple modulo operations. Try a comparison in <a href=\"https://jsperf.com/fizzbuzzjstechniques/1\" rel=\"nofollow noreferrer\">this jsPerf test</a>.</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 fizzBuzz(value) {\n let output = \"\";\n if (value % 3 === 0) { output += \"Fizz\"; }\n if (value % 5 === 0) { output += \"Buzz\"; }\n return output || value;\n}\nfor (let i = 1; i &lt;= 100; i++) {\n console.log(fizzBuzz(i));\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T22:01:35.103", "Id": "408215", "Score": "3", "body": "There is also the \"never use semicolons\" school. https://blog.izs.me/2010/12/an-open-letter-to-javascript-leaders-regarding https://feross.org/never-use-semicolons/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:43:54.580", "Id": "408304", "Score": "4", "body": "@CaseyB I don't think arguing about micro-optimizations like this when OP is a beginner is a good idea at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:34:55.270", "Id": "408319", "Score": "4", "body": "@Voile One million percent. Even if this were a production-ready, enterprise-grade, cloud-based microservice™, readability and maintainability is **always** the number one concern. The concept of micro-optimizing a JavaScript FizzBuzz is honestly hilarious." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:05:58.217", "Id": "408335", "Score": "8", "body": "@Michael [FizzBuzz Enterprise Edition](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition) begs to differ. :P But FWIW, I believe Casey was merely providing a counterargument for the microoptimization that the answer itself first suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T13:10:25.217", "Id": "408353", "Score": "2", "body": "@MateenUlhaq 260 issues... man, they really need to refactor it, arrange UATs, and use Kanban." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:46:36.060", "Id": "408372", "Score": "0", "body": "I think you are just looking for criticisms, and are largely judging style. Because of different styles of different developers, I can find a criticism of any code. If you want common style (which also has its potential downsides) just use a code formatter. Also, making a function \"just because\" can lead to difficult to maintain code (unnecessarily complex modularization). I typically don't modularize a code block into a function/method until said logic is used by two distinct code blocks, and then the logic needs to be complex enough to warrant it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:17:20.533", "Id": "408379", "Score": "2", "body": "@Tombo If it was my style vs your style, I would agree, but the OP has not used a consistent style (semi-colons sometimes but not always, indentation sometimes but not always). You can get these things with a formatter, sure, so the OP should use one. (Being a beginner, it's reasonable that they don't know this automatically, but it's something to learn.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:19:43.747", "Id": "408380", "Score": "0", "body": "@Voile Sure! But the \"improved\" string concatenation version was also more complex. It was more a comment that the added cleverness was misplaced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:04:55.193", "Id": "408389", "Score": "1", "body": "I do not agree with this one: `Consider default value`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:20:35.727", "Id": "408663", "Score": "0", "body": "@KorayTugay okay I have removed that part about the default value. In your opinion, is this an improvement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T01:34:47.687", "Id": "454444", "Score": "0", "body": "When I have a one-line `if` I usually remove the `{}` to make it a little cleaner, so `if (value % 15 === 0) return \"FizzBuzz\";`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T01:36:14.307", "Id": "454445", "Score": "1", "body": "Another nit-pick would be to use `let` instead of `var`" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:54:29.877", "Id": "211122", "ParentId": "211113", "Score": "53" } }, { "body": "<p>One of the problems is that the case where you check <code>i % 15</code> (i.e. <code>i</code> is a multiple of 3 and 5) is unnecessary. You have the concept of 3 and 5 repeated, and the concept of Fizz and Buzz repeated.</p>\n\n<p>This is not currently much of a problem but suppose someone asks you to extend your program to print \"Jazz\" when <code>i</code> is a multiple of 7. Using your current strategy we now need a case where <code>i</code> is a multiple of:</p>\n\n<ol>\n<li>3</li>\n<li>5</li>\n<li>7</li>\n<li>3 and 5</li>\n<li>3 and 7</li>\n<li>5 and 7</li>\n<li>3 and 5 and 7</li>\n</ol>\n\n<p>It would look something like this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>for(var i = 1;i &lt;= 100; i++) {\n var output = \"\";\n\n if(i % 105 == 0) {output = \"FizzBuzzJazz\"}\n else if(i % 15 == 0) {output = \"FizzBuzz\"}\n else if(i % 35 == 0) {output = \"BuzzJazz\"}\n else if(i % 21 == 0) {output = \"FizzJazz\"}\n else if(i % 3 == 0) {output = \"Fizz\"}\n else if(i % 5 == 0) {output = \"Buzz\"}\n else if(i % 7 == 0) {output = \"Jazz\"}\n else { output = i; }\n\n console.log(output);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>See how quickly that got out of hand? If we add a fourth word it becomes even worse.</p>\n\n<p>If we use a different strategy by <em>appending</em> text to the <code>output</code> variable, we can get away with having as few conditions as we have words.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>for(var i = 1; i &lt;= 100; i++) {\n var output = \"\";\n if (i % 3 === 0) {output += \"Fizz\";}\n if (i % 5 === 0) {output += \"Buzz\";}\n if (i % 7 === 0) {output += \"Jazz\";}\n\n console.log(output === \"\" ? i : output);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>(I've fixed a few other things as suggested <a href=\"https://codereview.stackexchange.com/a/211122/89839\">in Sam's answer</a>)</p>\n\n<p>One thing that might be new to you here, if you're a beginner, is that the expression used as the argument for <code>console.log</code> or called the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"noreferrer\"><em>conditional or ternary operator</em></a>. Ours says that if the output is blank (i.e. not a multiple of 3, 5 or 7) then print <code>i</code>, else print the string that we've compounded.</p>\n\n<p>The ternary operator can always be replaced by an if-statement if you're not yet comfortable with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T16:15:15.297", "Id": "408530", "Score": "0", "body": "@PatrickRoberts True. I wanted to focus more on the approach to solving the problem than those things. Buuut I did correct everything else (I couldn't help myself) so yeah I've made that change as well. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T16:23:09.593", "Id": "408532", "Score": "1", "body": "You forgot the equality in the ternary expression. I tried to edit myself but I can only make edits of at least 6 characters :|" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T14:43:41.947", "Id": "454519", "Score": "0", "body": "You're not wrong about the repetition of 3, 5 ,Fizz and Buzz, but you're biased on how to improve it. Consider a change where \"FizzBuzz\" now needs to be on a multiple of 13. Or a change where the multiple of 15 needs to be \"Floopidoops\". In these cases, OP's code is much easier to change than yours is. The issue here is whether you infer that the relationship between the multiples (3, 5, 15) , and the relationship between \"Fizz\", \"Buzz\" and \"FizzBuzz\", is **causal or coincidental**. It requires elaboration (= analysis) before you can make the right judgment call." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:22:58.340", "Id": "211174", "ParentId": "211113", "Score": "26" } }, { "body": "<p>From a maintenance stand point, I think it's better that you check for 3 and 5 instead of checking for 15. The issue with checking for 15 is that when you come back to your code 6 months from now, you won't realize that you were just printing fizzbuzz when something was divisible by both 3 and 5. That might matter in the future, but I think that's something worth talking about in an interview.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:22:49.063", "Id": "211205", "ParentId": "211113", "Score": "2" } }, { "body": "<p>Though your code is fine, another thing to look is amount of division happening the code, Division is computationally expensive operation and as @Michael has suggested that it is redundant. So always try to minimise the multiplication and division operation in your code. </p>\n\n<p>You have mentioned that you are a beginner programmer. I believe it is a good practice to start familiarising your self with topics like Computational Complexity.</p>\n\n<p>Look <a href=\"https://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations\" rel=\"nofollow noreferrer\">here</a> for computational complexity of mathematical functions</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T20:10:28.143", "Id": "408436", "Score": "0", "body": "While I think it's a bit early for a beginning programmer to be learning about things such as memory management (assuming this is one of their FIRST actual programs), I think this is a good answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:37:42.340", "Id": "408460", "Score": "4", "body": "This advice screams \"premature optimization\". Division is not an expensive operation. It's a bit more expensive that addition but it's not really expensive on today's computers. Your mobile phone can do millions of divisions in a fraction of a second. String concatenation is much more expensive, by far.\nThe most important metric in code quality is readability.\nAlso, if you are talking about computational complexity, you should note that your change won't change complexity at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T03:05:13.033", "Id": "408484", "Score": "1", "body": "The theoretical computational complexity of the underlying division algorithm is practically irrelevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T13:58:50.847", "Id": "408511", "Score": "0", "body": "@Sulthan The subject computational complexity doesn't take in to account how many operations a machine can perform, it takes into account how many operations/steps are required to solve a problem. While CC of addition i linear, division is quadratic. Dividing only by 3 and 5 would change the complexity and results of those can be saved in a bool variable which can be evaluated in constant time complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:08:53.707", "Id": "408512", "Score": "1", "body": "On a modern CPU integer division takes 1 CPU cycle, the JS version of `%` a little longer. JS will use 32bit signed ints when it can so the operation is insignificant in comparison to just calling a function. BTW the linked computational complexity page has nothing to do with how CPUs ALU and FLU process the basic math operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:12:58.427", "Id": "408513", "Score": "0", "body": "@Hemanshu I think you misunderstand what time complexity is. In time complexity the important metric is the amount of data, in this case the length of the `for` cycle. Everything inside is a constant, either with 2 or 3 divisions. Still a constant. The resulting time complexity is still O(n)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:02:39.053", "Id": "408518", "Score": "0", "body": "@Sulthan, i don't want to get into an argument here, you are completely ignoring the division fact." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:03:49.020", "Id": "408519", "Score": "0", "body": "@Blindman67 could you point me to the direction of the algorithm used for divisions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:49:51.137", "Id": "408525", "Score": "0", "body": "CPUs do these OPs using a combination of hardware and internal instruction sets (or pure hardware in simpler CPUs). There are many tricks that can be used so the logic steps to perform an OP will depend on the CPU. The operations are separated from the CPU and performed on dedicated hardware, called the, Arithmetic Logic Unit (ALU) , and Floating point Logic Unit (FLU or FPLU). Because these units CPU, ALU, FLU are independent they can often perform operations in parallel. Making it very hard to know what is most performant in high level languages such as Javascript. Google CPU ALU for more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:48:47.850", "Id": "408688", "Score": "0", "body": "@Hemanshu the underlying hardware algorithm does scale based on your estimate of complexity. However, Hardware dividers have fixed input lengths and guaranteed times rounded to the next clock cycle. As such the amount of time to divide 4/2 and 400000/200000 is the same because both are fed in as hardware words. Effectively for all word sized inputs the time is constant for all ALU operations. If you are implementing arbitrary length division algorithm then this you must apply the theoretical computational complexity. For hardware division it is fixed time for all operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:50:44.867", "Id": "408689", "Score": "0", "body": "Put another way if you are designing the CPU a 64 bit ALU divider will generally take 4 times longer than a 32 bit ALU divider and this impacts your timing and signal propogation (pipelining), but to the programmer this is irrelevant because the operation is constant time and constant input. 1 tick vs 2 for addition/division is noting compared 100 for cache miss due to memory access (even though this is \"O(1)\"). Complexity is only useful to compare the relative performance of different algorithms vs input size, once everything has been fixed in place only absolute time matters" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T01:40:44.200", "Id": "454447", "Score": "0", "body": "@Blindman67 Did you confuse \"1 CPU cylcle\" with \"1 machine instruction\"? If not, please provide an example for a CPU that actually divides in a single clock cycle. And by division I do not mean division by an integer constant, but division by an integer variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:51:16.557", "Id": "454458", "Score": "0", "body": "@RolandIllig Machine Instruction, I am old school A \"CPU cycle\" is time to cycle an instruction from fetch (instruction & data) to write (data) which is distinct from a Clock Tick as provided by CLK pin. Considering modern CPUs like the 10nm Penryn with Fast Radix DIV the fizzBuzz divide is at most 2 ticks (ignoring fetch and write). Maybe 8-7nm could double the space for DIV logic and provide DIV at 8bits per tick and we edge closer to single tick divide (if the machines word size does not grow)" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:07:43.553", "Id": "211211", "ParentId": "211113", "Score": "1" } }, { "body": "<p>Expanding on <a href=\"https://codereview.stackexchange.com/a/211174/96569\">Michael</a>'s answer, you could also create an object with all the words you want, with the key being the number your input must be divisible by, to make this more dynamic and a bit more future proof (A lot easier to add a new entry to the object versus adding more lines of code), and the object itself can also be dynamically generated.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>divisions = {3: \"Fizz\", 5: \"Buzz\", 7: \"Jazz\"};\n\nfor(var i = 1; i &lt;= 100; i++) {\n var output = \"\";\n\n for (var x in divisions) {\n if(i % x == 0) output += divisions[x]; \n }\n\n console.log(output == \"\" ? i : output);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T01:37:05.010", "Id": "454446", "Score": "0", "body": "How do you guarantee that Fizz always comes before Buzz? Unlike in PHP, in JavaScript the keys of an object are not in a deterministic order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T14:48:20.747", "Id": "454520", "Score": "0", "body": "@RolandIllig: With a change to the data structure, `divisions.sort(d => d.Value)` (or any variation thereof) fixes that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T18:56:32.693", "Id": "454549", "Score": "0", "body": "@Flater yep, I know that. I wanted to hear exactly that from Grumpy, since the answer is wrong in its current state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T14:29:39.717", "Id": "455896", "Score": "0", "body": "@RolandIllig I'm sorry, I don't really understand what you are asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T18:10:57.597", "Id": "455934", "Score": "0", "body": "Your code only works if the divisors and words are to be applied in order. In general, [the order of the words is not specified](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). Therefore your code works \"by accident\", not by design." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T18:17:30.820", "Id": "455938", "Score": "0", "body": "@RolandIllig So as Flater said above, I just need to sort the divisors to make sure it's in the correct order?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T07:27:57.730", "Id": "455990", "Score": "0", "body": "Yes. But then there's absolutely no reason to have the divisors in a map at all. An array is more appropriate." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T21:00:55.313", "Id": "211222", "ParentId": "211113", "Score": "4" } }, { "body": "<p>I tend to be somewhat \"literalist\", at least at first, when implementing algorithms. So I would start with this, and then optimize from there. I like that it keeps things very clear. </p>\n\n<pre><code>const calcFizzBuzz = function(num) {\n let result = \"\";\n if (num % 3 === 0) {\n result += \"Fizz\";\n if (num % 5 === 0) {\n result += \"Buzz\";\n }\n } \n else if (num % 5 === 0) {\n result += \"Buzz\";\n } \n else {\n result = num;\n }\n return result;\n}\n\nfor (let i = 0; i &lt; 100; i++) {\n console.log(calcFizzBuzz(i));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T01:43:41.007", "Id": "454448", "Score": "0", "body": "The repeated `if (num % 5 === 0) { result += \"Buzz\" }` is obviously redundant. Why do you prefer to write it this way?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T09:34:28.733", "Id": "211314", "ParentId": "211113", "Score": "3" } } ]
{ "AcceptedAnswerId": "211122", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:26:17.540", "Id": "211113", "Score": "24", "Tags": [ "javascript", "beginner", "fizzbuzz", "iteration" ], "Title": "FizzBuzz in Javascript" }
211113
<p>I wrote this to make the "callback hell" more manageable on the part of the coder when using Socket IO, so that there wasn't really any callback hell to go with, just a simple await.</p> <p>This should work with any socket implementation, so long as it has <code>socket.on</code>, <code>socket.emit</code>, and <code>socket.removeListener</code>.</p> <pre><code>function emit_and_wait(socket, emit, data, wait_key, max_wait = 1000, error_on_timeout = true) { return new Promise(function(resolve, reject) { let responded = false, callback, removed = false; if(!socket) { reject("Socket supplied is not valid.") } else if(socket.disconnected) { reject("Socket is disconnected"); } let timeout = setTimeout(function() { if(!responded) { if(error_on_timeout) { reject("Socket timeout"); } else { resolve(null); } responded = true; if(!removed) { socket.removeListener(wait_key, callback); removed = true; } } }, max_wait) callback = function(data) { if(!removed) { socket.removeListener(wait_key, callback); } if(!responded) { resolve(data); clearTimeout(timeout); } } socket.on(wait_key, callback); socket.emit(emit, data) }) } </code></pre>
[]
[ { "body": "<p>You have a few flags (<code>removed</code>, <code>responded</code>) which are almost equivalent and possibly useless. <code>removeListener()</code> won't cause any error if listener has been already removed then <code>removed</code> is unnecessary. After you called <code>removeListener()</code> your callback won't be called then also <code>responded</code> (which BTW is a misleading name) is unnecessary. Also, <code>setTimeout()</code> won't call its callback twice then again <code>responded</code> isn't necessary.</p>\n\n<p>Use <code>const</code> instead of <code>let</code> whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:</p>\n\n<pre><code>if (!socket) {\n reject(\"Socket supplied is not valid.\");\n return;\n}\n\nif (socket.disconnected) {\n reject(\"Socket is disconnected\");\n return;\n}\n\nconst timeout = setTimeout(() =&gt; {\n socket.removeListener(wait_key, callback);\n\n if (error_on_timeout) {\n reject(\"Socket timeout\");\n } else {\n resolve(null);\n }\n}, max_wait)\n\nconst callback = (data) =&gt; {\n clearTimeout(timeout);\n socket.removeListener(wait_key, callback);\n resolve(data);\n};\n\nsocket.on(wait_key, callback);\nsocket.emit(emit, data)\n</code></pre>\n\n<p>Few more notes: <code>resolve()</code> and <code>reject()</code> won't stop execution then you need to add the proper <code>return</code>. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:40:56.930", "Id": "211207", "ParentId": "211117", "Score": "2" } } ]
{ "AcceptedAnswerId": "211207", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:56:19.380", "Id": "211117", "Score": "2", "Tags": [ "javascript", "asynchronous", "socket", "async-await", "socket.io" ], "Title": "Await socket Response" }
211117
<p>I've written a generic data adapter that can make use of a cache, for use in a data access layer. It presents an interface allowing CRUD operations, as well as retrieving all objects of a certain type.</p> <p>IEntity.cs:</p> <pre><code>using System; namespace GenericDataAdapter { public interface IEntity { Guid Id { get; set; } } } </code></pre> <p>IDataAdapter.cs:</p> <pre><code>using System; using System.Collections.Generic; using System.Threading.Tasks; namespace GenericDataAdapter { public interface IDataAdapter&lt;T&gt; where T : IEntity { Task&lt;IEnumerable&lt;T&gt;&gt; ReadAllAsync(); Task&lt;(bool, T)&gt; ReadAsync(Guid id); // bool indicates whether entity was present in data source Task SaveAsync(T newData); // update if present, create if not present Task DeleteAsync(Guid id); } } </code></pre> <p>CacheDataAdapter.cs:</p> <pre><code>using System; using System.Collections.Generic; using System.Threading.Tasks; namespace GenericDataAdapter { public class CacheDataAdapter&lt;T&gt; : IDataAdapter&lt;T&gt; where T : IEntity { private IDataAdapter&lt;T&gt; PrimaryDataSource; private IDataAdapter&lt;T&gt; Cache; public CacheDataAdapter(IDataAdapter&lt;T&gt; primaryDataSource, IDataAdapter&lt;T&gt; cache) { PrimaryDataSource = primaryDataSource; Cache = cache; } public Task&lt;IEnumerable&lt;T&gt;&gt; ReadAllAsync() { return PrimaryDataSource.ReadAllAsync(); } // can potentially return stale data, due to SaveAsync()/DeleteAsync() not being atomic public async Task&lt;(bool, T)&gt; ReadAsync(Guid id) { var (presentInCache, cacheData) = await Cache.ReadAsync(id); if (presentInCache) { return (true, cacheData); } var (presentInPrimary, primaryData) = await PrimaryDataSource.ReadAsync(id); if (presentInPrimary) { await Cache.SaveAsync(primaryData); return (true, primaryData); } else { return (false, default(T)); } } public async Task SaveAsync(T newData) { await Cache.SaveAsync(newData); await PrimaryDataSource.SaveAsync(newData); } public async Task DeleteAsync(Guid id) { await Cache.DeleteAsync(id); await PrimaryDataSource.DeleteAsync(id); } } } </code></pre> <p>There are two points I'd like feedback on, though all comments are welcome:</p> <ul> <li>In <code>CacheDataAdapter.ReadAllAsync()</code>, should I use <code>await</code>? It doesn't seem like I should, since I'm just passing through the return value of <code>PrimaryDataSource.ReadAllAsync()</code>, but I'm not sure.</li> <li>I'm not sure whether unifying the create and update operations into <code>SaveAsync()</code> is a good idea; it puts the responsibility for fully initializing objects on the application. That's why I'm using GUIDs as the identifier, so the application can generate unique IDs without having to consult the database first.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:57:15.670", "Id": "408681", "Score": "0", "body": "In your `SaveAsync` and `DeleteAsync` methods I would switch around the order of writing to the primary datasource first then the cache. Looking at this from a defensive principle the current implementation could be an issue. Should the save/delete to the primary datasource fail the cache would cover this until it expires. The other way around allows your `ReadAsync` method to handle the case and retry save to the cache transparently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T20:16:50.530", "Id": "429284", "Score": "0", "body": "@DylanSp Having a unique identifier, whether it's a business or technical id, is never a bad idea, regardless whether it represents the primary key in a database." } ]
[ { "body": "<p>Typically this scenario is done with a decorator pattern where you would wrap just the one and have the cache functionality in the one class. You would put the code in the CacheDataAdapter that I assume is currently in the code of the IDataAdapter cache. Most of the time this will simplify your code as you can call base method to get the values if not in the backing store for the cache. </p>\n\n<p>For example if you are using the ConcurrentDictionary or MemoryCache they will have methods to GetOrCreate or AddOrUpdate that will take a lamba expression that you can call into your base method to get the value if missing. Since you are doing async work while caching you should check out the <a href=\"https://blogs.msdn.microsoft.com/pfxteam/2011/01/15/asynclazyt/\" rel=\"nofollow noreferrer\">AsyncLazy</a></p>\n\n<p>If you don't want to do the decorator pattern I would swap Save and Delete to do it in the primary store before removing them from the cache. You could have a situation where the save fails in the primary but your cache is updated to say it's good. </p>\n\n<p>As far if you should await the ReadAllAsync or not it doesn't matter a lot. I personally wouldn't await it but either way is fine. See <a href=\"https://stackoverflow.com/a/17887084\">answer</a> on SO</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T13:47:06.707", "Id": "408358", "Score": "0", "body": "I figured I'd separate the implementation of caching logic into CacheDataAdapter, while another implementation of IDataAdapter would handle the lower-level logic of connecting to a specific cache solution like Redis." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:47:47.193", "Id": "211134", "ParentId": "211120", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:20:23.523", "Id": "211120", "Score": "2", "Tags": [ "c#", "async-await", "cache" ], "Title": "Generic Cache-Aware Data Adapter" }
211120
<p>My initial problem is to transform a <code>List</code> of <code>Mapping</code>s whose values are <code>List</code>s of values. The transformed list must contain the Cartesian product of all lists (those that are values in the dictionaries) that belong to separate dictionaries (in other words, the values of the lists present in the same directories are "coupled").</p> <p>Basically, if you disregard the keys of the dictionaries, this would be solved simply with <code>itertools.product</code>.</p> <p><strong>Input:</strong></p> <pre><code>[ { ('B3G', 'B1'): [1.0, 2.0], ('B1G', 'B1'): [11.0, 12.0] }, { ('B2G', 'B1'): [1.5, 2.5, 3.5] } ] </code></pre> <p><strong>Output:</strong></p> <pre><code>[ {('B3G', 'B1'): 1.0, ('B1G', 'B1'): 11.0, ('B2G', 'B1'): 1.5}, {('B3G', 'B1'): 1.0, ('B1G', 'B1'): 11.0, ('B2G', 'B1'): 2.5}, {('B3G', 'B1'): 1.0, ('B1G', 'B1'): 11.0, ('B2G', 'B1'): 3.5}, {('B3G', 'B1'): 2.0, ('B1G', 'B1'): 12.0, ('B2G', 'B1'): 1.5}, {('B3G', 'B1'): 2.0, ('B1G', 'B1'): 12.0, ('B2G', 'B1'): 2.5}, {('B3G', 'B1'): 2.0, ('B1G', 'B1'): 12.0, ('B2G', 'B1'): 3.5} ] </code></pre> <p>To make the matter more confusing, the keys of each dictionaries are <code>Tuple</code>s of strings.</p> <p>Here is a possible implementation, using a <code>class</code> to isolate the whole mess.</p> <pre><code>@dataclass class ParametricMapping: """Abstraction for multi-dimensional parametric mappings.""" mappings: List[Mapping[Tuple[str], Sequence[float]]] = field(default_factory=lambda: [{}]) @property def combinations(self) -&gt; List[Mapping[Tuple[str], float]]: """Cartesian product adapted to work with dictionaries, roughly similar to `itertools.product`.""" labels = [label for arg in self.mappings for label in tuple(arg.keys())] pools = [list(map(tuple, zip(*arg.values()))) for arg in self.mappings] def cartesian_product(*args): """Cartesian product similar to `itertools.product`""" result = [[]] for pool in args: result = [x + [y] for x in result for y in pool] return result results = [] for term in cartesian_product(*pools): results.append([pp for p in term for pp in p]) tmp = [] for r in results: tmp.append({k: v for k, v in zip(labels, r)}) if len(tmp) == 0: return [{}] else: return tmp </code></pre> <p><strong>Question</strong>: How can I improve this to make it cleaner (priority #1) and faster (#2)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:21:32.733", "Id": "408316", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p><strong>TL;DR:</strong> Scroll to the end for the provided code with suggested improvements</p>\n\n<h1>Suggestions</h1>\n\n<h3>1. Standalone <code>cartesian_product</code> helper function outside scope of <code>combinations</code></h3>\n\n<p>A preferable solution would be to simply use <code>itertools.product</code> as most Python-savvy readers will be familiar with it - and it is well-documented for those that aren’t. However, since you explicitly mention it...</p>\n\n<p><em>If you still don't want to use <code>itertools.product</code>:</em></p>\n\n<p>While it does improve clarity to construct a hierarchy of scopes that expose things only when necessary, in this case, I believe that making <code>cartesian_product</code> a nested function inside <code>combinations</code> serves only to confuse the purpose of <code>combinations</code>. It is better to define <code>cartesian_product</code> above, making the code below cleaner and easier to understand. Now someone reading your code will first see <code>cartesian_product</code>’s definition and understand its relatively simple purpose. Then, inside <code>ParametricMapping.combinations</code>, readers are already familiar with <code>cartesian_product</code>, and their train of thought isn’t derailed by trying to understand a nested function.</p>\n\n<h3>2. <code>flatten</code> helper function</h3>\n\n<p>This helper function should be used thusly: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for term in cartesian_product(*pools):\n results.append(flatten(term))\n</code></pre>\n\n<p>This may seem silly as flattening is a simple operation, but in this example there are a few fairly tricky list/dict comprehensions nearby. Therefore, it may help to replace that piece with a simple <code>flatten</code> call to clean up some confusion and to emphasize that this is a straight-forward operation - A fact that could be lost on some readers of the code in its current state. My point here is that stacking lots of loops and comprehensions on top of each other (especially without documentation/comments) can quickly get messy and confusing.</p>\n\n<h3>3. Consolidate some code</h3>\n\n<p>If you took both of the above suggestions, a nice opportunity to consolidate some code has presented itself. After the above changes, the section that was originally</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>results = []\nfor term in cartesian_product(*pools):\n results.append([pp for p in term for pp in p])\n</code></pre>\n\n<p>should now be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>results = []\nfor term in itertools.product(*pools):\n results.append(flatten(term))\n</code></pre>\n\n<p>This block can be expressed clearly and concisely with the following list comprehension: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>results = [flatten(term) for term in itertools.product(*pools)]\n</code></pre>\n\n<p>Note that because of the separation of functionality into helper functions, the purpose of this list comprehension is abundantly clear. It creates <code>results</code>, which is a list containing the <code>flatten</code>ed outputs of <code>product</code>.</p>\n\n<h3>4. Check for empty <code>mappings</code> at top of <code>combinations</code></h3>\n\n<p>Instead of the if/else at the end of <code>combinations</code> that checks for <code>len(tmp) == 0</code>, make the first two lines of <code>combinations</code> the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if self.mappings == [{}]:\n return [{}]\n</code></pre>\n\n<p>The <code>else</code> clause at the bottom of <code>combinations</code> is no longer necessary, and you can simply <code>return tmp</code>. This is cleaner because it handles the case where <code>mappings</code> is empty immediately, which means those cases bypass all the code that was being executed before when <code>len(tmp)</code> was evaluated at the end of <code>combinations</code>. This also allows readers to make the assumption that <code>mappings</code> is non-empty when they get into the actual work being done by <code>combinations</code>, which is just one less thing to worry about. Alternatively, a more concise option would be to replace</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if len(tmp) == 0:\n return [{}]\nelse:\n return tmp\n</code></pre>\n\n<p>with</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return tmp or [{}]\n</code></pre>\n\n<p>This works because if <code>mappings</code> is empty, the value of <code>tmp</code> will be an empty list, which will evaluate to False, returning the value following the <code>or</code>. This more concise version may come at the cost of decreased readability.</p>\n\n<h3>5. Define <code>labels</code> and <code>pools</code> using helper methods or non-init fields</h3>\n\n<p>Remove the first two code lines from <code>combinations</code>, and move them to either helper methods, or <a href=\"https://docs.python.org/3/library/dataclasses.html#post-init-processing\" rel=\"nofollow noreferrer\">additional fields that are processed post-initialization</a>. I recommend doing this to further clarify the work actually being done by <code>combinations</code> and to clean up the code overall. These both have the added benefit of exposing <code>labels</code> and <code>pools</code> as additional attributes of the <code>dataclass</code> that can be accessed outside of <code>combinations</code>.</p>\n\n<p>See the <code>ParametricMapping1</code> class defined in the section below for an implementation using helper methods, and see the alternative <code>ParametricMapping2</code> class defined below it for an implementation using non-init fields.</p>\n\n<h1>TL;DR</h1>\n\n<p>In the end, if all suggestions are followed, the code should include the below declaration of <code>flatten</code>, along with one of the two following blocks (<code>ParametricMapping1</code>, <strong>or</strong> <code>ParametricMapping2</code>):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def flatten(l):\n return [item for sublist in l for item in sublist]\n</code></pre>\n\n<p><strong>With either ...</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@dataclass\nclass ParametricMapping1:\n mappings: List[Mapping[Tuple[str], Sequence[float]]] = field(default_factory=lambda: [{}])\n\n def _labels(self) -&gt; List[Tuple[str]]:\n return flatten(self.mappings)\n\n def _pools(self) -&gt; List[List[Sequence[float]]]:\n return [list(map(tuple, zip(*arg.values()))) for arg in self.mappings]\n\n @property\n def combinations(self) -&gt; List[Mapping[Tuple[str], float]]:\n if self.mappings == [{}]:\n return [{}]\n\n pool_values = [flatten(term) for term in itertools.product(*self._pools())]\n return [dict(zip(self._labels(), v)) for v in pool_values]\n</code></pre>\n\n<p><strong>Or ...</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@dataclass\nclass ParametricMapping2:\n mappings: List[Mapping[Tuple[str], Sequence[float]]] = field(default_factory=lambda: [{}])\n labels: List[Tuple[str]] = field(init=False, repr=False)\n pools: List[List[Sequence[float]]] = field(init=False, repr=False)\n\n def __post_init__(self):\n self.labels = flatten(self.mappings)\n self.pools = [list(map(tuple, zip(*arg.values()))) for arg in self.mappings]\n\n @property\n def combinations(self) -&gt; List[Mapping[Tuple[str], float]]:\n pool_values = [flatten(term) for term in itertools.product(*self.pools)]\n return [dict(zip(self.labels, v)) for v in pool_values] or [{}]\n</code></pre>\n\n<p><strong>Edit (2019-01-09 - 1530):</strong></p>\n\n<ul>\n<li>The definitions of <code>_labels</code> and <code>self.labels</code> in the above two code blocks, respectively, have been simplified per @MathiasEttinger's <a href=\"https://codereview.stackexchange.com/questions/211121/data-transformation-involving-dictionaries-and-lists/211155#comment408288_211155\">excellent suggestion</a>. See revision history for their original definitions.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:31:57.233", "Id": "408288", "Score": "1", "body": "Nice answer. Two thoughts though: isn't `labels` simply `flatten(mappings)`? And isn't `zip` already returning `tuple`s? Why keep the `map` call?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:33:09.977", "Id": "408289", "Score": "0", "body": "Also I like to define `flatten` in terms of `itertools.chain.from_iterable`. But it's mostly a matter of personal taste." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:38:15.003", "Id": "408303", "Score": "0", "body": "Thanks a lot for the answer. I will investigate in details. @MathiasEttinger I didn't get your second point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:51:30.803", "Id": "408305", "Score": "2", "body": "@CedricH. I usually define `flatten = itertools.chain.from_iterable` as I prefer to work with iterables, but as an alternative to the `flatten` proposed by this answer, you could have `def flatten(iterable): return list(itertools.chain.from_iterable(iterable))` instead. As said, there might not be much of a difference appart for style." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:19:04.517", "Id": "408312", "Score": "0", "body": "@MathiasEttinger Got it. I also changed the definition of `labels` based on your first comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:19:41.263", "Id": "408315", "Score": "0", "body": "Hunter, Thanks a lot for the detailed answer. I edited the question to show the final implementation I chose based on your answer and on the comments above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:28:23.540", "Id": "408459", "Score": "0", "body": "@MathiasEttinger, thank you! You’re absolutely right! I missed that. Defining `labels` as `flatten(self.mappings)` is certainly better! I’ll edit my answer to mention your improvement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:41:32.297", "Id": "408461", "Score": "0", "body": "@Mathias Ettinger, `itertools.chain.from_iterable` is also a great alternative I had forgotten about. Thanks for bringing that up! @Cedric H., I’m glad you found the suggestions helpful!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:51:50.673", "Id": "211155", "ParentId": "211121", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:37:14.533", "Id": "211121", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Data transformation involving dictionaries and lists" }
211121
<p>Consider the following structure,</p> <pre><code>let condition = { and: [ { id: 3 }, { pageId: '1' } ] } </code></pre> <p>I want to get the <code>id</code> property value in a recursive way, it can be also nested inside other conditions.</p> <p>for example the structure could be like that</p> <pre><code>let condition = {or: [{ and: [ { id: 3 }, { pageId: '1' } ] }, {age: 10}]} </code></pre> <p>I ended using this but I don't like the final syntax </p> <pre><code> function getIdConditionValue(cond) { if (isArray(cond.and)) { return map(cond.and, getIdConditionValue); } else if (isArray(cond.or)) { return map(cond.or, getIdConditionValue); } if (cond.id) return cond.id; } const id = getIdConditionValue(condition).filter(x =&gt; x)[0]; </code></pre> <p>It is working, but I would like to remove <code>.filter(x =&gt; x)[0]</code> part from the calling function, which I added because the returned value would be like this <code>[1, undefined]</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:52:07.743", "Id": "408185", "Score": "0", "body": "It's a little hard to review code when there is missing code. If you could either, add some details about missing functions, or include the source That will help you get a good review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:58:35.343", "Id": "408186", "Score": "0", "body": "Welcome to Code Review! Going along with what Blindman67 stated: Besides the obvious (i.e. getting a property value) What task does this code accomplish (the big picture)? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:52:17.913", "Id": "408189", "Score": "0", "body": "Thanks for your kind words, I've edited the question as requested" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:53:26.673", "Id": "408190", "Score": "0", "body": "Why is recursion required?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:58:53.527", "Id": "408192", "Score": "0", "body": "Are the two examples the only possible data structures?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T23:54:39.883", "Id": "408233", "Score": "0", "body": "You still have not provided the information on the two missing functions `map` and `isArray`. Their behaviour can not be assume and on the face of it your function has many sources of failure, that these functions may or may not protect you from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T18:48:15.590", "Id": "408423", "Score": "0", "body": "@Blindman67 they are lodash's" } ]
[ { "body": "<p>Given the <code>map()</code> function used at the question having the same signature as <code>jQuery.map()</code> function used at the question, in order to avoid chaining <code>.filter()</code> to get the value at index <code>0</code> of the returned, you can use destructuring to assign <code>id</code> to the value at index <code>0</code> of the array returned from the function.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getIdConditionValue(cond) {\n if (Array.isArray(cond.and)) {\n return $.map(cond.and, getIdConditionValue);\n } else if (Array.isArray(cond.or)) {\n return $.map(cond.or, getIdConditionValue);\n }\n if (cond.id) return cond.id;\n}\n\nvar condition = {\n or: [{\n and: [{\n id: 3\n }, {\n pageId: '1'\n }]\n }, {\n age: 10\n }]\n}\n\n\nconst [id] = getIdConditionValue(condition);\n\nconsole.log(id);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;\n&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For Loash and Underscore signatures of <code>map()</code> signature (each library's <code>_.map()</code> returns an array having two elements, the fist is the expected result, the second <code>undefined</code>) you can use </p>\n\n<pre><code>const [[id]] = getIdConditionValue(condition);\n</code></pre>\n\n<hr>\n\n<p>For an alternative recursive solution you can create a function that accepts an object and a property name for parameter, utilizes the recursive <code>replacer</code> function of <code>JSON.stringify()</code> and <code>JSON.parse()</code>. If the property name is found during recursive iteration of property names of the object passed, a parameter of an immediately invoked arrow function declared as <code>undefined</code> is set to the property value, else <code>undefined</code> is returned from the function.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const condition1 = {and: [{id:3}, {pageId:'1'}]};\nconst condition2 = {or: [{and: [{id: 3}, {pageId: '1'}]}, {age: 10 }]};\nconst condition3 = {and:[,,]};\nconst condition4 = {and:{or:[]}};\nconst condition5 = {or:[{or:[{id:1}]}]};\n\nconst getObjectPropertyValue = (o, prop) =&gt; (result =&gt;\n (JSON[typeof o === 'string' ? 'parse' : 'stringify'](o, (key, value) =&gt; \n key == prop ? (result = value) : value), result))(void 0);\n\nlet prop = 'id';\n\nconst id1 = getObjectPropertyValue(condition1, prop);\n\nconsole.log(id1);\n\nlet condition2json = JSON.stringify(condition2);\n\nconst id2 = getObjectPropertyValue(condition2json, prop);\n\nconsole.log(id2);\n\nconst id3 = getObjectPropertyValue(condition3, prop);\n\nconsole.log(id3); // `undefined`\n\nconst id4 = getObjectPropertyValue(condition4, prop);\n\nconsole.log(id4); // `undefined`\n\nconst id5 = getObjectPropertyValue(condition5, prop);\n\nconsole.log(id5);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T23:42:27.170", "Id": "408230", "Score": "1", "body": "You have a typo in the second call, think you mean `condition2`, also your function is prone to throwing errors. `{and:[,,]}`, `{and:{or:[]}}`, and `{or:[{or:[{id:1}]}]}` each throw a different error, and `{and:[{id:false}],id:null}` incorrectly returns `false`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T00:15:47.833", "Id": "408235", "Score": "0", "body": "@Blindman67 See updated post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T00:55:20.163", "Id": "408240", "Score": "0", "body": "@Blindman67 What is the expected result of `{and:[{id:false}],id:null}`? The language at the question is _\"the `id` property value\"_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:40:48.300", "Id": "408243", "Score": "1", "body": "I am guessing its `undefined` due to the line `if (cond.id) return cond.id;` from OP code However its is completely unclear what the actual needs are as the OP's code only prioritises `and` above `or` and gives no indication that `and` and `or` are defining logic. Eg `and` means all ids in array are truthy and `or` means any id is truthy. Unless the call to `map` has something going on in it (don't think so). At face values its a search for the FIRST truthy `id` along prop paths with `and` having priority, then `or` and last `id`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:46:46.560", "Id": "408245", "Score": "0", "body": "@Blindman67 If you are referring to the `undefined` returned from the function at the answer, that is a decision made, here. The structure of the JavaScript plain object passed to the function at the answer is irrelevant to getting a specific property value. The name of the property itself, `\"id\"`, strongly implies that each distinct object or each element of an array of objects have precisely 1 property named `\"id\"`. The example objects at the question demonstrate that. As for further information from OP, that too, is not necessary for this answer to stand on its own re the current question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:49:47.443", "Id": "408246", "Score": "0", "body": "@Blindman67 Updated the answer to throw an `Error` if the property is not found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T02:05:30.500", "Id": "408247", "Score": "0", "body": "In JS I avoid throwing unless closure and dependent state will be damaged as to not allow the function to run again, also throwing is passing the buck to someone else.. If data is undefined then all you can return is undefined. The question is too ambiguous for a clear review on the functions logic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T02:08:09.917", "Id": "408249", "Score": "0", "body": "@Blindman67 The question is not ambiguous from perspective here. A plain JavaScript object cannot have duplicate property names. Reverted to returning `undefined` if the property name is not found in the object. Will update the answer to include a solution using the code at the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T02:30:15.273", "Id": "408250", "Score": "0", "body": "@Blindman67 See updated post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T18:56:30.210", "Id": "408425", "Score": "0", "body": "@guest271314 Can you please explain the second syntax \n`const getObjectPropertyValue = (o, prop) => (result =>\n (JSON[typeof o === 'string' ? 'parse' : 'stringify'](o, (key, value) => \n key == prop ? (result = value) : value), result))(void 0);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:34:04.800", "Id": "408430", "Score": "1", "body": "@MustafaMagdy `(result => (JSON[typeof o === 'string' ? 'parse' : 'stringify'](o, (key, value) => key == prop ? (result = value) : value), result))(void 0)` is an immediately invoked arrow function. The purpose is to 1) define the variable `result` as `undefined` within the function without declaring the variable as a parameter of `getObjectPropertyValue` 2) return `result` either being set to `value` if `key == prop` or remain `undefined`. The call to `JSON[stringify/parse]` is wrapped in parenthesis to allow the comma operator which follows `((..), result)` where `result` is always returned." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:37:30.050", "Id": "211133", "ParentId": "211124", "Score": "0" } }, { "body": "<p>If you just want the first result of any 'id' property in the structure you can just do a recursive search:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let condition = {or: [{ and: [ { id: 3 }, { pageId: '1' } ] }, {age: 10}]}\n\nfunction getFirstId(struct){\n for(let prop in struct){\n let val = struct[prop];\n if(prop === 'id') return val;\n if(\"object\" === typeof val) return getFirstId(val);\n }\n}\n\nconsole.log(getFirstId(condition));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T23:54:24.513", "Id": "408232", "Score": "0", "body": "Your function is not safe when object or arrays contain cyclic references (throws error), returns the wrong value for `{id:false}`, unsafely uses `for in` and will recurse on a null property (eg `typeof null === \"object\"` is true)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:47:03.787", "Id": "408373", "Score": "0", "body": "true. other answers made assumptions about the structure of the input so I did as well. maybe I'll update it later." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T21:12:30.530", "Id": "211141", "ParentId": "211124", "Score": "0" } } ]
{ "AcceptedAnswerId": "211133", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:39:00.980", "Id": "211124", "Score": "0", "Tags": [ "javascript", "recursion" ], "Title": "Get property value from object tree in a recursive way" }
211124
<p>This is a two player dice game where two players each roll two dice. If a player's dice sum is even, they gain 10 points. If the dice total is odd, they lose 5 points.</p> <pre><code>import random import time import sys print("*****************Welcome To The DICE Game*******************") abc=input("please type in 'n' if your are a new user type 'e' if you are a existing user: ") while abc not in ('e','n'): abc=input("please type in 'n' if your are a new user type 'e' if you are a existing user: ") if abc =="n": print("make an account") username=input("type in a username: ") password1=input("type in a pasword: ") password2=input("renter the password: ") if password1==password2: print("your password is",password1) f = open ("username + password.txt","a+") f.write(f"{username}:{password2}\n") f.close() abc=input("please type in 'n' if your are a new user type 'e' if you are a existing user: ") else: print("the password you entered is not matching restart the program to start again") sys.exit() if abc == "e": check = True while check: print("player 1 enter your details") username1=input("Username = ") password=input("Password = ") with open("username + password.txt","r") as username_finder: for line in username_finder: if(username1 + ":" + password) == line.strip(): print("you are logged in") print("player 2 enter your details") while check: print("incoreect password or username please try again") username2=input("Username = ") password=input("Password = ") with open("username + password.txt","r") as username_finder: for line in username_finder: if(username2 + ":" + password) == line.strip(): check = False print("you are logged on") #game player1=0 player2=0 print("*****************Welcome To The DICE Game*******************") print("PLAYER 1 READY") time.sleep(1) print("PLAYER 2 READY") totalscore1=0 totalscore2=0 #player 1 dice1 = random.randint(1,6) dice2 = random.randint(1,6) roundno = 1 while roundno &lt; 5: totalscore1=totalscore1+player1 totalscore2=totalscore2+player2 player1=dice1+dice2 roundno=roundno+1 print("round",roundno) time.sleep(1) print("-----------------------------------------------------") asdf = input("player 1, press enter to roll") print("player 1 is rolling") print("player 1's first roll is",dice1) time.sleep(1) print("player 1's second roll is",dice2) time.sleep(1) print("-----------------------------------------------------") if player1 %2==0: print("This is an even number. so +10 points") time.sleep(1) player1=player1+10 time.sleep(1) print("score is",player1) if player1&lt;= 0: print("you have lost the game") sys.exit() print("-----------------------------------------------------") else: print("This is an odd number.") time.sleep(2) player1=player1-5 print("score is",player1) time.sleep(3) print("player 1 score",player1) print("-----------------------------------------------------") time.sleep(1) #player 2 dice1 = random.randint(1,6) dice2 = random.randint(1,6) totalscore1=totalscore1+player1 totalscore2=totalscore2+player2 player2=dice1+dice2 print("-----------------------------------------------------") asdf = input("player 2 press enter to roll") print("player 2 is rolling") time.sleep(1) print("player 2's first roll is",dice1) time.sleep(1) asdf = input("player 2 press enter to roll again") time.sleep(1) print("player 2's second roll is",dice2) time.sleep(1) print("-----------------------------------------------------") if player2 %2==0: print("This is an even number. so +10 points") time.sleep(1) player2=player2+10 print("score is",player2) time.sleep(1) if player2&lt;= 0: print("you have lost the game") sys.exit() print("-----------------------------------------------------") else: print("This is an odd number.") time.sleep(1) player2=player2-5 print("score is",player2) time.sleep(3) print("player 2 score",player2) print("-----------------------------------------------------") print("the total score for player 1 is ",totalscore1) print("the total score for player 2 is ",totalscore2) if totalscore1 &gt; totalscore2: print("player 1 wins") file = open("scores.txt2","a+") file.write("player 1 ") file.write(username1) file.write(" has won overall with ") file.write(str(totalscore1)) file.write(" points") file.write("\n") if totalscore2 &gt; totalscore1: print("player 2 wins") file = open("scores.txt2","a+") file.write("player 2 ") file.write(username2) file.write(" has won overall with ") file.write(str(totalscore2)) file.write(" points") file.write("\n") else: print("incorrect username or password") else: print("incorrect username or password") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:42:19.043", "Id": "408199", "Score": "2", "body": "Is this at all related to https://codereview.stackexchange.com/q/210517/46840?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T20:27:40.203", "Id": "408204", "Score": "0", "body": "no thats my friend we go to the same school" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T20:28:56.700", "Id": "408206", "Score": "2", "body": "Ahh. I knew it looked familiar. And some of the tips mentioned in the other post apply here as well. It's worth reviewing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T20:29:37.467", "Id": "408207", "Score": "0", "body": "I know my friend told me to look at his posts as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T11:43:12.120", "Id": "446984", "Score": "0", "body": "Try using a password that ends in a space, and then using it to log in." } ]
[ { "body": "<p>This only addresses one aspect of your code, but I think it's an important point to communicate:</p>\n\n<h1>Login systems</h1>\n\n<p>If you ever actually <em>need</em> a login system, you should investigate cybersecurity and good practices in more depth. Generally, it's advisable to use an existing reputable library or API to accomplish such a task, since it's easy to make mistakes in your own implementation.</p>\n\n<p>Having said that, there are a few things that are easy for me to notice in your code:</p>\n\n<ul>\n<li>Use <a href=\"https://docs.python.org/library/getpass.html#getpass.getpass\" rel=\"nofollow noreferrer\"><code>getpass.getpass</code></a> to prompt the password so others cannot see the entered password.</li>\n<li>You should <strong>never</strong> save passwords in plaintext. <a href=\"https://en.wikipedia.org/wiki/Cryptographic_hash_function\" rel=\"nofollow noreferrer\">Hashing</a> and <a href=\"https://en.wikipedia.org/wiki/Salt_(cryptography)\" rel=\"nofollow noreferrer\">salting</a> are standard security measures employed in all well-implemented password systems.</li>\n<li>Some other things I mentioned in my comment: it would probably be better to lock-out after too many wrong attempts to prevent brute force attacks, and it should probably prevent registration passwords that have identical hashes to those released in common password data dumps. But these are even more outside of the scope of this question's implicit context.</li>\n</ul>\n\n<p>Of course as @jpmc mentions, this is somewhat less relevant for this particular program, since it stores the password locally. But in general, I think starting to consider the security implications of your implementation is important, even if it's just practice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T23:30:54.283", "Id": "408228", "Score": "1", "body": "This is all useless considering that it's stored in a plain text file that the user has access to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T23:46:57.440", "Id": "408231", "Score": "0", "body": "@jpmc26 True, but I really just wanted to make some general points about cybersecurity, hence the caveat *need*. I also didn't mention that it should probably rate limit for brute force attacks, or prevention of people registering simple passwords are problems. I could, (and will) edit that into my answer. I do agree that [Carcigenicate's answer](https://codereview.stackexchange.com/a/210574/140921) is probably more implementable and immediately useful advice. My intention is communicating a bit of a larger picture idea: cybersecurity is easy to get wrong." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T18:39:43.927", "Id": "211128", "ParentId": "211125", "Score": "9" } }, { "body": "<h1><em><strong>FUNCTIONS!</strong></em></h1>\n<p>Divide your code into functions to make it more readable. In a couple of places, your code is <em>12 levels of indentation</em> deep! That's the equivalent of 48 characters!</p>\n<hr />\n<h1>Spacing</h1>\n<p>Operators should usually have a space on either side.</p>\n<h1><code>with</code></h1>\n<p>The best way of opening files is as follows (to make sure it get closed even if there is an error):</p>\n<pre><code>with open(...) as f:\n ...\n</code></pre>\n<hr />\n<p>My modified version is available <a href=\"https://repl.it/@solly_ucko/UnconsciousOddInitializationfile\" rel=\"noreferrer\">on repl.it</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:06:05.713", "Id": "408390", "Score": "0", "body": "could you check my code and modify it if anything is wrong please [https://codereview.stackexchange.com/questions/210517/two-player-dice-game-for-nea-task-computer-science-updated]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:53:17.227", "Id": "211135", "ParentId": "211125", "Score": "13" } } ]
{ "AcceptedAnswerId": "211128", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:47:29.663", "Id": "211125", "Score": "11", "Tags": [ "python", "python-3.x", "game", "dice" ], "Title": "2 player dice game with login system" }
211125
<p>I'm trying to properly write a card class in swift. I've been taking classes in software engineering and I need help in understanding how to take a more object-oriented approach to my class. I have seen a Class for suit and rank and I'm wondering would that approach would be better? I have also seen the suit as enums and wonder if that approach would be better. </p> <p>Any help will be appreciated.</p> <p>Thank you</p> <pre>class Card</pre> <pre><code>private var rank: Int private var suit: Int init(n: Int) { self.rank = -1; self.suit = -1; if(n &gt;= 0 &amp;&amp; n &lt;= 51) { self.rank = n % 13; self.suit = n / 13; } } func getRank() -&gt; Int { return self.rank; } func getSuit() -&gt; Int { return self.suit; } func compareRank(otherCard: Card) -&gt; Bool { return self.rank == otherCard.getRank(); } func compareSuit(otherCard: Card) -&gt; Bool { return self.suit == otherCard.getSuit(); } </code></pre>
[]
[ { "body": "<h2>Writing Style</h2>\n\n<ol>\n<li><p>In Swift, semicolons are not needed at the end of a line.</p></li>\n<li><p>Specifying <code>self</code> in <code>self.suit</code> and <code>self.rank</code> is not needed (since there is no possible confusion). The compiler can infer that you are referring to the properties of this class.</p></li>\n</ol>\n\n<hr>\n\n<h2>Initializer</h2>\n\n<p>With <code>rank</code> and <code>suit</code> defined as integers, a card would be initialized with <code>-1</code> as rank and suit if <code>n &lt; 0</code>. As defined, the initializer would produce an invalid card. An honest initializer would fail instead :</p>\n\n<pre><code>init?(n: Int) {\n guard n &gt;= 0 &amp;&amp; n &lt;= 51 else {\n return nil\n }\n rank = n % 13\n suit = n / 13\n}\n</code></pre>\n\n<p>And since the suit and rank properties can't be changed (you've defined them as private properties with getter methods), it would be appropriate to define them as \n constants: <code>let</code> instead of <code>var</code>: </p>\n\n<pre><code>private let rank: Int\nprivate let suit: Int\n</code></pre>\n\n<hr>\n\n<h2>Type Choices</h2>\n\n<ol>\n<li><p>Creating a card based on an integer isn't very intuitive. An alternative choice, as you've mentioned, would be using enums. Such an approach avoids the possibility of creating an invalid <code>Card</code> :</p>\n\n<pre><code>enum Suit: Character {\n case spades = \"♠\", hearts = \"♡\", diamonds = \"♢\", clubs = \"♣\"\n}\n\nenum Rank: Int {\n case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king\n}\n</code></pre></li>\n</ol>\n\n<p>Usually, it is not sufficient to look for equality when comparing the rank of a card. The value associated with a rank could be defined in a Blackjack game <a href=\"https://docs.swift.org/swift-book/LanguageGuide/NestedTypes.html\" rel=\"nofollow noreferrer\">this way</a>.</p>\n\n<ol start=\"2\">\n<li>Using a struct instead of a class would be encouraged here since there is no flagrant purpose of having a shared mutable state for a Card instance. Plus, value types are stored in the Stack instead of the Heap, which allows quicker access. </li>\n</ol>\n\n<hr>\n\n<p>Here is a version of your code with all the previous suggestions :</p>\n\n<pre><code>enum Suit: Character {\n case spades = \"♠\", hearts = \"♡\", diamonds = \"♢\", clubs = \"♣\"\n}\n\nenum Rank: Int {\n case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king\n}\n\nclass Card {\n\n private let rank: Rank\n private let suit: Suit\n\n init(_ rank: Rank, of suit: Suit) {\n self.rank = rank\n self.suit = suit\n }\n\n func getRank() -&gt; Rank {\n return rank\n }\n\n func getSuit() -&gt; Suit {\n return suit\n }\n\n func compareRank(with otherCard: Card) -&gt; Bool {\n return rank == otherCard.getRank()\n }\n\n func compareSuit(with otherCard: Card) -&gt; Bool {\n return suit == otherCard.getSuit()\n }\n}\n</code></pre>\n\n<p>And you could use it like so :</p>\n\n<pre><code>let a = Card(.ace, of: .spades)\nlet q = Card(.queen, of: .hearts)\n\nprint(a.getRank()) //ace\nprint(a.getSuit()) //spades\nprint(a.getSuit().rawValue) //♠\nprint(q.getRank().rawValue) //12\nprint(a.compareRank(with: q)) //false\nprint(a.compareSuit(with: q)) //false\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-16T18:00:59.677", "Id": "425792", "Score": "0", "body": "while using self is not necessary I think it can make things more clear. Swift sacrifices a lot of readability for brevity." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T08:17:58.680", "Id": "211242", "ParentId": "211137", "Score": "1" } }, { "body": "<p>In addition to what @Carpsen90 said:</p>\n\n<h3>No <code>get...</code> accessor methods</h3>\n\n<p>Unlike some other programming languages, you don't define accessor methods for the properties, these are implicitly created by the compiler. If <code>suit</code> and <code>rank</code> are constant properties (initialized once and never mutated) then it is simply</p>\n\n<pre><code>struct Card {\n let rank: Int\n let suit: Int\n\n // ...\n}\n</code></pre>\n\n<p>For properties which are publicly read-only, but internally read-write, it is</p>\n\n<pre><code> struct Card {\n private(set) var rank: Int\n private(set) var suit: Int\n\n // ...\n}\n</code></pre>\n\n<p>That makes the <code>compareRank/Suit</code> methods obsolete, because you can directly test</p>\n\n<pre><code>if card1.rank == card2.rank { ... }\n</code></pre>\n\n<p>etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T16:15:41.837", "Id": "211272", "ParentId": "211137", "Score": "3" } } ]
{ "AcceptedAnswerId": "211242", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T20:32:55.600", "Id": "211137", "Score": "1", "Tags": [ "swift", "playing-cards" ], "Title": "Playing Card in Swift" }
211137
<p>One of my react component's methods is using an async fetch() internally. After fetching the response from the server, it is being converted to JSON, then I perform a check on that JSON string. Finally, I return the result wrapped in a new promise. Here is the code:</p> <pre><code>fetchCalendarData(offset, length) { return fetch(this.props.Uri + '?offset=' + offset + '&amp;length=' + length) .then(response =&gt; response.json()) .then((result) =&gt; { if (result.hasOwnProperty('redirect_to_login') &amp;&amp; result.redirect_to_login == true) { window.location.reload(window.globalAppState.base_url + "/login"); } return Promise.resolve(result); }) .catch(() =&gt; { return Promise.reject('FAILURE'); }); } </code></pre> <p>When I call the method, I do it like this:</p> <pre><code>this.fetchCalendarData(0, 6).then((fetched_calendar_data) =&gt; { this.calendar_data = fetched_calendar_data; }); </code></pre> <p>The code works, but I am not familiar with promise based flow at all, and those 3 return statements look a little weird to me. I also read about the <a href="https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it">promise constructor antipattern</a> but am not sure if that applies here. And, is it necessary to return the result wrapped in a new promise, at all? </p>
[]
[ { "body": "<blockquote>\n <p>but am not sure if that applies here. And, is it necessary to return\n the result wrapped in a new promise, at all?</p>\n</blockquote>\n\n<p>Yes, that applies here. </p>\n\n<p>No, returning <code>Promise.resolve()</code> is not necessary. <code>.then()</code> returns a new <code>Promise</code> object. Use </p>\n\n<p><code>return result</code></p>\n\n<p>within the function passed to <code>.then()</code>.</p>\n\n<p>Note, a value <code>return</code>ed from <code>.catch()</code> results in a resolved <code>Promise</code>. Depending on how errors are handled an error could be <code>throw</code>n (withing <code>{}</code> of a function).</p>\n\n<pre><code>this.fetchCalendarData(0, 6).then((fetched_calendar_data) =&gt; {\n this.calendar_data = fetched_calendar_data;\n});\n</code></pre>\n\n<p>should include the second parameter to <code>.then()</code> to handle potential error</p>\n\n<pre><code>.then((fetched_calendar_data)=&gt;{}, err=&gt;{/* handle error */})\n</code></pre>\n\n<p>given then <code>Promise.reject()</code> is returned from <code>.catch()</code>, or <code>.catch()</code> should be chained to <code>.then()</code></p>\n\n<pre><code>.then((fetched_calendar_data)=&gt;{}\n.catch(err=&gt;{/* handle error */})\n</code></pre>\n\n<hr>\n\n<pre><code>fetchCalendarData(offset, length) {\n return fetch(this.props.Uri + '?offset=' + offset + '&amp;length=' + length)\n .then(response =&gt; response.json())\n .then(result =&gt; {\n if (result.hasOwnProperty('redirect_to_login') \n &amp;&amp; result.redirect_to_login == true) {\n window.location.reload(window.globalAppState.base_url + \"/login\");\n }\n return result;\n })\n .catch(() =&gt; {\n throw new Error('FAILURE');\n });\n}\n\nthis.fetchCalendarData(0, 6)\n.then(fetched_calendar_data =&gt; {\n this.calendar_data = fetched_calendar_data;\n})\n.catch(err =&gt; console.error(err));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:53:03.380", "Id": "408306", "Score": "0", "body": "I really appreciate your comprehensive review! Is it just a matter of style if you use `.then(resolve_callback, reject_callback)` or `.then(resolve_callback).catch(reject_callback)` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:01:15.177", "Id": "408407", "Score": "1", "body": "@Benni There is a difference, see [When is .then(success, fail) considered an antipattern for promises?](https://stackoverflow.com/q/24662289)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:21:44.487", "Id": "211154", "ParentId": "211146", "Score": "1" } } ]
{ "AcceptedAnswerId": "211154", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T23:00:58.737", "Id": "211146", "Score": "2", "Tags": [ "javascript", "react.js", "promise" ], "Title": "Wrapping fetch(), preserve promise-based API for outer function" }
211146
<p>I implemented the linked-list natural merge sort in Python, and I referred to this awesome if not poetic <a href="https://gist.github.com/zed/5651186" rel="nofollow noreferrer">gist</a> and <a href="https://codereview.stackexchange.com/questions/87272/natural-mergesort/87334#87334">this implementation in Go</a>. Here is my code:</p> <pre><code># Linked list is either empty or a value and a link to the next list empty = None # empty list class LL(object): __slots__ = &quot;value&quot;, &quot;next&quot; def __init__(self, value, next=empty): self.value = value self.next = next def __le__(self, other): return self.value &lt;= other.value def __lt__(self, other): return self.value &lt; other.value def reverse(head, size=-1): &quot;&quot;&quot; reference: https://stackoverflow.com/a/22049871/3552 &quot;&quot;&quot; new_head = None while head: temp = head head = temp.next temp.next = new_head new_head = temp size-=1 if not size: tail = new_head while tail.next: tail = tail.next tail.next = head return new_head return new_head def find_next_stop(head): if head is empty: return head, 0, empty next_node = head.next if next_node is empty: return head, 1, empty size = 2 if head &lt;= next_node: while(next_node.next and next_node &lt;= next_node.next): size += 1 next_node = next_node.next next_node = next_node.next else: while(next_node.next and next_node.next &lt; next_node): size += 1 next_node = next_node.next next_node = next_node.next head = reverse(head, size) return head, size, next_node def linked_list_natural_merge_sort(head): &quot;&quot;&quot;Revising from mergesort-linkedlist to Natural_mergesort_linkedlist [1]. [1]: https://gist.github.com/zed/5651186 &quot;&quot;&quot; while True: p = head head, tail = empty, empty nmerges = 0 while p is not empty: nmerges += 1 q = p p, psize, next_start, = find_next_stop(p) q, qsize, next_start = find_next_stop(next_start) while psize &gt; 0 or (qsize &gt; 0 and q is not empty): if psize == 0: e, q = q, q.next qsize -= 1 elif qsize == 0 or q is empty: e, p = p, p.next psize -= 1 elif p.value &lt;= q.value: e, p = p, p.next psize -= 1 else: # p.value &gt; q.value i.e., first element of q is lower e, q = q, q.next qsize -= 1 # add e to the end of the output list if tail is not empty: tail.next = e else: head = e # smallest item among two lists tail = e p = next_start if tail is not empty: tail.next = empty # if we have done only one merge, we're finished if nmerges &lt;= 1: return head def mklist(initializer): it = reversed(initializer) try: x = next(it) except StopIteration: return empty else: head = LL(x) for value in it: head = LL(value, head) return head def walk(head, size=-1): while head is not empty: if size: size -= 1 else: break yield head.value head = head.next def tolist(head, size=-1): return list(walk(head, size)) </code></pre> <p>I tested it as follows:</p> <pre><code>def test(): for n, r, k in product(range(10), repeat=3): L = list(range(n)) + [n//2]*r + [n-1]*k random.shuffle(L) head = mklist(L) assert tolist(head) == L head = linked_list_natural_merge_sort(head) assert tolist(head) == sorted(L) if __name__ == &quot;__main__&quot;: import random from itertools import product test() </code></pre> <p>After reading <a href="https://codereview.stackexchange.com/a/210332/77243">this answer</a> I modified the linked_list_natural_merge_sort function as follows:</p> <pre><code>def linked_list_natural_merge_sort(head): &quot;&quot;&quot;Revising from mergesort-linkedlist to Natural_mergesort_linkedlist [1]. [1]: https://gist.github.com/zed/5651186 &quot;&quot;&quot; p = q = head psize = 0 tail = empty while q is not empty: tail = empty q, qsize, next_q = find_next_stop(q) msize = psize + qsize while qsize &gt; 0 or psize &gt; 0: if psize == 0: e, q = q, q.next qsize -= 1 elif qsize == 0: e, p = p, p.next psize -= 1 elif p &lt;= q: e, p = p, p.next psize -= 1 else: e, q = q, q.next qsize -= 1 if tail is empty: head = e else: tail.next = e tail = e psize = msize q = next_q p = head if tail is not empty: tail.next = empty return head </code></pre> <p>Any suggestions or recommendations for further improvements will be highly appreciated. The complete code can be found <a href="https://gist.github.com/eduOS/37cf32ed097d487c7ad335148baa4b5f" rel="nofollow noreferrer">here</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T00:16:38.037", "Id": "211149", "Score": "4", "Tags": [ "python", "python-3.x", "linked-list", "mergesort" ], "Title": "Linked-list natural merge sort in Python" }
211149
<blockquote> <p>Given a string, find the first repeating character in it. </p> <p>Examples:</p> <ul> <li><code>firstUnique("Vikrant")</code> → <code>None</code></li> <li><code>firstUnique("VikrantVikrant")</code> → <code>Some(V)</code></li> </ul> </blockquote> <p>Scala implementation:</p> <pre class="lang-scala prettyprint-override"><code>object FirstUniqueChar extends App { def firstUnique(s: String): Option[Char] = { val countMap = (s groupBy (c=&gt;c)) mapValues(_.length) def checkOccurence(s1: String ): Option[Char] = { if (countMap(s1.head) &gt; 1) Some(s1.head) else if (s1.length == 1) None else checkOccurence(s1.tail) } checkOccurence(s) } println(firstUnique("abcdebC")) println(firstUnique("abcdef")) } </code></pre> <p>I also have a followup question. What is the recommended way if I do not want to solve this problem with recursion? Instead of using the <code>checkOccurence</code> method I can traverse through the string and <code>break</code> when I find the first element with a count more than 1. But that will require a break, which is discouraged in Scala.</p>
[]
[ { "body": "<p>Your <code>checkOccurrence(s)</code> is just a clumsy way to write <code>s.<a href=\"https://www.scala-lang.org/api/current/scala/collection/immutable/Seq.html#find%28p:A=&gt;Boolean%29:Option[A]\" rel=\"nofollow noreferrer\">find</a>(countMap(_) > 1)</code>.</p>\n\n<p>You can significantly simplify the solution by taking advantage of <a href=\"https://www.scala-lang.org/api/current/scala/collection/immutable/StringLike.html#distinct:Repr\" rel=\"nofollow noreferrer\"><code>.distinct</code></a>.</p>\n\n<pre><code>def firstUnique(s: String): Option[Char] =\n s.zipAll(s.distinct, '\\u0000', '\\u0000')\n .collectFirst({ case ab if ab._1 != ab._2 =&gt; ab._1 })\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T01:20:59.363", "Id": "408474", "Score": "2", "body": "Slightly more concise syntax for a very nice answer: `collectFirst{case (a,b) if a != b => a}`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T21:04:33.530", "Id": "211223", "ParentId": "211151", "Score": "2" } } ]
{ "AcceptedAnswerId": "211223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T00:53:21.350", "Id": "211151", "Score": "0", "Tags": [ "strings", "recursion", "interview-questions", "functional-programming", "scala" ], "Title": "Find first repeating Char in String" }
211151
<p>I am trying to solve the following minimization problem:</p> <p><span class="math-container">$$ \min\lvert\lvert{x}\rvert\rvert_1 + \beta\lvert\lvert{x}\rvert\rvert^2_2 s.t. \sum_{m = 1}^M (y - \lvert{c}^{H} . x\rvert^2)^2 \le \epsilon $$</span></p> <ul> <li><code>x</code>: my unknown value (input) with complex elements and known size, here (4x1)</li> <li><code>y</code>: the output vector (known) </li> <li><code>c</code>: a 'skaling' vector</li> </ul> <p>I am very new to this so my approach may seem basic. I simply loop over all combination of <code>c</code> (non-redundant) and according to the computed minimization value and condition I update my results.</p> <p>My questions are the following: </p> <ul> <li>Is this correct and is there a better approach to this? </li> <li>This code fails with a small step due to the huge size of combinations, so how can I solve that?</li> </ul> <p></p> <pre><code>from itertools import combinations from random import randint import numpy as np def deg2rad(phase): return round(((phase*3.14)/180),3) def excitation(amplitude, phase): return complex(round(amplitude * (np.cos(deg2rad(phase))),3), round(amplitude*(np.sin(deg2rad(phase))),3)) def compute_subject_equation_result(x): M = 12 difference = [] y = [randint(10, 20) for i in range(M)] for m in range(0, M): c = np.array([randint(0, 9), randint(10,20), randint(0, 9), randint(0,20)]).reshape(4,1) ch = c.conjugate().T eq = (y[m] - (abs(np.dot(ch, x))[0])**2)**2 difference.append(eq**2) return round(sum(difference)[0], 3) def compute_main_equation_result(x, beta): norm1 = np.linalg.norm(x,1) norm2 = np.linalg.norm(x,2) return round(norm1 + beta*(norm2**2), 3) def optimize(x, min_x, min_phi_x): min_result = 10**25 # compute the optimization formals and check for the min value main_equation_result = compute_main_equation_result(c, beta) subject_equation_result = compute_subject_equation_result(c) # update min value if min detected' if subject_equation_result &lt; epsilon and main_equation_result &lt; min_result: min_result = main_equation_result min_x = x min_phi_x = phx return min_x, min_phi_x # initialization phases = [alpha for alpha in range(0, 361, 90)] beta = 1 epsilon = 10**25 min_x = np.array([]) min_phi_x = np.array([]) phases_combinations = [list(comb) for comb in combinations(phases, 4)] # start checking all combinations for phx in phases_combinations: phi1, phi2, phi3, phi4 = phx[0], phx[1], phx[2], phx[3] # build the hypothesis for the excitations vector c c = np.array([ excitation(1, phi1), excitation(1, phi2), excitation(1, phi3), excitation(1, phi4) ]).T.reshape(4,1) min_x, min_phi_x = optimize(c, min_x, min_phi_x) print(' --------------------------------------------------') print('-----&gt; new_min_c = ', list(min_x)) print('-----&gt; new_min_phi_c = ', min_phi_x) </code></pre> <p>Remark: When trying <code>phases = [alpha for alpha in range(0, 361, 1)]</code> I get a "memory error". I can avoid using a higher step. However I am not sure about my approach in general nor of the step change effect on the accuracy.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T01:10:44.433", "Id": "211153", "Score": "3", "Tags": [ "python", "numpy", "memory-optimization" ], "Title": "Minimization problem solving and its step limits" }
211153
<p>I have been looking at homemade CNC and have been wondering how curves are drawn, so I looked into it and found <a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="nofollow noreferrer">this cool article</a>. I then decided to try coming up with a bezier curve algorithm in C. It seems to work ok, and while I haven't tried plotting points with this exact implementation, it seems to match up with results from a previous implementation that I did plot points with.</p> <pre><code>#include &lt;stdint.h&gt; static long double bbezier(long double t, long double p0, long double p1){ return ((p1 - p0) * t) + p0; } long double bezier(long double t, uint64_t *points, uint64_t n){ long double p0 = points[0], p1 = points[1]; if(n == 1) return bbezier(t, p0, p1); long double q0 = bezier(t, points, n - 1), q1 = bezier(t, points + 1, n - 1); return bbezier(t, q0, q1); } </code></pre> <p>I then quickly wrote this test program in C++.</p> <pre><code>#include &lt;iostream&gt; extern "C" long double bezier(long double, uint64_t *, uint64_t); uint64_t pointsx[] = { 0, 40, 100, 200 }; uint64_t pointsy[] = { 0, 150, 60, 100 }; int main(){ for(uint64_t i = 0; i &lt;= 10000; ++i){ long double ii = i; long double j = ii/10000; long double x = bezier(j, pointsx, 3); long double y = bezier(j, pointsy, 3); std::cout &lt;&lt; "X: " &lt;&lt; x &lt;&lt; ", Y: " &lt;&lt; y &lt;&lt; '\n'; } return 0; } </code></pre> <p>I wrote an implementation running in javascript from a lightly modified w3 schools canvas tutorial <a href="https://www.w3schools.com/code/tryit.asp?filename=FZ15C1Q1XRZS" rel="nofollow noreferrer">here</a> to understand how bezier curves work but it only supports 3rd degree curves. It does plot the points though, and that's what I based the above implementation on.</p> <p>It doesn't make any checks to ensure t is between 0 and 1 and n != 0 but I'm not too worried. The only thing I'm worried about is segfaults in cases where n is so high that you get a stack overflow but that will be a pretty crazy curve. Anyway, how does it look?</p>
[]
[ { "body": "<p><strong>Recursion</strong></p>\n\n<p>[Edit]<br>\nIn <code>bezier()</code>, the 2 recursive calls to <code>bezier()</code> <em>is</em> inefficient as it exponential grows with O(2<sup>n</sup>) and only O(n<sup>2</sup>) operations are needed. I suspect better efficiency (linear) can be had with a pre-computed weighing of the <code>d[]</code> terms below.</p>\n\n<p>The concern about seg faulting due to excessive recursion would be mitigated with the above improvement.</p>\n\n<p>I also change function <code>bbezier()</code> to code.</p>\n\n<pre><code>long double bezier_alt1(long double t, const uint64_t *points, size_t n) {\n assert(n);\n long double omt = 1.0 - t;\n long double d[n]; // Save in between calculations.\n\n for (size_t i = 0; i &lt; n; i++) {\n d[i] = omt * points[i] + t * points[i + 1];\n }\n while (n &gt; 1) {\n n--;\n for (size_t i = 0; i &lt; n; i++) {\n d[i] = omt * d[i] + t * d[i + 1];\n }\n }\n return d[0];\n}\n</code></pre>\n\n<p>[Edit2]</p>\n\n<p>A <a href=\"https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Explicit_definition\" rel=\"nofollow noreferrer\">linear</a> solution O(n) is possible with O(1) additional memory.</p>\n\n<pre><code>long double bezier_alt2(long double t, const uint64_t *points, size_t n) {\n assert(n);\n long double omt = 1.0 - t;\n long double power_t = 1.0;\n long double power_omt = powl(omt,n);\n long double omt_div = omt != 0.0 ? 1.0/omt : 0.0;\n\n long double sum = 0.0;\n unsigned long term_n = 1;\n unsigned long term_d = 1;\n for (size_t i = 0; i &lt; n; i++) {\n long double y = power_omt*power_t*points[i]*term_n/term_d;\n sum += y;\n power_t *= t;\n power_omt *= omt_div;\n term_n *= (n-i);\n term_d *= (i+1);\n }\n power_omt = 1.0;\n long double y = power_omt*power_t*points[n]*term_n/term_d;\n sum += y;\n return sum;\n}\n</code></pre>\n\n<p>Additional linear simplifications possible - perhaps another day.</p>\n\n<hr>\n\n<p>Minor stuff</p>\n\n<p><strong>Use <code>const</code></strong></p>\n\n<p>A <code>const</code> in the referenced data allows for some optimizations, wider application and better conveys code's intent.</p>\n\n<pre><code>// long double bezier(long double t, uint64_t *points, uint64_t n){\nlong double bezier(long double t, const uint64_t *points, uint64_t n){\n</code></pre>\n\n<p><strong>Excessive wide type</strong></p>\n\n<p>With <code>uint64_t n</code>, there is no reasonable expectation that such an iteration will finish for large <code>n</code>.</p>\n\n<p>Fortunately, <code>n</code> indicates the <em>size</em> of the array. For array indexing and sizing, using <code>size_t</code>. It is the right size - not too narrow, nor too wide a type.</p>\n\n<pre><code>// long double bezier(long double t, uint64_t *points, uint64_t n){\nlong double bezier(long double t, uint64_t *points, size_t n){\n</code></pre>\n\n<p>For this application, certainly <code>unsigned</code> would always suffice. </p>\n\n<p><strong><code>static</code></strong></p>\n\n<p>Good use of <code>static</code> in <code>static long double bbezier()</code> to keep that function local.</p>\n\n<p><strong>Missing <code>\"bezier.h\"</code></strong></p>\n\n<p>I'd expect a <code>bezier()</code> declaration in a .h file and implementation in the .c file instead of <code>extern \"C\" long double bezier(long double, uint64_t *, uint64_t);</code> in main.c</p>\n\n<pre><code>// extern \"C\" long double bezier(long double, uint64_t *, uint64_t);\n#include \"bezier.h\".\n</code></pre>\n\n<p><strong><code>n</code> range check</strong></p>\n\n<p>Perhaps in a debug build, test <code>n</code>.</p>\n\n<pre><code>long double bezier(long double t, const uint64_t *points, uint64_t n){\n assert( n &gt; 0); // Low bound\n assert( n &lt; 1000); // Maybe a sane upper limit too\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:46:45.683", "Id": "408543", "Score": "0", "body": "Woah, those loops are smart. But isnt `size_t` the same as `uint64_t` on most machines?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:11:59.050", "Id": "408547", "Score": "0", "body": "@user233009 \"isn't `size_t` the same as `uint64_t` on most machines?\" --> I very much doubt `size_t` is 64-bit on 32-bit or smaller machines. Most processors in 2019 are small embedded ones (billions per year). IAC, the assumption is not needed, serves scant benefit and incurs issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:14:56.680", "Id": "408548", "Score": "0", "body": "@user233009 I did not know better Bezier algorithms until researching due to this post. So we both [LSNED](https://www.urbandictionary.com/define.php?term=LSNED)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T05:21:03.180", "Id": "211159", "ParentId": "211157", "Score": "4" } }, { "body": "<ul>\n<li><p>I don't like <code>bbezier</code>. It collided too much with <code>bezier</code>, and is not very informative. It performs a linear interpolation, so why not call it <code>interpolate</code>?</p></li>\n<li><p>The <code>p0</code> and <code>p1</code> just add noise. Consider</p>\n\n<pre><code> if (n == 1) {\n return interpolate(t, points[0], points[1]);\n }\n</code></pre>\n\n<p>I would seriously consider getting rid of <code>q0</code> and <code>q1</code>:</p>\n\n<pre><code> return interpolate(t,\n bezier(t, points, n - 1),\n bezier(t, points + 1, n - 1));\n</code></pre>\n\n<p>Don't take it as a recommendation.</p></li>\n<li><p>The recursion leads to the exponential time complexity. Way before you start having memory problems you'd face a performance problem. Consider computing the Bernstein form instead. It gives you linear time, and no memory problems.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T05:59:01.133", "Id": "408258", "Score": "0", "body": "\"It gives you linear time, and no memory problems.\" Evaluating them in Bernstein form through de Casteljau's algorithm is inefficient: \\$n(n+1)/2\\$ additions and \\$n(n+1)\\$ multiplications to calculate a point on a curve of degree \\$n\\$. Rather, I'd prefer Wang-Ball form. For reference: \"[Efficient algorithms for Bézier curves](https://doi.org/10.1016/S0167-8396(99)00048-5).\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T06:01:46.660", "Id": "408259", "Score": "1", "body": "@esote Did I ever mention de Casteljau? A not-so-naive implementation _is_ linear. Two multiplications and two divisions per term. It will have some _numerical_ issues with large `n`, sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T06:04:43.003", "Id": "408261", "Score": "0", "body": "Fair enough, I should've read your answer more carefully." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T05:39:04.203", "Id": "211160", "ParentId": "211157", "Score": "4" } } ]
{ "AcceptedAnswerId": "211159", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T03:33:21.597", "Id": "211157", "Score": "4", "Tags": [ "c", "recursion", "computational-geometry" ], "Title": "Computing bezier curves of degree n with recursive functions" }
211157
<p>I have this following module using for adding and enabling/disabling Windows Firewall rules using Python.</p> <p>I currently use <code>subprocess.call</code> to execute the <code>netsh</code> command inside Python. I'm wondering if there is any better method to do this? Executing the <code>cmd</code> command inside Python seems to be impractical to me.</p> <pre><code>import subprocess, ctypes, os, sys from subprocess import Popen, DEVNULL def chkAdmin(): """ Force to start application with admin rights """ try: isAdmin = ctypes.windll.shell32.IsUserAnAdmin() except AttributeError: isAdmin = False if not isAdmin: ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1) def addRule(rule_name, file_path): """ Add rule to Windows Firewall """ subprocess.call("netsh advfirewall firewall add rule name="+ rule_name +" dir=out action=block enable=no program=" + file_path, shell=True, stdout=DEVNULL, stderr=DEVNULL) print("Rule", rule_name, "for", file_path, "added") def modifyRule(rule_name, state): """ Enable/Disable specific rule, 0 = Disable / 1 = Enable """ if state: subprocess.call("netsh advfirewall firewall set rule name="+ rule_name +" new enable=yes", shell=True, stdout=DEVNULL, stderr=DEVNULL) print("Rule", rule_name, "Enabled") else: subprocess.call("netsh advfirewall firewall set rule name="+ rule_name +" new enable=no", shell=True, stdout=DEVNULL, stderr=DEVNULL) print("Rule", rule_name, "Disabled") chkAdmin() addRule("RULE_NAME", "PATH_TO_FILE") modifyRule("RULE_NAME", 1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T07:23:01.067", "Id": "408267", "Score": "1", "body": "could it be this : https://stackoverflow.com/a/5486837/6212957" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:37:17.820", "Id": "408321", "Score": "1", "body": "I would at least give PowerShell a look. It supports remote execution and is as close as you can get to a tool intended to manage Windows via script." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:35:00.543", "Id": "408411", "Score": "0", "body": "Is it possible for these commands to fail? If netsh returns an error for any reason, it will go undetected (correct me if I'm wrong). At least assert things went smoothly even if you don't want to handle errors." } ]
[ { "body": "<p>This seems <strong>OK</strong></p>\n<p>We can add a little flavor to it:</p>\n<ol>\n<li><p>Don't use string concatenation, but use <code>f&quot;{strings}&quot;</code> or <code>&quot;{}&quot;.format(strings)</code></p>\n</li>\n<li><p>Your modify rule, can be simplified</p>\n<p>The <code>if</code> <code>else</code> don't differ that much, you can use a (Python)ternary to calculate the variables beforehand</p>\n</li>\n<li><p>Consider to chop up the lines, to make it a little more readable</p>\n</li>\n<li><p>Functions and variables should be <code>snake_case</code> according to PEP8</p>\n</li>\n<li><p>Use a <code>if __name__ == '__main__'</code> guard</p>\n</li>\n<li><p>As mentioned, you could use <code>os.system(&quot;command&quot;)</code> instead of <code>subprocess</code></p>\n<p>But honestly I would stick with <code>subprocess</code>, since it will give greater control over how commands are executed</p>\n</li>\n</ol>\n<h1>Code</h1>\n<pre><code>import subprocess, ctypes, os, sys\nfrom subprocess import Popen, DEVNULL\n\ndef check_admin():\n &quot;&quot;&quot; Force to start application with admin rights &quot;&quot;&quot;\n try:\n isAdmin = ctypes.windll.shell32.IsUserAnAdmin()\n except AttributeError:\n isAdmin = False\n if not isAdmin:\n ctypes.windll.shell32.ShellExecuteW(None, &quot;runas&quot;, sys.executable, __file__, None, 1)\n\ndef add_rule(rule_name, file_path):\n &quot;&quot;&quot; Add rule to Windows Firewall &quot;&quot;&quot;\n subprocess.call(\n f&quot;netsh advfirewall firewall add rule name={rule_name} dir=out action=block enable=no program={file_path}&quot;, \n shell=True, \n stdout=DEVNULL, \n stderr=DEVNULL\n )\n print(f&quot;Rule {rule_name} for {file_path} added&quot;)\n\ndef modify_rule(rule_name, state):\n &quot;&quot;&quot; Enable/Disable specific rule, 0 = Disable / 1 = Enable &quot;&quot;&quot;\n state, message = (&quot;yes&quot;, &quot;Enabled&quot;) if state else (&quot;no&quot;, &quot;Disabled&quot;)\n subprocess.call(\n f&quot;netsh advfirewall firewall set rule name={rule_name} new enable={state}&quot;, \n shell=True, \n stdout=DEVNULL, \n stderr=DEVNULL\n )\n print(f&quot;Rule {rule_name} {message}&quot;)\n\nif __name__ == '__main__':\n check_admin()\n add_rule(&quot;RULE_NAME&quot;, &quot;PATH_TO_FILE&quot;)\n modify_rule(&quot;RULE_NAME&quot;, 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:55:47.830", "Id": "408297", "Score": "0", "body": "Thanks! and may I ask another question? Why you recommend against using string concatenation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:02:58.977", "Id": "408299", "Score": "3", "body": "Sure,.. it has no significant influence, but it does read a lot smoother, especially with the introduction of `f\"{strings}\"`. (Python 3.6+)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:23:20.280", "Id": "211168", "ParentId": "211163", "Score": "9" } }, { "body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/a/211168/84718\">@Ludisposed</a> answer, but you have a few <code>subprocess</code> gotchas:</p>\n\n<ul>\n<li>You don't need to spawn a shell in order to run the command, simply build your command as a list of arguments and it will be fine. This is especially important if your rules names may contains spaces as the command would be treated entirelly differently in your implementation;</li>\n<li><a href=\"https://docs.python.org/3/library/subprocess.html#older-high-level-api\" rel=\"noreferrer\">Replace the old <code>subprocess.call</code> by <code>subprocess.run</code></a>;</li>\n<li>You may be interested to run <code>subprocess.run</code> by specifying <code>check=True</code> in order to generate an exception and be alerted if something does not go according to plan.</li>\n</ul>\n\n<p>Applying these changes to <em>e.g.</em> <code>modify_rule</code> can lead to:</p>\n\n<pre><code>def modify_rule(rule_name, enabled=True):\n \"\"\"Enable or Disable a specific rule\"\"\"\n subprocess.run(\n [\n 'netsh', 'advfirewall', 'firewall',\n 'set', 'rule', f'name={rule_name}',\n 'new', f'enable={\"yes\" if enabled else \"no\"}',\n ],\n check=True,\n stdout=DEVNULL,\n stderr=DEVNULL\n )\n</code></pre>\n\n<p>Also note that I removed the <code>print</code> call from the function as it impairs reusability. If the caller want this kind of messages, it should be responsible for printing them, not this function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:47:36.643", "Id": "211172", "ParentId": "211163", "Score": "10" } } ]
{ "AcceptedAnswerId": "211168", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T07:19:54.347", "Id": "211163", "Score": "7", "Tags": [ "python", "python-3.x", "networking", "windows" ], "Title": "Add and enable/disable Windows Firewall rules with Python" }
211163
<p>At the moment, I'm learning and experimenting on the use of web scraping content from different varieties of web pages. But I've come across a common smelly code among several of my applications. I have many repetitive <code>List</code> that has data being append to them.</p> <pre><code>from requests import get import requests import json from time import sleep import pandas as pd url = 'https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&amp;limit=16&amp;filter_soldout=true' list_name = [] list_price = [] list_discount = [] list_stock = [] response = get(url) json_data = response.json() def getShockingSales(): index = 0 if response.status_code is 200: print('Response: ' + 'OK') else: print('Unable to access') total_flashsale = len(json_data['data']['items']) total_flashsale -= 1 for i in range(index, total_flashsale): print('Getting data from site... please wait a few seconds') while i &lt;= total_flashsale: flash_name = json_data['data']['items'][i]['name'] flash_price = json_data['data']['items'][i]['price'] flash_discount = json_data['data']['items'][i]['discount'] flash_stock = json_data['data']['items'][i]['stock'] list_name.append(flash_name) list_price.append(flash_price) list_discount.append(flash_discount) list_stock.append(flash_stock) sleep(0.5) i += 1 if i &gt; total_flashsale: print('Task is completed...') return getShockingSales() new_panda = pd.DataFrame({'Name': list_name, 'Price': list_price, 'Discount': list_discount, 'Stock Available': list_stock}) print('Converting to Panda Frame....') sleep(5) print(new_panda) </code></pre> <p>Would one list be more than sufficient? Am I approaching this wrongly.</p>
[]
[ { "body": "<h1>Review</h1>\n\n<ol>\n<li>Remove unnecessary imports</li>\n<li><p>Don't work in the global namespace</p>\n\n<p>This makes it harder to track bugs</p></li>\n<li><p>constants (<code>url</code>) should be <code>UPPER_SNAKE_CASE</code></p></li>\n<li><p>Functions (<code>getShockingSales()</code>) should be <code>lower_snake_case</code></p></li>\n<li><p>You don't break or return when an invalid status is encountered</p></li>\n<li><p><code>if response.status_code is 200:</code> should be <code>==</code> instead of <code>is</code></p>\n\n<p>There is a function for this though</p>\n\n<p><code>response.raise_for_status()</code> this will create an exception when there is an 4xx, 5xx status</p></li>\n<li><p>Why use a <code>while</code> inside the <code>for</code> and return when finished with the <code>while</code> </p>\n\n<p>This is really odd!\nEither loop with a <code>for</code> or a <code>while</code>, not both! Because the while currently disregards the for loop.</p>\n\n<p>I suggest to stick with for loops, Python excels at readable for loops </p>\n\n<p>(Loop like a native)</p></li>\n</ol>\n\n<blockquote>\n <p>Would one list be more than sufficient? Am I approaching this wrongly.</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>You don't have the use 4 separate lists, but can instead create one list and add the column names afterwards.</p>\n\n<h1>Code</h1>\n\n<pre><code>from requests import get\nimport pandas as pd\n\nURL = 'https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&amp;limit=16&amp;filter_soldout=true'\n\ndef get_stocking_sales():\n response = get(URL)\n response.raise_for_status()\n return [\n (item['name'], item['price'], item['discount'], item['stock'])\n for item in response.json()['data']['items']\n ]\n\ndef create_pd():\n return pd.DataFrame(\n get_stocking_sales(),\n columns=['Name', 'Price', 'Discount', 'Stock']\n )\n\nif __name__ == '__main__':\n print(create_pd())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T02:12:31.320", "Id": "408480", "Score": "0", "body": "Thank you for showing where and what I did wrong and where I can improve and also making them much cleaner! I've followed what you've said and never knew about the `if __name__ == '__main__':` concept. Really; not only did you help ~ but I've learned more from your insight. Thank you so much~" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T04:44:32.183", "Id": "408600", "Score": "0", "body": "May I know just to really understand; how does this portion works\n`return[\n (item['name'], item['discount'], item['liked_count'], item['stock'])\n for item in response.json()['data']['items']\n ]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T08:38:04.767", "Id": "408609", "Score": "0", "body": "It is called a list comprehension [here is a decent explanation](https://www.pythonforbeginners.com/basics/list-comprehensions-in-python)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:34:59.963", "Id": "211176", "ParentId": "211164", "Score": "3" } }, { "body": "<h1>Review</h1>\n\n<ol>\n<li><p>Creating functions that read and modify global variables is not a good idea, for example if someone wants to reuse your function, they won't know about side effects.</p></li>\n<li><p><code>index</code> is not useful, and <code>range(0, n)</code> is the same as <code>range(n)</code></p></li>\n<li><p>Using <code>==</code> is more appropriate than <code>is</code> in general, hence <code>response.status_code == 200</code></p></li>\n<li><p>If <code>response.status_code != 200</code>, I think the function should ~return an empty result~ raise an exception like said by @Ludisposed.</p></li>\n<li><p>You use <code>json_data[\"data\"][\"items\"]</code> a lot, you could define <code>items = json_data[\"data\"][\"items\"]</code> instead, but see below.</p></li>\n<li><p>Your usage of <code>i</code> is totally messy. Never use both <code>for</code> and <code>while</code> on the same variable. I think you just want to get the information for each item. So just use <code>for item in json_data[\"data\"][\"items\"]:</code>.</p></li>\n<li><p>Actually, <code>print(\"Getting data from site... please wait a few seconds\")</code> is wrong as you got the data at <code>response = get(url)</code>. Also, <code>sleep(0.5)</code> and <code>sleep(5)</code> don't make any sense.</p></li>\n<li><p>Speaking from this, <code>requests.get</code> is more explicit.</p></li>\n<li><p>You can actually create a pandas DataFrame directly from a list of dictionaries.</p></li>\n<li><p>Actually, if you don't use the response in another place, you can use the url as an argument of the function.</p></li>\n<li><p>Putting spaces in column names of a DataFrame is not a good idea. It removes the possibility to access the column named <code>stock</code> (for example) with <code>df.stock</code>. If you still want that, you can use <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html\" rel=\"nofollow noreferrer\">pandas.DataFrame.rename</a></p></li>\n<li><p>You don't need to import <code>json</code>.</p></li>\n<li><p>The discounts are given as strings like <code>\"59%\"</code>. I think integers are preferable if you want to perform computations on them. I used <code>df.discount = df.discount.apply(lambda s: int(s[:-1]))</code> to perform this.</p></li>\n<li><p>Optional: you might want to use <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> instead of printing everything. Or at least print to stderr with:</p>\n\n<p><code>from sys import stderr</code></p>\n\n<p><code>print('Information', file=stderr)</code></p></li>\n</ol>\n\n<h1>Code</h1>\n\n<pre><code>import requests\nimport pandas as pd\n\n\ndef getShockingSales(url):\n response = requests.get(url)\n columns = [\"name\", \"price\", \"discount\", \"stock\"]\n response.raise_for_status()\n print(\"Response: OK\")\n json_data = response.json()\n df = pd.DataFrame(json_data[\"data\"][\"items\"])[columns]\n df.discount = df.discount.apply(lambda s: int(s[:-1]))\n print(\"Task is completed...\")\n return df\n\n\nURL = \"https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&amp;limit=16&amp;filter_soldout=true\"\ndf = getShockingSales(URL)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T02:14:00.057", "Id": "408481", "Score": "0", "body": "Thank you for your insight~ I've learned more than I could hope for by reading your review. It even helped me solved and fixed a few errors in other areas of my application. I wish I could give you more upvotes v.v" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:41:00.357", "Id": "211178", "ParentId": "211164", "Score": "4" } } ]
{ "AcceptedAnswerId": "211176", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T07:41:28.740", "Id": "211164", "Score": "3", "Tags": [ "python", "python-3.x", "json" ], "Title": "Reducing the amount of List in a WebScraper" }
211164
<p>I created a linked list in C++ using class with few methods to provide interface for it.</p> <p>Methods are <code>pushFront()</code>, <code>traverse()</code> and few more as shown below. <code>PushFront</code> is used to insert the data at the head of linked list at any given time. <code>traverse</code> is to display the linked list at any time. My code is shown below:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class SingleLL{ private: struct Node { int data; Node * next; }; Node * head; Node * tail; public: SingleLL(); void pushFront(int i); int topFront(); void popFront(); void pushBack(int i); int topBack(); void popBack(); bool find(int key); void erase(int key); void addBefore(int beforekey,int key); void addAfter(int afterkey,int key); bool empty(); void traverse(); }; SingleLL::SingleLL(){ head = nullptr; tail = nullptr; } void SingleLL::pushFront(int i) { Node * newNode =new Node; newNode-&gt;data=i; newNode-&gt;next=head; head=newNode; if(tail==nullptr) tail = head; } int SingleLL::topFront() { if(empty()) { cout&lt;&lt;"No element at the front top.\n"; return 0; } return head-&gt;data; } void SingleLL::popFront() { if (empty()){ cout&lt;&lt;"No element to pop.\n"; return; } head=head-&gt;next; if(head==nullptr) tail=nullptr; } void SingleLL::traverse() { if (empty()) cout&lt;&lt;"empty list. add elements"; Node * ptr = head; while(ptr!=nullptr) { cout&lt;&lt;ptr-&gt;data; ptr=ptr-&gt;next; } } bool SingleLL::empty() { return head==nullptr; } int SingleLL::topBack() { if(empty()) { cout&lt;&lt;"No element at the back top.\n"; return 0; } return tail-&gt;data; } void SingleLL::popBack() { if(empty()){ cout&lt;&lt;"No element to pop\n"; return; } Node *ptr=head; if(head-&gt;next==nullptr) { head=nullptr; tail=nullptr; } while(ptr-&gt;next-&gt;next != nullptr) { ptr=ptr-&gt;next; } tail=ptr; ptr-&gt;next=nullptr; } void SingleLL::pushBack(int i) { Node * newNode2 =new Node; newNode2-&gt;data=i; newNode2-&gt;next=nullptr; if(tail!=nullptr) tail-&gt;next=newNode2; tail=newNode2; if(head==nullptr) head=tail; } bool SingleLL::find(int key) { if(head == nullptr) return false; Node * boolfinder = head; while(boolfinder-&gt;next!=nullptr) { if(boolfinder-&gt;data==key) { return true; } boolfinder=boolfinder-&gt;next; } return false; } void SingleLL::erase(int key) { if(find(key)) { if (head-&gt;data==key) { popFront(); return; } if(tail-&gt;data==key) { popBack(); return; } Node * finderprev = head; Node * findererase = head-&gt;next; while(findererase!=nullptr) { if(findererase-&gt;data==key) { finderprev-&gt;next=findererase-&gt;next; free(findererase); break; } findererase=findererase-&gt;next; finderprev=finderprev-&gt;next; } } else cout&lt;&lt;"There is no such key to erase"; } void SingleLL::addAfter(int afterkey,int key) { Node * newNode =new Node; newNode-&gt;data=key; Node * ptr = head; while(ptr!=nullptr) { if(ptr-&gt;data==afterkey) { newNode-&gt;next=ptr-&gt;next; ptr-&gt;next=newNode; if(newNode-&gt;next==nullptr) tail=newNode; return; } ptr=ptr-&gt;next; } cout&lt;&lt;"There is no "&lt;&lt;afterkey&lt;&lt;" key to add "&lt;&lt;key&lt;&lt;" key before it."; } void SingleLL::addBefore(int keybefore,int key) { if(head-&gt;data==keybefore) { pushFront(key); return; } Node * newNode1 = new Node; newNode1-&gt;data=key; Node *ptr = head-&gt;next; Node *ptrprev = head; while(ptr!=nullptr) { if(ptr-&gt;data==keybefore) { newNode1-&gt;next=ptr; ptrprev-&gt;next=newNode1; return; } ptr=ptr-&gt;next; ptrprev=ptrprev-&gt;next; } cout&lt;&lt;"There is no"&lt;&lt;keybefore&lt;&lt;" key to add "&lt;&lt;key&lt;&lt;" key before it."; } int main() { SingleLL l1; for(int i=10;i&gt;=1;i--) l1.pushFront(i); l1.traverse(); l1.popFront(); cout&lt;&lt;"\n"; l1.traverse(); for(int i=0;i&lt;8;i++) l1.popFront(); cout&lt;&lt;"\n"; l1.traverse(); l1.popFront(); l1.popFront(); l1.popBack(); if(l1.empty()) cout&lt;&lt;"linked list is empty.\n"; l1.topBack(); l1.popBack(); return 0; } </code></pre> <p>I know that many things that I have used is not upto mark, like I have used struct like in old c where it contains data only. I have seen implementation of linked list using class in few other languages like java and python. But since C++ takes many or we can say all features from c language and adds O.O.P.to that, there are many things different in this language. Can anyone provide me the valuable code review and point out what are the things that I need to improve in my coding style. And how can I improve my O.O.P. design skills. What are the mistakes in this code? And also what changes should I do to make it full modern powerful C++ code? And even though I will try it myself anyways i need valuable insight from this community on how to templatize or make this class generic so that it takes any atomic data type not only integer type as it does now.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:23:08.370", "Id": "408449", "Score": "1", "body": "C++ doesn't just bolt on OOP, but adds support for more paradigms. Pure OOP isn't really good C++ anyways. And there is Nothing wrong with having a POD, especially as an implementation-detail." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T16:38:12.153", "Id": "408733", "Score": "0", "body": "You don't want to use `cout << …` inside a library as you might not always want to see the text on the console." } ]
[ { "body": "<h2>Code Review:</h2>\n<p>Please stop doing this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>It's a bad habit that will one day cause you lots of grief because it can silently change the meaning of the code. See: <a href=\"https://stackoverflow.com/a/1453605/14065\">Why is “using namespace std” considered bad practice?\n</a></p>\n<p>Not indenting after <code>public/private</code> makes it very hard to spot the public interface:</p>\n<pre><code>class SingleLL{\n private:\n Node * head;\n Node * tail;\n public:\n SingleLL();\n};\n</code></pre>\n<p>Much easier if you had written like this:</p>\n<pre><code>class SingleLL{\n private:\n Node * head;\n Node * tail;\n public:\n SingleLL();\n};\n</code></pre>\n<p>The <code>*</code> is part of the type. Put it with the type not half way to the identifier.</p>\n<pre><code>Node * head\n</code></pre>\n<p>Prefer to use the initializer list to initialize member variables.</p>\n<pre><code>SingleLL::SingleLL(){\n head = nullptr;\n tail = nullptr;\n}\n</code></pre>\n<p>Like this:</p>\n<pre><code>SingleLL::SingleLL()\n : head(nullptr)\n , tail(nullptr)\n{}\n</code></pre>\n<p>If the members had constructors then you would have constructed them before the code block then re-assigned them with the assignment operator. I know it seems trivial but changing types is a common maintenance task. If the type of the object but was expecting the behavior to not change then you now if a non optimal initialization strategy.</p>\n<p>Sure this works:</p>\n<pre><code>void SingleLL::pushFront(int i)\n{\n Node * newNode =new Node;\n newNode-&gt;data=i;\n newNode-&gt;next=head;\n head=newNode;\n if(tail==nullptr)\n tail = head;\n}\n</code></pre>\n<p>But it is very verbose. Why not create and initialize the object in one go?</p>\n<pre><code>void SingleLL::pushFront(int i)\n{\n head = new Node{i, head};\n if(tail==nullptr)\n tail = head;\n}\n</code></pre>\n<p>I know checking is the nice thing to do.</p>\n<pre><code>int SingleLL::topFront()\n{\n if(empty())\n {\n cout&lt;&lt;&quot;No element at the front top.\\n&quot;;\n return 0;\n }\n return head-&gt;data;\n}\n</code></pre>\n<p>But if your code guarantees that the list has values then this becomes a waste of time:</p>\n<pre><code>// Here I am checking that the list is not empty before\n// entering the loop and getting the value. So the internal\n// check is completely wasted.\nwhile(!list.empty()) {\n std::cout &lt;&lt; list.topFront();\n list.popFront();\n}\n</code></pre>\n<p>There are times though when a check should be done. So most containers provide two accesses mechanisms. Both a checked and an un-checked version. It may be worth adding an unchecked version for situations where you don't need to check (like the loop above).</p>\n<p>Same comment as above.</p>\n<pre><code>void SingleLL::popFront()\n{\n if (empty()){\n cout&lt;&lt;&quot;No element to pop.\\n&quot;;\n return;\n }\n head=head-&gt;next;\n if(head==nullptr)\n tail=nullptr;\n}\n</code></pre>\n<p>I would also note that printing to the output so not a good idea for a generic container. Throw an exception or do nothing.</p>\n<p>Sure have a traverse.</p>\n<pre><code>void SingleLL::traverse()\n // STUFF\n cout&lt;&lt;ptr-&gt;data;\n</code></pre>\n<p>But why <code>std::cout</code>? You may not want to print it. Allow the caller to pass in a function and do an operation on the data. Then call the function for each node.</p>\n<p>That's a good test.</p>\n<pre><code>bool SingleLL::empty()\n</code></pre>\n<p>But it does not modify the state of the object. So you should mark it as a <code>const</code> method. <code>bool SingleLL::empty() const</code>.</p>\n<hr />\n<p>Update to implement traverse to show that you can apply an external function to all elements in the list:</p>\n<p>Original code:</p>\n<pre><code>void SingleLL::traverse()\n{\n if (empty())\n cout&lt;&lt;&quot;empty list. add elements&quot;;\n Node * ptr = head;\n while(ptr!=nullptr)\n {\n cout&lt;&lt;ptr-&gt;data;\n ptr=ptr-&gt;next;\n }\n}\n</code></pre>\n<p>Modify to pass function/functor/lambda</p>\n<pre><code>// Use a template for the function\n// This is because there are several different types that can\n// act like a function and you should be able to support all of them.\n// --\n// If you want to limit this and support only a specific type that\n// is possible.\n// --\n// Alternatively you can use the std::function&lt;void(int)&gt; will\n// work just as well and be a specific type that accepts most function\n// like objects.\ntemplate&lt;typename F&gt;\nvoid SingleLL::traverse(F const&amp; action)\n{\n Node * ptr = head;\n while(ptr!=nullptr)\n {\n action(ptr-&gt;data);\n ptr=ptr-&gt;next;\n }\n}\n</code></pre>\n<p>Now we can call traverse like this:</p>\n<pre><code>SingleLL list;\n// Add items.\n\n// Pass a lambda\nlist.traverse([](int val){std::cout &lt;&lt; val &lt;&lt; &quot; &quot;;});\n\n// Pass a functor\nstruct Functor {\n void operator()(int val) const {std::cout &lt;&lt; val &lt;&lt; &quot; &quot;;}\n};\nlist.traverse(Functor{});\n\n// Pass a function\nvoid function(int val) {std::cout &lt;&lt; val &lt;&lt; &quot; &quot;;}\nlist.traverse(&amp;function);\n\n----\n\n// Now the reason in allowing traverse() to have an action ist\n// that you can now manipulate the data in the list (not just print it)\n\nlist.traverse([](int&amp; val) const {val += 2;}); // Add two to each member.\n\nint count[2] = {0,0};\nlist.traverse([&amp;count](int val) const {++count[val%2];}); // Count odd and even values in the list.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T08:25:58.660", "Id": "409012", "Score": "0", "body": "Thanks Martin for this review. Learnt many things from this single review. I also wanted to ask what would be the best practices to make this class generic. At this point it takes data which are integers only. I want to templatize it. And may be i could use template specialization so that i could add other nodes or linked lists as data like extend() in python or '+' operator for strings in C++. What would be the major things to take care in such case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T11:38:13.757", "Id": "429684", "Score": "0", "body": "If anyone is watching, I have one doubt in above code review which i realised after this much time. Martin here advised me to allow the caller to pass the function to my traverse method right? As far as I know, unlike python, functions are not objects in c++ so we cannot pass the name of the function as argument in c++ right? the only way i can think of to achieve that is to use function pointers. Can anyone help me with that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:57:13.493", "Id": "429697", "Score": "1", "body": "@shishirjha You can not pass a function by name. But you can pass any function like object. This includes function pointer, functor (function like object ie an object of a class that implements `operator()`) and lambda (syntactic sugar to create an anonymous functor)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:02:23.070", "Id": "429698", "Score": "0", "body": "@shishirjha Added an example to the end that uses a lambda." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T18:09:47.860", "Id": "211339", "ParentId": "211166", "Score": "5" } } ]
{ "AcceptedAnswerId": "211339", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:07:41.223", "Id": "211166", "Score": "2", "Tags": [ "c++", "linked-list" ], "Title": "Implementation of linked list in C++ using class" }
211166
<blockquote> <p>Write a simple monitoring navigation function.</p> </blockquote> <ul> <li>I feel logic judgment still needs to be optimized.</li> <li>I don't have a clear idea right now about code logic such as reducing <code>if</code> statements</li> <li>How can I optimize the performance of this code?</li> </ul> <p></p> <pre><code>&lt;!-- =panel: start --&gt; &lt;div class="panel" role="region"&gt;&lt;/div&gt; &lt;!-- =panel: end --&gt; &lt;script&gt; var em = document.querySelectorAll(".panel"); var viewHeight = window.innerHeight; var clientHeight = document.body.clientHeight; var timeOut = null; em.forEach(function (em, index) { watchNav(em); }); function watchNav(em) { var emHeight = em.offsetHeight; var emTop = em.offsetTop; clearTimeout(timeOut); window.addEventListener("scroll", function (e) { var scrollY = window.scrollY; timeOut = setTimeout(function () { // Logical judgment: how to optimize, want better implementation. // Such as reducing the if statement // ++++++++++++++++ if (scrollY &gt; emTop || scrollY + viewHeight / 2 &gt; emTop || scrollY + viewHeight &gt; emTop + emHeight) { console.log("...activing..."); em.classList.add("view-focus"); } else { console.log("none"); em.classList.remove("view-focus"); } if (scrollY &gt; emTop + emHeight / 2) { console.log("none"); em.classList.remove("view-focus"); } // ++++++++++++++++ }, 40); }, false); } &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:34:17.870", "Id": "408290", "Score": "1", "body": "`.querySelectorAll()` has a `.forEach()` method. `Array.prototype.slice()` is not necessary. See also [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:59:14.593", "Id": "408385", "Score": "1", "body": "Welcome, to Code Review, my kin." } ]
[ { "body": "<p>A few comments:</p>\n\n<ul>\n<li><code>Array.forEach</code> takes a callback, this can be done directly as so: <code>ems.forEach(watchNav)</code></li>\n<li>Also, you have scope conflicts: the global variable <code>em</code>, and the function parameter <code>em</code></li>\n<li>A third comment: You should n ot edit your question based on feedback in comments.</li>\n<li>Your if statement is fine.</li>\n</ul>\n\n<pre><code>\n&lt;script&gt;\n var ems = document.querySelectorAll(\".panel\"),\n viewHeight = window.innerHeight,\n clientHeight = document.body.clientHeight,\n timeOut = null;\n\n ems.forEach(watchNav);\n\n function watchNav(em) {\n var emHeight = em.offsetHeight;\n var emTop = em.offsetTop;\n clearTimeout(timeOut);\n\n window.addEventListener(\"scroll\", function (e) {\n var scrollY = window.scrollY;\n\n timeOut = setTimeout(function () {\n // Logical judgment: how to optimize, want better implementation.\n // Such as reducing the if statement\n // ++++++++++++++++\n if (scrollY &gt; emTop || scrollY + viewHeight / 2 &gt; emTop || scrollY + viewHeight &gt; emTop + emHeight) {\n console.log(\"...activing...\");\n em.classList.add(\"view-focus\");\n } else {\n console.log(\"none\");\n em.classList.remove(\"view-focus\");\n }\n\n if (scrollY &gt; emTop + emHeight / 2) {\n console.log(\"none\");\n em.classList.remove(\"view-focus\");\n }\n // ++++++++++++++++\n }, 40);\n }, false);\n }\n&lt;/script&gt;\n```\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T03:44:24.480", "Id": "408486", "Score": "0", "body": "Thank you for your reply. I want to make the code more optimized." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-11T04:29:50.163", "Id": "449164", "Score": "2", "body": "I would argue that a better way to thank someone is to up-vote the answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:58:38.333", "Id": "211204", "ParentId": "211167", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:17:21.120", "Id": "211167", "Score": "4", "Tags": [ "javascript", "performance", "array", "event-handling" ], "Title": "Monitoring navigation function: logic judgment" }
211167
<p>I've been working for a while on locking resources (state objects) so that the only way to access them is by acquiring a lock. This moves the responsibility for locking from the <em>user</em> of the state to the state itself. I wanted something with a lot of syntactic sugar so that once the lock is acquired the state object is used via a reference without a need for special getters and setters.</p> <pre><code>namespace Lockable { public delegate void ActionRef&lt;T&gt;(ref T r1); public delegate void ActionIn&lt;T&gt;(in T r1); public delegate RES FuncRef&lt;T, RES&gt;(ref T r1); public delegate RES FuncIn&lt;T, RES&gt;(in T r1); public delegate void ActionRef&lt;T1, T2&gt;(ref T1 r1, ref T2 r2); public delegate void ActionIn&lt;T1, T2&gt;(in T1 r1, in T2 r2); public delegate RES FuncRef&lt;T1, T2, RES&gt;(ref T1 r1, ref T2 r2); public delegate RES FuncIn&lt;T1, T2, RES&gt;(in T1 r1, in T2 r2); public delegate void ActionRef&lt;T1, T2, T3&gt;(ref T1 r1, ref T2 r2, ref T3 r3); public delegate void ActionIn&lt;T1, T2, T3&gt;(in T1 r1, in T2 r2, in T3 r3); public delegate RES FuncRef&lt;T1, T2, T3, RES&gt;(ref T1 r1, ref T2 r2, ref T3 r3); public delegate RES FuncIn&lt;T1, T2, T3, RES&gt;(in T1 r1, in T2 r2, in T3 r3); public class Lockable&lt;T&gt; where T : new() { public Lockable() =&gt; this.val = new T(); public Lockable(T val) =&gt; this.val = val; readonly object theLock = new object(); T val; public void Lock(ActionRef&lt;T&gt; f) { lock (theLock) f(ref val); } public void Lock(ActionIn&lt;T&gt; f) { lock (theLock) f(in val); } public TRES Lock&lt;TRES&gt;(FuncRef&lt;T, TRES&gt; f) { lock (theLock) return f(ref val); } public TRES Lock&lt;TRES&gt;(FuncIn&lt;T, TRES&gt; f) { lock (theLock) return f(in val); } public class TwoLockable&lt;T2&gt; where T2 : new() { public TwoLockable(Lockable&lt;T&gt; val1, Lockable&lt;T2&gt; val2) { this.l1 = val1; this.l2 = val2; } readonly Lockable&lt;T&gt; l1; readonly Lockable&lt;T2&gt; l2; public void Lock(ActionRef&lt;T, T2&gt; f) { lock (l1.theLock) lock (l2.theLock) f(ref l1.val, ref l2.val); } public void Lock(ActionIn&lt;T, T2&gt; f) { lock (l1.theLock) lock (l2.theLock) f(in l1.val, in l2.val); } public TRES Lock&lt;TRES&gt;(FuncRef&lt;T, T2, TRES&gt; f) { lock (l1.theLock) lock (l2.theLock) return f(ref l1.val, ref l2.val); } public TRES Lock&lt;TRES&gt;(FuncIn&lt;T, T2, TRES&gt; f) { lock (l1.theLock) lock (l2.theLock) return f(in l1.val, in l2.val); } public class ThreeLockable&lt;T3&gt; where T3 : new() { public ThreeLockable(Lockable&lt;T&gt; val1, Lockable&lt;T2&gt; val2, Lockable&lt;T3&gt; val3) { this.l1 = val1; this.l2 = val2; this.l3 = val3; } readonly Lockable&lt;T&gt; l1; readonly Lockable&lt;T2&gt; l2; readonly Lockable&lt;T3&gt; l3; public void Lock(ActionRef&lt;T, T2, T3&gt; f) { lock (l1.theLock) lock (l2.theLock) lock (l3.theLock) f(ref l1.val, ref l2.val, ref l3.val); } public void Lock(ActionIn&lt;T, T2, T3&gt; f) { lock (l1.theLock) lock (l2.theLock) lock (l3.theLock) f(in l1.val, in l2.val, in l3.val); } public TRES Lock&lt;TRES&gt;(FuncRef&lt;T, T2, T3, TRES&gt; f) { lock (l1.theLock) lock (l2.theLock) lock (l3.theLock) return f(ref l1.val, ref l2.val, ref l3.val); } public TRES Lock&lt;TRES&gt;(FuncIn&lt;T, T2, T3, TRES&gt; f) { lock (l1.theLock) lock (l2.theLock) lock (l3.theLock) return f(in l1.val, in l2.val, in l3.val); } } public ThreeLockable&lt;T3&gt; Combine&lt;T3&gt;(Lockable&lt;T3&gt; l3) where T3 : new() =&gt; new ThreeLockable&lt;T3&gt;(this.l1, this.l2, l3); } public TwoLockable&lt;T2&gt; Combine&lt;T2&gt;(Lockable&lt;T2&gt; l2) where T2 : new() =&gt; new TwoLockable&lt;T2&gt;(this, l2); } } </code></pre> <p>With that code, I can now do this:</p> <pre><code>public readonly Lockable&lt;Customers&gt; Customers = new Lockable&lt;Customers&gt;(); </code></pre> <p>and now the <em>only</em> way to access <code>Customers</code> is via the Lock method like this:</p> <pre><code>Customers.Lock((ref Customers Customers) =&gt; { Log(Customers.GetPhone("John")); Customers=new Customers(); Customers.Add("Mary"); }); </code></pre> <p>or to return a value I can do:</p> <pre><code>var count = Customers.Lock((ref Customers Customers) =&gt; Customers.Count()); </code></pre> <p>Note that you can use the above to modify the state <em>without</em> locking i.e.:</p> <pre><code>var UnlockedCustomers = Customers.Lock((ref Customers Customers) =&gt; Customers); UnlockedCustomers.Add("Dave"); // unlocked !!! </code></pre> <p>This is by design as I wanted to allow that but make it very explicit in the code (unlike forgetting to lock..), if this is not desired the locks returning values need to be removed (<code>FuncRefs</code> etc.).</p> <p>If I need to lock both I combine the Locks:</p> <pre><code>public readonly Lockable&lt;Agents&gt; Agents = new Lockable&lt;Agents&gt;(); Customers.Combine(Agents).Lock((ref Customers Customers, ref Agents Agents) =&gt; { // both Agents and Customers are locked here ! }); </code></pre> <p>I included versions of combining 2 and 3 Lockables. More can be added. Note that as with locks you have to always combine in the same order or risk deadlocks. It would be interesting to think of ways around this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:14:17.297", "Id": "408311", "Score": "0", "body": "Why does `Lock` have various `ref` and `in` overloads, but no 'plain' variants?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:19:09.323", "Id": "408313", "Score": "0", "body": "Without a ref the lambdas will get their own local reference to the state (val) and assigning to it will only change the local copy which is confusing and error prone. I mostly use this with immutable types so being able to reassign was a main goal .. (think of a redux like 'store')" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:35:58.213", "Id": "408453", "Score": "1", "body": "I'm not sure this pattern improves readability of the code significantly. In my opinion you might be adding quite a bit of complexity for other programmers to maintain this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:40:22.167", "Id": "408454", "Score": "0", "body": "svek the idea is not to improve readability but to prevent access without locking. But still, the Lockable class itself is complex but using it is (to me) very straight forward" } ]
[ { "body": "<p>The only thing I can spot here is in this line</p>\n\n<pre><code> public class Lockable&lt;T&gt; where T : new()\n</code></pre>\n\n<p>The constraint is probably not bulletproof. What would happen if I did something like</p>\n\n<pre><code> var foo = Lockable&lt;Lockable&lt;Foo&gt;&gt;();\n</code></pre>\n\n<p>I would imagine this would make for an exciting explosion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:53:00.610", "Id": "408456", "Score": "2", "body": ":) yeah probably .. too scared to try" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:46:22.790", "Id": "211228", "ParentId": "211169", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:26:46.070", "Id": "211169", "Score": "0", "Tags": [ "c#", "functional-programming", "locking" ], "Title": "Managing locking for access" }
211169
<p>My code-editor "show hints" says that the method length exceeds 20 lines. How can I refactor the <code>setEmailTemplateBcc</code> function? </p> <pre><code>private function setBcc($bcc) { if ($bcc) { $this-&gt;bcc = explode(',', $bcc); } } public function setType($type) { $this-&gt;setEmailTemplateBcc($type); return $this; } private function setEmailTemplateBcc($type) { $template = ''; $bcc = ''; switch ($type) { case self::EMAIL_NEW_SUBSCRIPTION: $template = DataHelper::XML_PATH_SUBSCRIPTION_EMAIL; $bcc = DataHelper::XML_PATH_REMINDER_EMAIL_BCC; break; case self::EMAIL_CARD_ADD: $template = DataHelper::XML_PATH_NEW_CARD_ADD_EMAIL; $bcc = DataHelper::XML_PATH_NEW_CARD_ADD_EMAIL_BCC; break; case self::EMAIL_PAYMENT_FAILED: $template = DataHelper::XML_PATH_PAYMENT_FAILED_EMAIL; $bcc = DataHelper::XML_PATH_PAYMENT_FAILED_EMAIL_BCC; break; case self::EMAIL_PROFILE_UPADATE: $template = DataHelper::XML_PATH_PROFILE_UPDATE_EMAIL; $bcc = DataHelper::XML_PATH_PROFILE_UPDATE_EMAIL_BCC; break; case self::EMAIL_REMINDER: $template = DataHelper::XML_PATH_REMINDER_EMAIL; $bcc = DataHelper::XML_PATH_REMINDER_EMAIL_BCC; break; case self::EMAIL_TOPUP_REMINDER: $template = DataHelper::XML_PATH_EWALLET_TOPUP_REMINDER_EMAIL; $bcc = DataHelper::XML_PATH_EWALLET_TOPUP_REMINDER_EMAIL; break; } $this-&gt;setTemplate($template); $this-&gt;setBcc($bcc); } </code></pre>
[]
[ { "body": "<p>I would create two new static variables in your class, arrays that contain all options, like</p>\n\n<pre><code>public static $template = [\n self::EMAIL_NEW_SUBSCRIPTION =&gt; DataHelper::XML_PATH_SUBSCRIPTION_EMAIL,\n self::EMAIL_CARD_ADD =&gt; DataHelper::XML_PATH_NEW_CARD_ADD_EMAIL_BCC,\n // and so on\n];\n</code></pre>\n\n<p>then setting the email template will be as simple as just one line:</p>\n\n<pre><code>$template = self::$template[self::EMAIL_CARD_ADD] ?? '';\n</code></pre>\n\n<p>and the same goes for BCC</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:45:38.507", "Id": "211171", "ParentId": "211170", "Score": "3" } }, { "body": "<p>Or you can try this approach.</p>\n\n<pre><code>interface EmailTemplateInterface\n{\n public function create($type);\n\n /**\n * @param string $name\n * @return bool\n */\n public function supports($type);\n}\n\nclass EmailNewSubscription implements EmailTemplateInterface\n{\n /**\n * @inheritdoc\n */\n public function create($type)\n {\n echo 'XML_PATH_SUBSCRIPTION_EMAIL';\n }\n\n /**\n * @inheritdoc\n */\n public function supports($type)\n {\n return $type === 'XML_PATH_SUBSCRIPTION_EMAIL';\n }\n}\n\nclass EmailCardAdd implements EmailTemplateInterface\n{\n /**\n * @inheritdoc\n */\n public function create($type)\n {\n echo 'EMAIL_CARD_ADD';\n }\n\n /**\n * @inheritdoc\n */\n public function supports($type)\n {\n return $type === 'EMAIL_CARD_ADD';\n }\n}\n\nclass BuildEmailTemplate implements EmailTemplateInterface\n{\n /**\n * @var EmailTemplateInterface[]\n */\n private $emailTemplateInterface;\n\n /**\n * @param EmailTemplateInterface[] $emailCreators\n * @throws \\InvalidArgumentException\n */\n public function __construct(array $emailCreators)\n {\n foreach ($emailCreators as $builder) {\n if (!$builder instanceof EmailTemplateInterface) {\n throw new \\InvalidArgumentException('emailCreator is not valid');\n }\n }\n $this-&gt;emailTemplateInterface = $emailCreators;\n }\n\n /**\n * @inheritdoc\n */\n public function create($type)\n {\n foreach ($this-&gt;emailTemplateInterface as $builder) {\n if ($builder-&gt;supports($type)) {\n return $builder-&gt;create($type);\n }\n }\n\n throw new \\UnexpectedValueException('email creator for supporting this type is not found');\n }\n\n /**\n * @inheritdoc\n */\n public function supports($type)\n {\n foreach ($this-&gt;emailTemplateInterface as $builder) {\n if ($builder-&gt;supports($type)) {\n return true;\n }\n }\n\n return false;\n }\n\n}\n// usage\n$emailCreators = [\n new EmailNewSubscription(),\n new EmailCardAdd(),\n];\n\n$delegate = new BuildEmailTemplate($emailCreators);\n\n$delegate-&gt;create('XML_PATH_SUBSCRIPTION_EMAIL');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T16:03:47.167", "Id": "211486", "ParentId": "211170", "Score": "0" } } ]
{ "AcceptedAnswerId": "211171", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T09:18:35.687", "Id": "211170", "Score": "0", "Tags": [ "php" ], "Title": "Selecting an email template and BCC address based on the message type" }
211170
<p>I have the function which builds and return Slack message with <code>text</code> and <code>attachments</code>. How can I refactor this function to make it easier to test? Should I split it into multiple functions?</p> <pre><code>def build_list_message(team_id, user_id, msg_state=None, chl_state=None): if not msg_state: msg_state = {} if not chl_state: chl_state = {} resource_type = msg_state.get('resource_type', 'all') availability = msg_state.get('resource_availability', 'all') pages = Page.objects.none() async_tasks = AsyncTask.objects.none() if resource_type in ['web_pages', 'all']: pages = Page.objects.filter( user__team__team_id=team_id).order_by('title') if resource_type in ['async_tasks', 'all']: async_tasks = AsyncTask.objects.filter( user__team__team_id=team_id).order_by('title') if availability == 'available': pages = pages.filter(available=True) async_tasks = async_tasks.filter(available=True) elif availability == 'unavailable': pages = pages.filter(available=False) async_tasks = async_tasks.filter(available=False) channel_id = chl_state.get('channel_id') if channel_id: pages = pages.filter(alert_channel=channel_id) async_tasks = async_tasks.filter(alert_channel=channel_id) user = SlackUser.retrieve(team_id, user_id) attachments = [ _build_filters(resource_type, availability), *[_build_page_item(p, user) for p in pages], *[_build_async_task_item(at, user) for at in async_tasks] ] return { 'text': "Here's the list of all monitoring resources", 'attachments': attachments } </code></pre> <p>Here is private functions:</p> <pre><code>def _build_filters(resource_type, availability): resource_types = [ {"text": "All types", "value": "all"}, {"text": ":link: Webpages", "value": "web_pages"} ] availability_choices = [ {"text": "Available / Unavailable", "value": "all"}, {"text": ":white_circle: Available", "value": "available"}, {"text": ":red_circle: Unavaliable", "value": "unavailable"} ] selected_resource_types = list(filter( lambda t: t['value'] == resource_type, resource_types)) selected_availability_choices = list(filter( lambda a: a['value'] == availability, availability_choices)) return { "fallback": "Resource filters", "color": "#d2dde1", "mrkdwn_in": ["text"], "callback_id": "resource_filters", "actions": [ { "name": "resource_type", "text": "Type", "type": "select", "options": resource_types, "selected_options": selected_resource_types }, { "name": "resource_availability", "text": "Available", "type": "select", "options": availability_choices, "selected_options": selected_availability_choices } ] } def _build_page_item(page, user): return { "fallback": "Page", "color": page.status_color, "mrkdwn_in": ["fields"], "callback_id": 'page_change', "fields": [ { "title": page.title, "value": f"_Page_ ({page.status})" }, { "title": "URL", "value": page.url } ], "footer": _build_resource_footer(page), "actions": _build_resource_item_actions(page, user) } def _build_async_task_item(async_task, user): return { "fallback": "Async task", "color": async_task.status_color, "mrkdwn_in": ["fields"], "callback_id": 'async_task_change', "fields": [ { "title": async_task.title, "value": f"_Async task_ ({async_task.status})" }, { "title": "URL", "value": async_task.url } ], "footer": _build_resource_footer(async_task), "actions": _build_resource_item_actions(async_task, user) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:11:27.860", "Id": "408362", "Score": "0", "body": "Please include your imports. Currently `Page`, `AsyncTask` and `SlackUser` are undefined. Are they from some module or die you write them yourself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:21:27.063", "Id": "408363", "Score": "0", "body": "`Page`, `AsyncTask` and `SlackUser` are simply Django models." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:37:04.573", "Id": "408431", "Score": "0", "body": "@Mathias Ettinger Added private functions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T15:30:20.007", "Id": "417321", "Score": "0", "body": "One thing to note is that leading [underscores](https://dbader.org/blog/meaning-of-underscores-in-python) in method names are *not* a privacy model, and should not be treated as such. Even though some IDE's do suggest the contrary, there is no existing privacy model in python" } ]
[ { "body": "<p>I've come back to this question about 4 or 5 times since it was originally posted, started writing up an answer, started doubting my alternative implementation, scrapped it, and then come back about a month later. This tells me a few things:</p>\n\n<ol>\n<li>You have a tricky problem, where the \"best\" solution is not necessarily intuitive, and how you measure \"best\" can vary wildly</li>\n<li>Overall, the code is pretty good, so I can't just write a more nit-picky answer and ignore the larger question of \"is this structured the right way\"</li>\n</ol>\n\n<p>Because I had such a hard time with this, I'm not going to completely rewrite this, or provide an alternate implementation, or anything like that. Instead, I'm going to call out some overall architecture and design choices that I think have made this tricky, some potential solutions with pros/cons, and then leave it as an exercise for the reader to decide what they want to do.</p>\n\n<p>I'll also include a few nitpicky things about the code, because that's just who I am as a person and I'll feel bad if I don't review your code at all.</p>\n\n<p>Lastly, I've never used Django before, so its very possible a much better solution exists within the framework, or that someone else has solved the problem in another 3rd party library, or whatever. I encourage you to do your own research on if Django can make this easier.</p>\n\n<hr>\n\n<h2>The problem</h2>\n\n<blockquote>\n <p>How can I refactor this function to make it easier to test?</p>\n</blockquote>\n\n<p>You're right that this is hard to test as-is. The most significant reason for this, IMO, is that you're mixing up a lot of magic, a lot of state that your function doesn't own, and the business logic that your function <em>does own</em>.</p>\n\n<h3>Magic</h3>\n\n<p>Your function(s) are littered with magic numbers, strings, etc. These are all things that apparently have significant meaning, and are very tightly coupled with your implementation. If you ever decide that you want your colors to change, or you want to change somethings title, or the default resource type, or whatever, then you have a lot of logic that assumes the magic.</p>\n\n<p>A good way to make this less magic, easier to test, and easier to update is to at least make all magic values constants at the beginning of the file. For example, if you do this <code>msg_state.get('resource_type', 'all')</code> then it seems a little unclear what we're doing; just some place-holder, or something more meaningful? But if you do this <code>msg_state.get('resource_type', DEFAULT_RESOURCE_TYPE)</code> then it becomes immediately clear. </p>\n\n<p>Note that you wouldn't want to do this <code>msg_state.get('resource_type', ALL_RESOURCE_TYPE)</code> because that isn't really any better than just putting <code>'all'</code> there, unless you think that the resource type meaning all would change values. </p>\n\n<p>This is also a good time to propose using <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>enum</code>s</a> instead of strings, as you get runtime validation of correct values (e.g. <code>ResourceTypeEnum.lAl</code> will give you an error that <code>lAl</code> is not a valid enum, while <code>'lAl'</code> won't warn you that you typoed your string.</p>\n\n<h3>State</h3>\n\n<p>Your function to build a message depends a lot on the state of your application, of third party libraries, the framework, etc. In just this one function, you explicitly query the following kinds of state:</p>\n\n<ol>\n<li>Django state (pages and tasks)</li>\n<li>Slack state (users)</li>\n<li>Application state (message, channels, teams)</li>\n</ol>\n\n<p>This couples you really tightly with these things that your function can't control, and is the death of any truly repeatable unit testing. There are a lot of ways you could address them; for example you could make a service per state and use <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">dependency injection</a> or some other inversion of control methodology. This is what I was playing around with for a while, and eventually came up with a 500 line, OOPomination that was super generic and super unreadable. I don't know what support Django has for this, but I would guess that at some point someone has made dependency injection easier.</p>\n\n<p>Ultimately, I think there is room for some level of encapsulation here. It is likely worthwhile to create separate methods for the different types of work, and filtering, etc. Could you subclass <code>Page</code> or <code>AsyncTask</code> to provide a <code>slack_item</code> property? Is there a better spot in your application to filter on resource type, or team, or availability, or channel, etc?</p>\n\n<h3>Business Logic</h3>\n\n<p>Once you peel everything back, your actual logic is pretty straightforward:</p>\n\n<ol>\n<li>Get the list of resources that meet some filtering criteria</li>\n<li>Transform them into json that meets some Slack specification</li>\n<li>Send it back</li>\n</ol>\n\n<p>This part is pretty straightforward, and I don't have a lot to say about it. These each sound like good candidates for unit testing though, and might be worth splitting up that way.</p>\n\n<h2>A potential solution</h2>\n\n<p>I think whatever you do to restructure this is going to add more code and complexity (by becoming more generic/loosely coupled), and how much of that makes sense for your use-case depends. If your tool is meant to just be a quick-and-dirty tool for your team, it might not make sense to split up the code. If you want this to be around longer, or there are plans for future enhancements, this might be a good time to break things up. I think I'd roughly recommend the following:</p>\n\n<ol>\n<li>For different kinds of data (e.g. <code>Page</code> vs <code>AsyncTask</code> vs other stuff), create different methods/handlers/classes/whatever for each one that is responsible for transforming it into the Slack format json. A perfect solution would be able to take advantage of duck-typing, where you could just do <code>input_object.to_slack_json()</code> </li>\n<li>Play around with the filtering - can this be done by the caller instead of your application? Can you encapsulate how to do it in the same per-type method/handler/class/whatever as previously suggested?</li>\n<li>Instead of getting your state within the function, pass it in instead. Then it can be truly independent of how it is being run, and the unit test can construct the input as desired.</li>\n</ol>\n\n<hr>\n\n<p>As promised, here are some </p>\n\n<h2>Little nitpicky things</h2>\n\n<p>When doing this:</p>\n\n<pre><code>if not msg_state:\n msg_state = {}\n</code></pre>\n\n<p>It may be easier to write it this way: <code>msg_state = msg_state or {}</code>. <code>or</code> will pick the first truthy-element, or the last non-truthy element (e.g. the empty dictionary).</p>\n\n<hr>\n\n<p>Instead of using this (and needlessly building lists just to throw them away)</p>\n\n<pre><code>attachments = [\n _build_filters(resource_type, availability),\n *[_build_page_item(p, user) for p in pages],\n *[_build_async_task_item(at, user) for at in async_tasks]\n]\n</code></pre>\n\n<p>Consider using <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.chain\" rel=\"noreferrer\"><code>itertools.chain</code></a>:</p>\n\n<pre><code>attachments = list(\n itertools.chain(\n (_build_filters(resource_type, availability), ),\n (_build_page_item(p, user) for p in pages),\n (_build_async_task_item(at, user) for at in async_tasks)\n )\n)\n</code></pre>\n\n<hr>\n\n<p>Instead of using <code>list</code> + <code>filter</code>, and <code>lambda</code> functions that add just a bit of extra mental overhead</p>\n\n<pre><code>selected_resource_types = list(filter(\n lambda t: t['value'] == resource_type, resource_types))\n\nselected_availability_choices = list(filter(\n lambda a: a['value'] == availability, availability_choices))\n</code></pre>\n\n<p>Use a list comprehension</p>\n\n<pre><code>selected_resource_types = [\n rt for rt in resource_types if resource_type[\"value\"] == rt\n]\n\nselected_availability_choices = [\n ac for ac in availability_choices if availability[\"value\"] == ac \n]\n</code></pre>\n\n<p>Or, define a class that represents a Slack option, or a selection of Slack options, and encapsulate this logic in that class. Then you don't have to repeat yourself between <code>resource_types</code> and <code>availability_choices</code>.</p>\n\n<p>Rough outline:</p>\n\n<pre><code>class SlackOption:\n\n def __init__(self, text, value):\n self.text = text\n self.value = value\n\nclass SlackOptions:\n\n def __init__(self, choices):\n self.choices = choices\n\n def get_selection(self, choice):\n return [option for option in self.choices if option.value == choice]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-09T15:19:03.603", "Id": "227730", "ParentId": "211173", "Score": "10" } }, { "body": "<p>We can learn a lot about what code is supposed to do by giving our functions explicit type signatures. Starting at the top, what are we working with?</p>\n\n<ul>\n<li><code>team_id</code> is some kind of Team ID. It's probably a string, or maybe an int, but for now I'll assume it's a <code>TeamID</code>. We know it's exactly what we need because it's passed as-is to the Django filters an <code>SlackUser.retrieve</code>. </li>\n<li><code>user_id</code> we can similarly assume is a <code>UserID</code>. However, look at how it's used: All we do with it is retrieve the <code>SlackUser</code>.\n\n<ul>\n<li>We shouldn't be calling this function unless we know the <code>team_id</code> and the <code>user_id</code>. <strong>What if we just had one argument <code>user:SlackUser</code>?</strong> Then we wouldn't need to read those DB tables from inside this function.</li>\n</ul></li>\n<li><code>msg_state</code> is supposed to be a dict, but we're letting the user pass in None. Possibly this argument might be a bigger dict with lots of other stuff in it, but for the purpose at hand it really just bundles up two shadow arguments.\n\n<ul>\n<li><code>resource_type</code>, which itself is just a bundle of <code>web_pages:bool=True</code> and <code>async_tasks:bool=True</code>.</li>\n<li><code>availability</code>, which likewise breaks out into <code>available:bool=True</code> and <code>unavailable:bool=True</code>. Those aren't great names; we can improve on them later.</li>\n</ul></li>\n<li><code>chl_state</code> is just masking our real parameter: <code>channel_id:Optional[ChannelID]=None</code>.</li>\n<li>We're returning a dict, but most of it's static. The part that we're actually computing is a list of dicts. \n\n<ul>\n<li>Those dicts clearly have a structure that's needed elsewhere. You have a few options for how to explain and enforce that structure; a small inheritance tree is probably advisable. I'll just assume you've got a class <code>UIMessageItem</code>.</li>\n<li>So the <em>interesting</em> functionality will return an <code>Iterable[UIMessageItem]</code>, and that will get wrapped by the outer dict structure you've got.</li>\n</ul></li>\n</ul>\n\n<h1>Round 1:</h1>\n\n<p>I've included <code>old_build_list_message</code>, as a wrapper to the new function, just to show how you would use the new version in place of the new one.</p>\n\n<h3>helpers:</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _build_filters(*,\n include_web_pages: bool = True,\n include_async_tasks: bool = True,\n include_available: bool = True,\n include_unavailable: bool = True)\n -&gt; UIMessageItem:\n ...\n\n\ndef _build_page_item(page: Page, user: SlackUser) -&gt; UIMessageItem:\n ...\n\n\ndef _build_async_task_item(task: AsyncTask, user: SlackUser) -&gt; UIMessageItem:\n ...\n\ndef old_build_list_message(team_id, user_id, msg_state, chl_state):\n return {\n 'text': \"Here's the list of all monitoring resources\",\n 'attachments': build_list_message(\n SlackUser.retrieve(team_id, user_id),\n include_web_pages: msg_state['resource_type'] in ['web_pages', 'all'],\n include_async_tasks: msg_state['resource_type'] in ['async_tasks', 'all'],\n include_available: msg_state['resource_availability'] in ['available', 'all'],\n include_unavailable: msg_state['resource_availability'] in ['unavailable', 'all'],\n channel_id: chl_state.get('channel_id')\n )\n }\n</code></pre>\n\n<h3>heart:</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>def build_list_message(user: SlackUser,\n *,\n include_web_pages: bool = True,\n include_async_tasks: bool = True,\n include_available: bool = True,\n include_unavailable: bool = True,\n channel_id: Optional[ChannelID] = None)\n -&gt; Iterable[UIMessageItem]:\n\n pages = Page.objects.none()\n async_tasks = AsyncTask.objects.none()\n\n if include_web_pages:\n pages = Page.objects.filter(\n user__team__team_id=user.team_id).order_by('title')\n\n if include_async_tasks:\n async_tasks = AsyncTask.objects.filter(\n user__team__team_id=user.team_id).order_by('title')\n\n if not include_unavailable:\n pages = pages.filter(available=True)\n async_tasks = async_tasks.filter(available=True)\n\n if not include_available:\n pages = pages.filter(available=False)\n async_tasks = async_tasks.filter(available=False)\n\n if channel_id:\n pages = pages.filter(alert_channel=channel_id)\n async_tasks = async_tasks.filter(alert_channel=channel_id)\n\n return [\n _build_filters(include_web_pages = include_web_pages,\n include_async_tasks = include_async_tasks,\n include_available = include_available,\n include_unavailable = include_unavailable),\n *[_build_page_item(p, user) for p in pages],\n *[_build_async_task_item(at, user) for at in async_tasks]\n ]\n\n</code></pre>\n\n<h1>Round 2:</h1>\n\n<ul>\n<li>The call to <code>_build_filters</code> seems out of place. It <em>doesn't</em> need the external state that our business logic needs.</li>\n<li>The business logic seems to be doing two very similar things at once. We'd like the parts that are the same to happen once, separately from the parts that are different.</li>\n<li>We could probably break the \"display\" logic out from the \"find\" logic.</li>\n</ul>\n\n<h3>helpers:</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _build_filters(whatever):\n '''At this point this is the problem of whoever's higher in the stack.'''\n ...\n\n\ndef _build_UI_message_item(item: Union[Page, AsyncTask],\n user: SlackUser)\n -&gt; UIMessageItem:\n ...\n\ndef old_build_list_message(team_id, user_id, msg_state, chl_state):\n items = build_list_message(\n SlackUser.retrieve(team_id, user_id),\n django_filter = django_filters(\n include_available = msg_state['resource_availability'] in ['available', 'all'],\n include_unavailable = msg_state['resource_availability'] in ['unavailable', 'all'],\n channel_id = chl_state.get('channel_id')\n ),\n include_web_pages = msg_state['resource_type'] in ['web_pages', 'all'],\n include_async_tasks = msg_state['resource_type'] in ['async_tasks', 'all']\n )\n filters_message = _build_filters(msg_state)\n\n return {\n 'text': \"Here's the list of all monitoring resources\",\n 'attachments': itertools.chain((filters_message, ),\n map(_build_UI_message_item, items)\n )\n }\n</code></pre>\n\n<h3>heart:</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>def django_filters(include_available: bool = True,\n include_unavailable: bool = True,\n channel_id: Optional[ChannelID] = None)\n -&gt; Callable[[QuerySet], QuerySet]:\n filters = {}\n\n if not include_unavailable:\n filters['available' = True)\n\n if not include_available:\n filters['available' = False)\n\n if channel_id:\n filters['alert_channel' = channel_id)\n\n return functools.partial(QuerySet.filter, **filters)\n\ndef build_list_message(user: SlackUser,\n *,\n django_filter: Callable[[QuerySet], QuerySet] = lambda qs: qs,\n include_web_pages: bool = True,\n include_async_tasks: bool = True)\n -&gt; Iterable[Union[Page, AsyncTask]]:\n pages = django_filter(\n Page.objects.all() if include_web_pages else Page.objects.none()\n )\n tasks = django_filter(\n AsyncTask.objects.all() if include_async_tasks else AsyncTask.objects.none()\n )\n\n return itertools.chain(pages, async_tasks)\n\n</code></pre>\n\n<h1>Where does that leave us?</h1>\n\n<ul>\n<li>There are some situational details you'll have to decide for yourself, like whether <code>map(_build_UI_message_item,...)</code> goes inside <code>build_list_message</code>.</li>\n<li><code>django_filters()</code> could maybe be made easier to read somehow.</li>\n<li>Obviously I've introduced the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"noreferrer\">itertools</a>, <a href=\"https://docs.python.org/3/library/functools.html\" rel=\"noreferrer\">functools</a>, and <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">typing</a> libraries. They're part of the standard package, so hopefully that's ok.</li>\n<li>Is stuff testable?\n\n<ul>\n<li><code>_build_filters()</code> is pure and easy to test, if you feel it's necessary.</li>\n<li><code>_build_UI_message_item()</code> is pure and easy to test.</li>\n<li><code>old_build_list_message()</code>, <em>if</em> any such method is still needed, is a thin wrapper for the deeper methods. Give it its own type-signature, and you can probably get away without writing unit tests for it.</li>\n<li><code>django_filters()</code> is pure. It's not super easy to test, but if your test suite has a supply of QuerySet objects then you should be ok.</li>\n<li><code>build_list_message()</code> <strong>is impure!</strong> We've consolidated all our impure code down, almost to a one-liner. In order to have tests for it we'll need to have some kind of test database, or some other way of spoofing the Django Manager classes. That's probably do-able. </li>\n</ul></li>\n<li>Speaking of test: I haven't tested any of this, so it probably doesn't work as written.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-09T21:37:57.657", "Id": "227742", "ParentId": "211173", "Score": "6" } } ]
{ "AcceptedAnswerId": "227730", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:20:24.180", "Id": "211173", "Score": "14", "Tags": [ "python", "unit-testing", "django" ], "Title": "Building Slack message" }
211173
<p>Pretty straight forwards really...I know that it's usually bad practice to repeat your code so I'm wondering how I could join handleAuthorChange() and handleContentChange() into one method. I guess it was hard for me to find a solution because I don't understand how I would know which part of the state I'm updating. I was thinking maybe embed a HTML id and check on the event target if IDs match but that seems pretty inefficient. Thanks in advance!</p> <pre><code>import React, { Component } from 'react'; class AddComment extends Component { state = { author: '', content: '' } handleAuthorChange = (e) =&gt; { this.setState({ author: e.target.value }); } handleContentChange = (e) =&gt; { this.setState({ content: e.target.value }); } handleSubmit = (e) =&gt; { e.preventDefault(); this.props.addComment(this.state); this.setState({ author: '', content: '' }); } render() { return ( &lt;div className="add-form"&gt; &lt;form onSubmit={ this.handleSubmit } className="card hoverable p-bottom"&gt; &lt;p className="p-top"&gt;ADD COMMENT&lt;/p&gt; &lt;input onChange={ this.handleContentChange } value={this.state.content} type="text" placeholder="comment" /&gt; &lt;input id="name" onChange={ this.handleAuthorChange } value={this.state.author} type="text" placeholder="name" /&gt; &lt;input value="submit" type="submit"/&gt; &lt;/form&gt; &lt;/div&gt; ) } } export default AddComment; </code></pre>
[]
[ { "body": "<p>I find it fine as it is, but if you really want to keep a single method, you can parametrize it by the name of the key to set:</p>\n\n<pre><code>handleChange = (keyName, e) =&gt; { this.setState({ [keyName]: e.target.value }); }\n</code></pre>\n\n<p>and call it like <code>handleChange('content', event)</code> or <code>handleChange('author', event)</code>.</p>\n\n<p>Problem is, now, to call it properly when creating your components. You could write things like:</p>\n\n<pre><code>&lt;input onChange={(e) =&gt; this.handleChange('content', e)} value={this.state.content} type=\"text\" placeholder=\"comment\" /&gt;\n</code></pre>\n\n<p>But this syntax creates a new function each time the component is rendered, potentially triggering child re-render as well. <a href=\"https://reactjs.org/docs/handling-events.html\" rel=\"nofollow noreferrer\">React recommends</a> to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>bind</code></a> functions in the constructor instead:</p>\n\n<pre><code>import React, { Component } from 'react';\n\nclass AddComment extends Component {\n constructor(props) {\n super(props);\n this.state = { author: '', content: '' };\n this.handleAuthorChange = this.handleChange.bind(this, 'author');\n this.handleContentChange = this.handleChange.bind(this, 'content');\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleChange(keyName, e) {\n this.setState({ [keyName]: e.target.value });\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.addComment(this.state);\n this.setState({ author: '', content: '' });\n }\n\n render() {\n return (\n &lt;div className=\"add-form\"&gt;\n &lt;form onSubmit={this.handleSubmit} className=\"card hoverable p-bottom\"&gt;\n &lt;p className=\"p-top\"&gt;ADD COMMENT&lt;/p&gt;\n &lt;input onChange={this.handleContentChange} value={this.state.content} type=\"text\" placeholder=\"comment\" /&gt;\n &lt;input id=\"name\" onChange={this.handleAuthorChange} value={this.state.author} type=\"text\" placeholder=\"name\" /&gt;\n &lt;input value=\"submit\" type=\"submit\"/&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n );\n }\n};\n\nexport default AddComment;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:35:14.157", "Id": "408452", "Score": "0", "body": "Awesome thanks! I didn't know about the bind() method - good to know!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:51:23.473", "Id": "408455", "Score": "0", "body": "Also, In my example, if I were to keep it how it is...should I be using a constructor function and using 'super(props)'??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:57:44.120", "Id": "408457", "Score": "1", "body": "@user3158670 since the arrow methods automatically binding `this` are still considered experimental, I prefer to explicitly `bind` my methods, thus I need a constructor. But your original code is clear enough without it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:47:29.710", "Id": "211189", "ParentId": "211175", "Score": "2" } } ]
{ "AcceptedAnswerId": "211189", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:24:50.387", "Id": "211175", "Score": "3", "Tags": [ "html", "react.js", "jsx" ], "Title": "How to set state of multiple properties in one event handler (React)" }
211175
<p>I'm currently working on a complete overhaul of the CSS of our flagship product with a goal of maintainability and simplification. During the testing, my coworkers and I have found that a lot of pages aren't exactly coping well with extremely long user-defined values, leading to things like long scrollbars, buttons being pushed outside the visible area, text escaping the boundaries of labels,...</p> <p>In order to quickly enter data like this in an input, I've written a bookmarklet that automatically fills the focused element with w-padded numbers, incrementing by 10, up to the maxLength defined on the element. I chose the letter w because it's the widest letter in the English alphabet, so a value that for up to 80% consists of the letter w should be close to the worst-case scenario for display issues.</p> <p>The bookmarklet is as follows:</p> <pre><code>javascript:(function(){var focused=document.activeElement; if(focused&amp;&amp;focused.maxLength){ var focusedMaxLength=focused.maxLength,focusedText="",i=10; for(;focusedMaxLength&gt;=i;i+=10){ focusedText+=("wwwwwwwwwww"+i).slice(-10); } focused.value=focusedText.slice(0,focusedMaxLength); }})() </code></pre> <p>Version with whitespace:</p> <pre><code>javascript:(function(){ var focused=document.activeElement; if(focused&amp;&amp;focused.maxLength){ var focusedMaxLength=focused.maxLength,focusedText="",i=10; for(;focusedMaxLength&gt;=i;i+=10){ focusedText+=("wwwwwwwwwww"+i).slice(-10); } focused.value=focusedText.slice(0,focusedMaxLength); } })() </code></pre> <p>An example of the string this generates: wwwwwwww10wwwwwwww20wwwwwwww30wwwwwwww40wwwwwwww50 in a field that's 50 characters long.</p> <p>Any remarks on how this bookmarklet could be optimized or potential issues that could arise from using this bookmark are appreciated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:45:39.600", "Id": "211180", "Score": "2", "Tags": [ "javascript", "bookmarklet" ], "Title": "Bookmarklet to quickly fill an input with a maximum width string for visual testing purposes" }
211180
<p>This is a very specific question mixing up stochastic knowledge and VBA skills. So very exciting!</p> <p>I'm trying to compare several methods for generating standard, normally distributed numbers given a source of uniformly distributed random numbers. Therefore I'm implementing the <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform" rel="nofollow noreferrer">Box Muller Algorithm</a>, <a href="http://cis.poly.edu/~mleung/CS909/s04/Ziggurat.pdf" rel="nofollow noreferrer">Ziggurat Algorithm</a> and <a href="http://www2.econ.osaka-u.ac.jp/~tanizaki/class/2013/econome3/13.pdf" rel="nofollow noreferrer">Ratio of Uniforms Algorithm</a>. Every single implementation works great in terms of generating a clean standard, normally distribution. (checked by <a href="https://en.wikipedia.org/wiki/Shapiro%E2%80%93Wilk_test" rel="nofollow noreferrer">Shapiro-Wilk-Test</a>).</p> <p>What I want to find out: <strong>which is the quickest method</strong>?</p> <p>Testing every single program with a total of 10^7 generated numbers these are the run times:</p> <p><strong>Box-Muller: 3,7 seconds<br> Ziggurat: 1,28 seconds<br> Ratio of Uniforms: 10,77 seconds</strong></p> <p>Actually I am very happy about those readings, because I didn't expect it to be that fast. Of course the run time of every single method also depends on my programming skills and VBA knowledge. </p> <p><strong>My problem</strong>: after doing some research I found out that the Ratio of Uniforms Algorithm should be the quickest (about 3 to 4 times quicker than Box Muller). This information just leans on this <a href="https://stackoverflow.com/questions/7183229/what-is-the-fastest-method-of-sampling-random-values-from-a-gaussian-distributio">stack</a>:</p> <p><a href="https://i.stack.imgur.com/Bk2GH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bk2GH.png" alt="enter image description here"></a></p> <p>I am curious <strong>if this is just a wrong claim</strong> of this user or (what I do expect more) <strong>if my code is not perfectly implemented</strong>. Therefore I'll post my code and hope someone could help me with my question, if my code is just not good enough or if the Ratio of Uniforms just doesn't work that quick as mentioned.</p> <pre><code>Sub RatioUniforms() Dim x(10000000) As Double Dim passing As Long Dim amount As Long: amount = 10000000 Dim u1 As Double Dim u2 As Double Dim v2 As Double Do While passing &lt;= amount Do u1 = Rnd 'rnd= random number(0,1) Loop Until u1 &lt;&gt; 0 'u1 musn't become 0 v2 = Rnd u2 = (2 * v2 - 1) * (2 * exp(-1)) ^ (1 / 2) If u1 ^ 2 &lt;= exp(-1 / 2 * u2 ^ 2 / u1 ^ 2) Then x(passing) = u2 / u1 passing = passing + 1 End If Loop End Sub </code></pre> <p>Thank you very much helping me on this topic. Maybe some of you have tried those algorithms in VBA or other languages and can help me with there experience about the run time? If you need something else to know about my other implementations just let me know. Have a great day!</p>
[]
[ { "body": "<p>There are a few optimizations that can be made to the code to speed it up, mainly to do with how some mathematical operations are performed in VBA. Not sure if I have it implemented 100% accurately so please review for accuracy. Also, I'm sure there are more optimizations to be had, but this is hopefully a starting point for further conversation. </p>\n\n<p>A lot of my changes may be PC specific. It may ultimately depend on your CPU and instruction set available. On my computer, this runs in about 2.5 seconds.</p>\n\n<p>A list of changes:</p>\n\n<ol>\n<li>I replaced all instances of raising something to a power of two, instead, I just multiplied the item by itself.</li>\n<li>I pre-computed this part <code>Sqr((2 * Exp(-1)))</code> as it appears to always be the same, so it isn't calculated for each loop and put it into a constant.</li>\n<li>I removed the variable <code>v2</code>, it wasn't really needed, you just needed to introduce <code>Rnd</code> in one more spot</li>\n<li>General cleanup of the code, and renamed a few variables for clarity</li>\n</ol>\n\n<p><strong>Code</strong></p>\n\n<pre><code>Sub RatioUniforms()\n Const NumberOfIterations As Long = 10000000\n Const u2CalculationSecondHalf As Double = 0.857763884960707 'Caching this part Sqr((2 * Exp(-1)))\n Dim Results(NumberOfIterations) As Double\n Dim PassCounter As Long\n Dim u1 As Double 'Define a better name if possible\n Dim u2 As Double 'Define a better name if possible\n Dim MyTimer As Double\n\n MyTimer = Timer\n Do While PassCounter &lt;= NumberOfIterations\n Do: u1 = Rnd: Loop Until u1 &gt; 0\n u2 = (2 * Rnd - 1) * u2CalculationSecondHalf\n\n If u1 * u1 &lt;= Exp(-1 / 2 * (u2 * u2) / (u1 * u1)) Then\n Results(PassCounter) = u2 / u1\n PassCounter = PassCounter + 1\n End If\n\n Loop\n Debug.Print \"Process took: \" &amp; Timer - MyTimer\n\n End Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:08:54.023", "Id": "408360", "Score": "0", "body": "Thank you very much for your adviece! Now it runs also 3,5 seconds. Stil comparing to Box Muller it is not 3x faster... Do you know about this topic? Is Ratio of Uniforms really that much faster?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:11:13.113", "Id": "408361", "Score": "0", "body": "@J.schmidt. Probably theoretically, but it very much depends on the implementation. I've updated my answer slightly, got it improved to about 2.5 seconds. If you are looking for pure speed, VBA probably not the right tool for the job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:08:46.370", "Id": "408376", "Score": "0", "body": "What else did you change to improve it to 2,5 seconds? I'm aware that in terms of run time VBA is not the best too. Stil, my task is to see which algorithm is the fastest using VBA." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:09:43.930", "Id": "408378", "Score": "2", "body": "I cached this calculation `Sqr((2 * Exp(-1)))` as it appears to be deterministic and put that into a Constant Variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T16:44:38.960", "Id": "408400", "Score": "0", "body": "The only idea I had, was to simplify the test `u1 * u1 <= Exp(-1 / 2 * (u2 * u2) / (u1 * u1))`. It doesn't match ~30% of time, so there are quite a bit of wasted cycles here. Not comfortable enough to know how to simplify this test. The one thing that stuck out, is u1*u1 is on both sides. If there was a way to simplify this expression, it might run even faster. I thought something like `Exp(-1 / 2 * (u2 * u2) / (u1 * u1)) / u1 * u1 <= 1` would work, but not qualified to say for sure" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T13:43:51.010", "Id": "211191", "ParentId": "211186", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:19:06.610", "Id": "211186", "Score": "3", "Tags": [ "algorithm", "vba", "excel" ], "Title": "Excel VBA: Implementing Box Muller, Zigurrat and Ratio of Uniforms Algorithm" }
211186
<p>I have implemented Dijkstra algorithm to perform Shortest Path problem.</p> <h3>Input:</h3> <p>Adjacency List(Directed Graph): Description is like that</p> <p><strong>{Source Node, {edge_1, .. , edge_N}}</strong></p> <p>Cost Matrix (Same format as Adjacency List)</p> <p>Queue: Priority Queue</p> <p>Input to &quot;Shortest Path&quot; method are Start Node, End Node; it returns -1 if there is no path from Source Node to Target Node, else it returns the cost of the minimum path selected.</p> <h1>Code:</h1> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;limits&gt; #include &lt;queue&gt; #include &lt;tuple&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; namespace { constexpr int ZERO_DISTANCE_VALUE = 0; constexpr int INFINITY_VALUE = std::numeric_limits&lt;int&gt;::max(); } // namespace using NodeType = int; using CostType = int; using AdjacencyListType = std::vector&lt;std::vector&lt;NodeType&gt;&gt;; using DistanceVector = std::vector&lt;NodeType&gt;; using QueueType = std::queue&lt;NodeType&gt;; using CostEdgeVector = std::vector&lt;std::vector&lt;CostType&gt;&gt;; using CostNodeTuple = std::tuple&lt;NodeType, CostType&gt;; using DistanceMatrixType = std::vector&lt;CostType&gt;; class Graph { public: explicit Graph(const AdjacencyListType &amp;input_list, const CostEdgeVector &amp;input_cost_list) : adjancecy_list(input_list), cost_list(input_cost_list) {} struct QueueComparator { bool operator()(const CostNodeTuple &amp;left, const CostNodeTuple &amp;right) { return std::get&lt;1&gt;(left) &lt; std::get&lt;1&gt;(right); } }; int shortest_path(const int &amp;source, const int &amp;target) { int result = 0; if (source == target) return result; if (!is_valid_node(source)) return -1; std::vector&lt;int&gt; distance_node(adjancecy_list.size(), INFINITY_VALUE); distance_node[source] = 0; queue.emplace(std::make_tuple(source, 0)); while (!queue.empty()) { const auto &amp;current_node = queue.top(); queue.pop(); const NodeType &amp;current_node_index = std::get&lt;0&gt;(current_node); const auto &amp;sub_node_vector = adjancecy_list.at(current_node_index); const auto &amp;sub_node_cost = cost_list.at(current_node_index); const int &amp;current_distance_cost = distance_node.at(current_node_index); for (NodeType index = 0; index &lt; sub_node_vector.size(); ++index) { const auto &amp;child_index = sub_node_vector.at(index); const int relaxation_value = current_distance_cost + sub_node_cost.at(index); if ((distance_node.at(child_index) &gt; relaxation_value)) { distance_node[child_index] = relaxation_value; queue.emplace(std::make_tuple(child_index, relaxation_value)); } } } try { const auto &amp;target_distance = distance_node.at(target); result = target_distance == INFINITY_VALUE ? -1 : target_distance; } catch (...) { result = -1; } return result; } private: bool is_valid_node(const NodeType &amp;node) { return node &lt; adjancecy_list.size(); } std::priority_queue&lt;std::tuple&lt;NodeType, int&gt;, std::vector&lt;std::tuple&lt;NodeType, int&gt;&gt;, QueueComparator&gt; queue; const CostEdgeVector &amp;cost_list; const AdjacencyListType &amp;adjancecy_list; }; int main() { AdjacencyListType cost_vector; CostEdgeVector adjancecy_list; NodeType source_node = 0; NodeType target_node = 0; Graph graph(adjancecy_list, cost_vector); const auto result = graph.shortest_path(source_node, target_node); std::cout &lt;&lt; &quot;Shortest Path value: &quot; &lt;&lt; result &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<p>First: Why use a class?</p>\n\n<pre><code>Graph graph(adjancecy_list, cost_vector);\nconst auto result = graph.shortest_path(source_node, target_node);\n</code></pre>\n\n<p>This could easily be refactored to a simple function call of:</p>\n\n<pre><code>const auto result = shortest_path(adjancency_list, cost_vector, source_node, target_node);\n</code></pre>\n\n<p>Since all <code>shortest_path</code> does is access the classes <code>adjancency_list</code> and <code>cost_vector</code>, which can just be passed in, <code>queue</code>, which should just be a local variable, and <code>is_valid_node</code>, which could just be inlined as you only called it once.</p>\n\n<p>Where you have used the class, there are some minor mistakes. In your constructor, you have initialised <code>adjancecy_list</code> and then <code>cost_list</code>. This should be the other way around (Or you should swap the members). The constructor is also explicit for no reason.</p>\n\n<pre><code>class Graph {\npublic:\n Graph(const AdjacencyListType &amp;input_list,\n const CostEdgeVector &amp;input_cost_list)\n : adjancecy_list(input_list), cost_list(input_cost_list) {}\n // ...\nprivate:\n // The other way around\n const AdjacencyListType &amp;adjancecy_list;\n const CostEdgeVector &amp;cost_list;\n}\n</code></pre>\n\n<hr>\n\n<pre><code> const auto &amp;current_node = queue.top();\n queue.pop();\n</code></pre>\n\n<p>Is undefined behaviour. You take the const reference of a node, and then you delete it with <code>pop</code>. <code>current_node</code> would then be garbage. Just take a copy:</p>\n\n<pre><code> const auto current_node = queue.top();\n queue.pop();\n</code></pre>\n\n<p>You should probably not use reference at all. The objects are all <code>int</code>s or <code>std::tuple&lt;int, int&gt;</code>s, which are very cheap to copy.</p>\n\n<hr>\n\n<p>This:</p>\n\n<pre><code> try {\n const auto &amp;target_distance = distance_node.at(target);\n result = target_distance == INFINITY_VALUE ? -1 : target_distance;\n } catch (...) {\n result = -1;\n }\n</code></pre>\n\n<p>Can be worded in a much clearer way. First, try to avoid <code>catch (...)</code> as much as possible. The only thing that would throw is <code>at</code>, which throws a <code>std::out_of_range</code>, so you can write <code>catch (const std::out_of_range&amp;)</code>. However, exceptions are very confusing here. It only throws if <code>target</code> is too big, so you can write something like:</p>\n\n<pre><code> if (target &gt;= distance_node.size()) {\n result = -1;\n } else {\n const auto target_distance = distance_node[size];\n result = target_distance == INFINITY_VALUE ? -1 : target_distance;\n }\n</code></pre>\n\n<p>Or even better, change <code>if (!is_valid_node(source)) return -1</code> to <code>if (!is_valid_node(source) || !is_valid_node(target)) return -1</code>, so that the target will always be in <code>distance_node</code>.</p>\n\n<p>And (this is personal preference) I would avoid the c-like pattern of declaring a result variable. Where you do <code>result =</code> at the end can be replaced with just <code>return</code>, and it's still very clear.</p>\n\n<hr>\n\n<p>If you are able to control your input, it would probably be easier to, instead of having two vectors which name the neighbour and have the cost of the edge, have a list of neighbours of pairs of nodes and costs. I would declare a helper struct:</p>\n\n<pre><code>struct edge {\n NodeType neighbour;\n CostType cost;\n};\n\n// or `using edge = std::pair&lt;NodeType, CostType&gt;;`, but that has less meaning\n</code></pre>\n\n<p>And have one vector of vector of these.</p>\n\n<p>Also, you use a <code>std::tuple&lt;int, int&gt;</code> for \"<code>CostNodeTuple</code>\". Since there are only 2 values, it might have been easier to use a <code>std::pair</code>, so <code>std::get&lt;0&gt;(t)</code> turns into <code>t.first</code>, and <code>std::get&lt;1&gt;(t)</code> turns into <code>t.second</code>.</p>\n\n<p>And if you swapped the order, you wouldn't need a custom comparator (As a tuple or pair's <code>operator&lt;</code> does mostly what you want)</p>\n\n<hr>\n\n<p>If you can do even more refactoring, I would consider using <code>unsigned</code> instead of <code>int</code>, as this doesn't work for negative edge weights (i.e. if there is a negative loop, it should have a value of -infinity). Instead of returning <code>-1</code> for failure, you could throw an error (if this is an exceptional circumstance) or returning a <code>std::optional&lt;unsigned&gt;</code> (if disjoint graphs are common). The current solution is fine as is though.</p>\n\n<p>Currently, using signed integers, there are a bunch of places where they are implicitly converted to unsigned integers (to use for array indices). It's not too much of a problem, but it shouldn't be the case (Maybe use <code>std::size_t</code> for <code>NodeType</code>?)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T13:53:13.967", "Id": "211193", "ParentId": "211190", "Score": "3" } }, { "body": "<ul>\n<li><p>spelling: <code>adjancecy_list</code></p></li>\n<li><p>The <code>Graph</code> class doesn't own the cost list or the adjacency list, or do anything graph-like. It should probably be called <code>PathFinder</code> or simply turned into a free function, e.g.:</p>\n\n<pre><code>ShortestPathSearchResult FindShortestPath(const AdjacencyListType&amp;, const CostEdgeVector&amp;, const NodeType&amp; source, const NodeType&amp; destination);\n</code></pre></li>\n<li><p><code>NodeType</code> is really an index so it should probably be <code>NodeIndex</code> instead, and be the same type as used for indexing the adjacency list and cost list (<code>std::size_t</code>).</p></li>\n<li><p><code>int</code> is used in several places where we should be using <code>NodeType</code> or <code>CostType</code> instead.</p></li>\n<li><p><strong>Bug:</strong> In the simple example given, both the adjacency and cost list are empty (i.e. there are no nodes). However, <code>shortest_path</code> returns <code>0</code> for the given target / source node index, instead of <code>-1</code>. This is because it checks for equality between the source and target nodes before checking that the nodes actually exist.</p></li>\n<li><p>It's better to throw an exception when given invalid input (nodes that don't exist). Currently there's no difference between invalid input (returns <code>-1</code>) and simply not being able to find a path.</p></li>\n<li><p>Don't use exceptions for flow control (the try catch block). We can simply check the target index is valid earlier in the function (as with the source index).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:14:04.110", "Id": "211194", "ParentId": "211190", "Score": "2" } } ]
{ "AcceptedAnswerId": "211194", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:48:41.043", "Id": "211190", "Score": "2", "Tags": [ "c++", "c++11", "graph" ], "Title": "Dijkstra - shortest Path implementation - STL" }
211190
<p>For an assignment, I had to draw a checkers board, with blue and red checkers, in python. What I have works, but I'm wondering if there's a more elegant and/or efficient way to accomplish this feat? Any and all suggestions are welcome!</p> <pre><code>import turtle def draw_box(t,x,y,size,fill_color): t.penup() t.goto(x,y) t.pendown() t.fillcolor(fill_color) t.begin_fill() for i in range(0,4): board.forward(size) board.right(90) t.end_fill() def draw_circle(t,x,y,radius,color): t.penup() t.goto(x,y) t.pendown() t.fillcolor(color) t.begin_fill() t.circle(radius) t.end_fill() def draw_chess_board(): square_color = "black" start_x = 0 start_y = 0 box_size = 30 for i in range(0,8): for j in range(0,8): draw_box(board, start_x + j * box_size, start_y + i * box_size, box_size, square_color) square_color = 'black' if square_color == 'white' else 'white' if square_color == 'black' and i &lt; 3: draw_circle(board, board.xcor() + (box_size / 2), board.ycor() - box_size, box_size / 2, "red") if square_color == 'black' and i &gt; 4: draw_circle(board, board.xcor() + (box_size / 2), board.ycor() - box_size, box_size / 2, "blue") square_color = 'black' if square_color == 'white' else 'white' board = turtle.Turtle() draw_chess_board() turtle.done() </code></pre>
[]
[ { "body": "<p>In essence, the code is well designed. You’ve split the code into simple, reusable functions and the logic is clear.</p>\n\n<p>But there are still improvements to be made:</p>\n\n<ul>\n<li>You relly on the global variable <code>board</code>, which is a bad habit to get into. Instead, pass it as parameter, even for your <code>draw_chess_board</code> function;</li>\n<li>The check for the <code>square_color == 'black'</code> feels really odd, prefer to check for <code>'white'</code> as it is how it will draw and <strong>then</strong> change the background color;</li>\n<li>Using strings to alternate between two states is unnecessarily verbose, prefer to use booleans that you convert to string at the right moment;</li>\n<li>I don't see any reason to define <code>start_x</code> and <code>start_y</code> and they doesn't contribute mathematically either, you can drop them;</li>\n<li>You could simplify some of your computation by storing intermediate constants into variables;</li>\n<li>You should avoid magic numbers by naming them.</li>\n</ul>\n\n<p>Proposed improvements:</p>\n\n<pre><code>import turtle\n\n\ndef draw_box(canvas, x, y, size, fill_color):\n canvas.penup()\n canvas.goto(x, y)\n canvas.pendown()\n canvas.fillcolor(fill_color)\n\n canvas.begin_fill()\n for i in range(4):\n canvas.forward(size)\n canvas.right(90)\n canvas.end_fill()\n\n\ndef draw_circle(canvas, x, y, radius, color):\n canvas.penup()\n canvas.goto(x, y)\n canvas.pendown()\n canvas.fillcolor(color)\n\n canvas.begin_fill()\n canvas.circle(radius)\n canvas.end_fill()\n\n\ndef draw_chess_board(canvas, box_size=30, board_size=8, pawn_lines=3):\n half_box_size = box_size / 2\n white_square = False\n for i in range(board_size):\n y = i * box_size\n for j in range(board_size):\n x = j * box_size\n draw_box(canvas, x, y, box_size, 'white' if white_square else 'black')\n if white_square and i &lt; pawn_lines:\n draw_circle(canvas, x + half_box_size, y - box_size, half_box_size, 'red')\n if white_square and i &gt;= board_size - pawn_lines:\n draw_circle(canvas, x + half_box_size, y - box_size, half_box_size, 'blue')\n white_square = not white_square\n white_square = not white_square\n\n\nif __name__ == '__main__':\n t = turtle.Turtle()\n draw_chess_board(t)\n t.hideturtle()\n turtle.done()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T15:33:42.210", "Id": "211201", "ParentId": "211195", "Score": "4" } } ]
{ "AcceptedAnswerId": "211201", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:21:29.057", "Id": "211195", "Score": "1", "Tags": [ "python", "homework", "turtle-graphics", "checkers-draughts" ], "Title": "Draw checker board" }
211195
<p>I wrote a simple circular queue. (in order to store characters because of the fact, that I am using UART through the DMA and sometimes my printf's override each other) I am looking for some review, though my testfile was successful I have the feeling I've overseen something and the queue might be buggy at some point. I appreciate any kind of critics, ideas or improvements</p> <p>Header File:</p> <pre><code>#ifndef __QUEUEH #define __QUEUEH typedef struct queue { unsigned int head; unsigned int tail; unsigned char* buf; unsigned int bufSize; unsigned int freeSpace; unsigned int occuSpace; unsigned char initialized; } queue_t; extern int queue_init(queue_t* q, unsigned char* buf, unsigned int bufSize); extern int enqueue(queue_t* q, unsigned char* element, unsigned int size); extern int dequeue(queue_t* q, unsigned char* str, int strMaxSize); // change to static extern int printQueue(queue_t* q); #endif </code></pre> <p>C-File:</p> <pre><code>#include "queue.h" #if !defined bool typedef unsigned char bool; #endif extern int queue_init(queue_t* q, unsigned char* buf, unsigned int bufSize) { q-&gt;head = -1; q-&gt;tail = 0; q-&gt;buf = buf; q-&gt;bufSize = bufSize; q-&gt;freeSpace = bufSize; q-&gt;occuSpace = 0; q-&gt;initialized = 1; return 0; } static inline bool moveTail(queue_t* q) { q-&gt;occuSpace = q-&gt;occuSpace - 2 - (q-&gt;buf)[q-&gt;tail]; q-&gt;freeSpace = q-&gt;freeSpace + 2 + (q-&gt;buf)[q-&gt;tail]; q-&gt;tail = (q-&gt;tail + (q-&gt;buf)[q-&gt;tail]+2) % (q-&gt;bufSize); return 0; } static inline bool enoughSpaceAvailable(queue_t* q, unsigned int size) { if(q-&gt;freeSpace &lt; size+2) return 0; return 1; } extern int enqueue(queue_t* q, unsigned char* element, unsigned int size) { if(size==0) return -5; else if(size&gt;q-&gt;bufSize-2) return -8; while(!enoughSpaceAvailable(q,size)) moveTail(q); q-&gt;occuSpace = q-&gt;occuSpace + 2 + size; q-&gt;freeSpace = q-&gt;freeSpace - 2 - size; q-&gt;head = (q-&gt;head+1)%(q-&gt;bufSize); (q-&gt;buf)[q-&gt;head] = size; for(int i = 0; i&lt;size; i++) { q-&gt;head = (q-&gt;head+1)%(q-&gt;bufSize); (q-&gt;buf)[q-&gt;head] = element[i]; } q-&gt;head = (q-&gt;head+1)%(q-&gt;bufSize); (q-&gt;buf)[q-&gt;head] = size; return 0; } extern int dequeue(queue_t* q, unsigned char* str, int strMaxSize) { int len = q-&gt;buf[q-&gt;tail]; if(q-&gt;freeSpace == q-&gt;bufSize) return -6; else if(strMaxSize&lt;len) return -7; for(int j=0; j&lt;len; j++) { str[j] = q-&gt;buf[(q-&gt;tail+1+j)%(q-&gt;bufSize)]; } moveTail(q); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:42:54.037", "Id": "408412", "Score": "0", "body": "Please explain the comment \"change to static\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:27:18.803", "Id": "408450", "Score": "0", "body": "I put it there to indicate, that the print function wasnt meant to be an extern function" } ]
[ { "body": "<h3>Redundant bytes</h3>\n<p>What's confusing about your implementation is that you are using two extra bytes for each element enqueued, but those bytes are redundant. You are adding a <code>size</code> byte both before and after each element, but only the &quot;before&quot; byte is ever used. You should remove the &quot;after&quot; byte because it serves no purpose.</p>\n<h3>Size byte is not large enough</h3>\n<p>You only reserve room for a single byte to indicate the size of the element. However, your <code>enqueue()</code> function takes <code>unsigned int size</code> as its argument. Therefore, if <code>size</code> is greater than 255, your program will encode the incorrect value in the size byte and things will fail after that. Either you should leave room for <code>sizeof(unsigned int)</code> bytes to encode the size, or you should limit the <code>size</code> argument to an <code>unsigned char</code> if you expect to only enqueue data smaller than 256 bytes.</p>\n<h3>Miscellaneous</h3>\n<ul>\n<li><p>The field <code>occuSpace</code> is set but never used. You should remove that field, because you can always compute the value as <code>bufSize - freeSpace</code> anyways.</p>\n</li>\n<li><p>The field <code>initialized</code> is set but never used. It should either be removed, or you should check it in all your functions and return an error if the queue is not initialized.</p>\n</li>\n<li><p>Instead of returning <code>-5</code>, <code>-8</code>, and <code>-7</code> as error codes, you should define some error codes in your header and return them instead of hardcoded numbers.</p>\n</li>\n<li><p>Some functions such as <code>queue_init()</code> and <code>moveTail()</code> can't fail and always return 0. You should either make those functions return <code>void</code> since they can't fail, or modify them to check for error conditions and possibly return an error code. For example, in <code>queue_init()</code>, you could check for these errors:</p>\n<ul>\n<li><code>q == NULL</code></li>\n<li><code>buf == NULL</code></li>\n<li><code>bufSize == 0</code></li>\n</ul>\n</li>\n<li><p>Instead of:</p>\n</li>\n</ul>\n<blockquote>\n<pre><code>#if !defined bool\ntypedef unsigned char bool;\n#endif\n</code></pre>\n</blockquote>\n<p>just do</p>\n<pre><code>#include &lt;stdbool.h&gt;\n</code></pre>\n<p>You should also use <code>false</code> and <code>true</code> instead of <code>0</code> and <code>1</code>, for the functions that return <code>bool</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T16:03:07.140", "Id": "408932", "Score": "0", "body": "In order to confirm:\nThe size byte after each element was useless.\nI added a second size byte at the beginning, so now I can add strings with the maximum length of two bytes.\nOccupied space was useless.\nAnd your other recommendations I implemented too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T20:29:41.657", "Id": "408973", "Score": "0", "body": "@OliverAl-Hassani yes that is all correct." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:43:46.523", "Id": "211231", "ParentId": "211198", "Score": "4" } }, { "body": "<p><strong>Functionality unclear</strong></p>\n\n<p>Post discusses \"... circular queue. (in order to store characters ...\". </p>\n\n<p>After digging deeply into code I now realize the goal is not to enqueue a character and then a character and so on. Instead the goal is to enqueue a group of characters, then another group and so on.</p>\n\n<p>This is not clear from the the post and importantly, it is <strong>not clear from the .h file</strong>.</p>\n\n<p><strong>Documentation</strong></p>\n\n<p>The .h file, as a public interface deserves as least a little documentation/comment per function.</p>\n\n<p><strong>Nonuniform name-space</strong></p>\n\n<p><code>__QUEUEH, queue, queue_init, enqueue, dequeue, printQueue</code> would benefit with a more common naming convention to clearly show that they belong together.</p>\n\n<p>Consider <code>QUEUE_H, queue, queue_init, queue_set, queue_get, queue_print</code></p>\n\n<p><strong><code>queue_t</code></strong></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Information_hiding\" rel=\"noreferrer\">Information hiding</a>: The members of <code>queue_t</code> do not need to be in the .h file. The below is sufficient. If external code needs to read any of these members, I recommend a function to do so.</p>\n\n<pre><code>typedef struct queue queue_t;\n</code></pre>\n\n<p>Put the full <code>struct queue</code> definition in the .c file.</p>\n\n<p><code>.initialized</code> is a good candidate for <code>bool</code>.</p>\n\n<pre><code>// unsigned char initialized;\nbool initialized;\n</code></pre>\n\n<p><strong>Unnecessary item in .h</strong></p>\n\n<p>As a <a href=\"https://codereview.stackexchange.com/questions/211198/circular-queue-in-c-for-an-embedded-project?noredirect=1#comment408450_211198\"><code>static</code></a> function, <code>printQueue</code> does not belong in the .h file. Remove it.</p>\n\n<hr>\n\n<p><strong>Avoid standard library collisions</strong></p>\n\n<p>The below conflicts with <code>bool</code> from <code>stdbool.h</code>. Do not re-invent the standard boolean type.</p>\n\n<pre><code>// #if !defined bool\n// typedef unsigned char bool;\n// #endif\n#include &lt;stdbool.h&gt;\n</code></pre>\n\n<p><strong><code>queue_init()</code></strong></p>\n\n<p>Why set <code>.head</code>, an unsigned type, to a negative value? Set to a unsigned value.</p>\n\n<pre><code>// q-&gt;head = -1;\nq-&gt;head = -1u;\n</code></pre>\n\n<p><strong><code>moveTail()</code></strong></p>\n\n<p>The role of magic number 2 is unclear here and in many of the functions. Explain the <code>2</code>.</p>\n\n<p><strong>Unexpected <code>strMaxSize</code></strong></p>\n\n<p>How does reading the data in the queue relate to the length of anything?</p>\n\n<pre><code>int len = q-&gt;buf[q-&gt;tail];\n</code></pre>\n\n<p>The role of <code>strMaxSize</code> in <code>dequeue()</code> is unclear.</p>\n\n<p><strong>Hmmmmm</strong></p>\n\n<p>After more review it <em>looks</em> like the first character in a group of characters is the group's length.</p>\n\n<p><strong><code>enoughSpaceAvailable()</code></strong></p>\n\n<p>Avoid overflow: <code>size+2</code> can overflow - this code has no control over the value of <code>size</code>. Consider a more robust test.</p>\n\n<pre><code>// if(q-&gt;freeSpace &lt; size+2) return 0;\n//return 1;\n\nreturn q-&gt;freeSpace &gt; size &amp;&amp; q-&gt;freeSpace - size &gt;= 2;\n</code></pre>\n\n<p><strong>const</strong></p>\n\n<p>Many functions would benefit with a <code>const queue_t *</code></p>\n\n<pre><code>// enoughSpaceAvailable(queue_t* q, unsigned int size)\nenoughSpaceAvailable(const queue_t* q, unsigned int size)\n</code></pre>\n\n<p><strong>3 to do the job of 2</strong></p>\n\n<p>Unclear why code uses <code>.bufSize, .freeSpace, .occuSpace</code> when only 2 are needed. I'd expect <code>.bufSize, .occuSpace</code> are sufficient here.</p>\n\n<hr>\n\n<p><strong>Overall</strong></p>\n\n<p>Code lacks documentation to indicate the overall coding goals. Without that, there is too much to discover.</p>\n\n<p>I still do not know how to use best these calls. Will <code>enqueue(q, \"\", 0);</code> cause havoc? How to test is the queue is empty? What are all the error codes? Why are errors negative? What does a positive response mean? </p>\n\n<p>To me, it is the un-posted testfile contains too much information there and not enough here.</p>\n\n<p>This code deserves an update and then a following review.</p>\n\n<hr>\n\n<p>Sample alternate <code>aqueue.h</code>.<br>\nI avoided \"queue\" as too generic and used \"aqueue\".</p>\n\n<pre><code>/*\n * aqueue: queue of groups of binary data\n */\n\n#ifndef AQUEUE_H\n#define AQUEUE_H\n\ntypedef struct aqueue aqueue_t;\n\n// All functions that return `int` return 0 on success.\n\n/*\n * Initialize the queue with the buffer to use and its size.\n * Size [4..UINT_MAX]\n * Return TBD with invalid parameter values.\n */\nint aqueue_init(aqueue_t* q, unsigned char* buf, unsigned bufSize);\n\n/*\n * Insert a copy of what `data` points to.\n * Return TBD with insufficient space\n */\nint queue_set(aqueue_t* q, const unsigned char* data, unsigned dataSize);\n\n/*\n * Extract entry from the queue.\n * Return TBD when attempted with empty queue.\n * Return TBD when dataSize is too small.\n */\nint aqueue_get(aqueue_t* q, unsigned char *data, unsigned dataSize);\n\n/*\n * Queue empty?\n */\n_Bool aqueue_empty(const aqueue_t* q);\n\n/*\n * Get data without removing from the queue (Peek)\n * Return TBD when attempted with empty queue.\n * Return TBD when dataSize is too small.\n */\nint aqueue_top(const aqueue_t* q, unsigned char* data, unsigned dataSize);\n\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T00:29:23.457", "Id": "408467", "Score": "2", "body": "The calling code likely needs to know the size of `queue_t` thwarting my `information hiding` suggestion. If so, leave the full declaration of `queue_t` in the.h file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T15:59:44.237", "Id": "408930", "Score": "0", "body": "You understood/interpreted the functionality of my queue correctly: The queue shall store strings, whereby the idea was to store before every string respectively its length. queue_enqueue(&q, (unsigned char*)\"\", 0) results into a caught error in the updated code. (enqueue returns then only the enum value QUEUE_PARAM_BUFFERSIZE_TOOSMALL). Queue_enqueue(&q, (unsigned char*)\"\", 1) worked fine, I think because \"\" is a temporary string which only contains the string terminal symbol '\\0'.\nI chose negative error codes arbitrarily (updated to enum)\nI will post the updated code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T16:02:13.957", "Id": "408931", "Score": "0", "body": "yes I had to leave the complete declaration of queue_t within the header file, otherwise it caused:\n\"Application/main.c:52:10: error: storage size of 'q' isn't known.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T16:39:11.890", "Id": "408934", "Score": "1", "body": "@Oliver Al-Hassani I see the need for `queue_t` within the header file as a design weakness. It implies that the unposted calling code (`main()`) is doing things it should not. A better `queue_...` would hide the inner details from the calling code. Think of `FILE` as in `fopen(), fgetc(), fprintf(), fclose()`. What do we know of its size, or members - very little. That is how your `queue_...` should be too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:14:35.420", "Id": "408942", "Score": "0", "body": "I did some research within my debian kernel files for the example FILE in fprintf. I found the definition of FILE in stdio.h: typedef struct _IO_FILE FILE;\nAnd __IO_FILE is from libio.h with its complete structure content, visible within the header file:\nstruct _IO_FILE { ... }.\nyou can also relate to: https://stackoverflow.com/questions/16424349/where-to-find-struct-io-file\nSo linux kernel code also has user structures visible in the header files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T23:11:15.407", "Id": "408984", "Score": "1", "body": "@OliverAl-Hassani The member of `FILE` though are not needed to use the standard `FILE` functions. There is no need for `FILE f`, just `FILE *f`. Any access to `FILE` members is a matter of performance (in-lining code) vs. a function call. Code as you like, yet I find abstracted helper code, like this `queue` could be, to have more long term value when coded and used in a manner that separates the members from the caller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T15:31:49.250", "Id": "409054", "Score": "0", "body": "I thought about it again, and as you say it would be possible to make the queue struct as described in the from the OP accepted answer from: https://stackoverflow.com/questions/2672015/hiding-members-in-a-c-struct. \nDespite, one would need to use either malloc, or one has to force the user again to create a buffer for the queue_t.\nFor me personally it's getting more complicated than pragmatic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T15:34:13.070", "Id": "409055", "Score": "0", "body": "(by the way I don't want to use malloc)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T17:56:37.210", "Id": "409072", "Score": "1", "body": "@OliverAl-Hassani Consider the trade-off of \"it's getting more complicated than pragmatic\". It is usually more valuable and pragmatic to minimize the complication of the calling code, even if that makes this `queue` code more complex. There are various ways to handle the difficultly in memory management, but in the end, the idea is to make it easy from the caller-point-of-view - regardless of which way you choose to manage memory. Perhaps knowing more why your application needs to avoid `malloc()` would help - yet that is getting beyond the scope of this answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T18:06:18.867", "Id": "409075", "Score": "0", "body": "@OliverAl-Hassani Example code where the caller, unknowing provides memory with a _compound literal_: [printf converter to print in binary format?](https://stackoverflow.com/a/34641674/2410359). In your case code can use `queue *q = &(unsigned char [queue_n()]){ 0}`, perhaps wrapped in a macro. Various approaches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-16T14:49:52.623", "Id": "409232", "Score": "0", "body": "until yesterday I wasn't aware, that arm-none-eabi-gcc provides a stdlib and further. I've just implemented a handler and encapsulated the queue_t and now it just looks beautiful!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:50:31.140", "Id": "411098", "Score": "1", "body": "Excellent review. Regarding the `bool` remark, the reason might be to allow C90 compatibility, as often required because of dusty old embedded system compilers. The correct way to do it would however rather be `#ifndef __STDC_VERSION__ typedef unsigned char bool; #define false 0 #define true 1 #else #include <stdbool.h> #endif`. But then of course this doesn't give true booleans. Given `bool b = 2;`, C90 fake boolean will get value 2, whereas standard C boolean will get value 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:52:11.387", "Id": "411121", "Score": "0", "body": "@Lundin True that a define test is warranted yet since `_Bool` came in with [C99](https://stackoverflow.com/a/1608350/2410359) and not C89, the test would need to be more than just testing `__STDC_VERSION__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:14:21.960", "Id": "411122", "Score": "0", "body": "Ah crap, you are right. `__STDC_VERSION__` was introduced in C95, not C90. Looking at my actual production code doing stuff like this, it goes: `#ifdef __STDC_VERSION__ #if (__STDC_VERSION__ >= 199901L) #include <stdint.h> #include <stdbool.h>` ... `#else /* manual typedefs */`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:45:06.077", "Id": "411132", "Score": "1", "body": "@Lundin [How to find my current compiler's standard](https://stackoverflow.com/a/4991754/2410359) is a good resource." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:45:22.033", "Id": "211232", "ParentId": "211198", "Score": "5" } } ]
{ "AcceptedAnswerId": "211231", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:51:32.160", "Id": "211198", "Score": "3", "Tags": [ "c", "queue", "circular-list", "embedded" ], "Title": "Circular Queue in C for an embedded project" }
211198
<p>The web-scraping process currently takes quite a bit of time, and I wonder if I can structure the code otherwise or improve it in any way.</p> <p>Code looks like this:</p> <pre><code>import numpy as np import pandas as pd import requests import json from sklearn import preprocessing from sklearn.preprocessing import OneHotEncoder results_2017 = [] results_2018 = [] for game_id in range(2017020001, 2017021271, 1): url = 'https://statsapi.web.nhl.com/api/v1/game/{}/boxscore'.format(game_id) r_2017 = requests.get(url) game_data_2017 = r_2017.json() for homeaway in ['home','away']: game_dict_2017 = game_data_2017.get('teams').get(homeaway).get('teamStats').get('teamSkaterStats') game_dict_2017['team'] = game_data_2017.get('teams').get(homeaway).get('team').get('name') game_dict_2017['homeaway'] = homeaway game_dict_2017['game_id'] = game_id results_2017.append(game_dict_2017) df_2017 = pd.DataFrame(results_2017) for game_id in range(2018020001, 2018020667, 1): url = 'https://statsapi.web.nhl.com/api/v1/game/{}/boxscore'.format(game_id) r_2018 = requests.get(url) game_data_2018 = r_2018.json() for homeaway in ['home','away']: game_dict_2018 = game_data_2018.get('teams').get(homeaway).get('teamStats').get('teamSkaterStats') game_dict_2018['team'] = game_data_2018.get('teams').get(homeaway).get('team').get('name') game_dict_2018['homeaway'] = homeaway game_dict_2018['game_id'] = game_id results_2018.append(game_dict_2018) df_2018 = pd.DataFrame(results_2018) df = df_2017.append(df_2018) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T18:42:46.060", "Id": "408422", "Score": "1", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." } ]
[ { "body": "<p>Assuming you have a multi-core processor, you can use the multiprocessing module to do your scraping in parallel. Here's a good article that explains how to use it: <a href=\"https://sebastianraschka.com/Articles/2014_multiprocessing.html\" rel=\"nofollow noreferrer\">An introduction to parallel programming using Python's multiprocessing module</a> (you only need to read the first half of the article)</p>\n\n<p>The simplest way to parallelize this would be to do your 2017 loop in a separate process from your 2018 loop. If you need it faster than that, you could further subdivide your 2017 and 2018 ranges. It also depends on how many cores you have. If you only have 2 cores, you won't benefit from dividing it into more than 2 processes (or 4 processes for 4 cores).</p>\n\n<p>Other than that I can't see anything in your code structure you could change to speed it up.</p>\n\n<p>Update: I'm not familiar with the API you're using, but if there's a way to make one API call that returns a list of games with their box scores instead of making a separate request for each game, that would be the best way to speed it up.</p>\n\n<p>Also, according to Mathias in the comments, <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map\" rel=\"nofollow noreferrer\">multiprocessing.Pool.map</a> would be particularly helpful in this case. I'm not familiar with it, but it does look like it would be convenient for this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T18:55:09.667", "Id": "408424", "Score": "0", "body": "Thank you for the article and the feedback, really helpful!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:03:09.313", "Id": "408446", "Score": "0", "body": "You could mention [`multiprocessing.Pool.map`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map) that is particularly helpful in this case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T18:51:11.207", "Id": "211214", "ParentId": "211212", "Score": "2" } } ]
{ "AcceptedAnswerId": "211214", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:31:45.727", "Id": "211212", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "iteration" ], "Title": "Web scraping JSON-data from API put into Dataframe" }
211212
<p>I wrote the following program for encrypting PDF Files for checking out the PyPDF2 module.</p> <p>It takes a path and a password via the command line or user input. Then all PDF files in the provided folder and subfolders get encrypted.</p> <p>edit: the counterpart to drcrypt can be found in <a href="https://codereview.stackexchange.com/questions/211281/decrypting-pdf-files">Decrypting PDF-Files</a></p> <p><strong>pdf_encrypter.py</strong></p> <pre><code>""" Takes a path and a password provided by the command line or if not available by the user input. Each .pdf file found in a folder and sub folder which is not encrypted gets encrypted. """ import os import sys from typing import Tuple import PyPDF2 def get_password_from_user() -&gt; str: """ Asks the user to enter a password """ while True: input_string: str = input("Enter Password:") if input_string: return input_string def get_path_from_user() -&gt; str: """Asks for a path from the User""" while True: input_string: str = input("Enter absolute Path:") input_list: list[str] = input_string.split("\\") path = os.path.join(*input_list) if os.path.exists(path): return path print("Path doesn't exist\n") def get_path_and_password() -&gt; Tuple[str, str]: """ Gets path and password from command line or if not available from the user """ if len(sys.argv) &gt; 2: return sys.argv[1], sys.argv[2] return get_path_from_user(), get_password_from_user() def is_encrypted(filename: str) -&gt; bool: """Checks if file is encrypted""" with open(filename, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) return pdf_reader.isEncrypted def encrypt(filename: str, password: str) -&gt; str: """ Encrypts a file and returns the filename of the encrypted file. Precondition: File is not encrypted """ with open(filename, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) pdf_writer = PyPDF2.PdfFileWriter() for page_number in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_number)) pdf_writer.encrypt(password) filename_encrypted = filename.rstrip('.pdf') + "_encrypted.pdf" with open(filename_encrypted, 'wb') as pdf_file_encrypted: pdf_writer.write(pdf_file_encrypted) return filename_encrypted def decrypt(filename: str, password: str) -&gt; bool: """ Try to decrypt a file. If not successful a false is returned. If the file passed is not encrypted also a false is passed """ with open(filename, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) if not pdf_reader.isEncrypted: return False return pdf_reader.decrypt(password) def pdf_encrypter(): """ Main routine If file was found which is not encrypted a new encrypted copy is created. Then the encrypted copy is decrypted temporary to test that the encryption works. If successful the original files get deleted. """ path, password = get_path_and_password() for folder_name, _, filenames in os.walk(path): for filename in filenames: if not filename.endswith('.pdf'): continue if is_encrypted(os.path.join(folder_name, filename)): continue filename_encrypted: str = encrypt( os.path.join(folder_name, filename), password) if decrypt(os.path.join( folder_name, filename_encrypted), password): print("remove" + filename) if __name__ == "__main__": pdf_encrypter() </code></pre> <p>I would like to hear suggestions on how to improve the program / make it easier to read etc... </p> <p>Is it easy to understand or to complicated?</p> <p>What can be solved more simple?</p> <p>Are there any bad habbits?</p> <p>Im not sure if the input for the path is good handled like this.</p> <p>I tested it under Windows.</p>
[]
[ { "body": "<p>This is pretty good for a beginner! I can see a few improvements but overall your code is </p>\n\n<ul>\n<li>Well structured into functions</li>\n<li>Has decent docstrings</li>\n<li>Makes use of the latest Python features (Typing)</li>\n</ul>\n\n<p>But there are still some improvements to be made, </p>\n\n<p>a common expression is Python comes with batteries included. I've spotted a few missed standard library modules making your life easier in the future.</p>\n\n<ol>\n<li><p>Use <code>argparse</code> over <code>sys.argv</code></p>\n\n<p><a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> is a very cool Python module making it easy to get input from the commandline</p></li>\n<li><p>Getting password via <code>input()</code> is a security risk</p>\n\n<p>There is another Python module made for this situation: <a href=\"https://docs.python.org/3/library/getpass.html\" rel=\"nofollow noreferrer\"><code>getpass</code></a></p></li>\n<li><p>The way you get the path is a ugly</p>\n\n<p>Luckily we can make use of yet another Python module <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a></p>\n\n<p>You can enter a path (with any kind of slashes) and it will automatically convert it to the operating systems path correct slashes</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:47:52.613", "Id": "408544", "Score": "1", "body": "Thanks for mention these modules. It looks like unlike c++ python has already many good utility libraries available by default." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T08:28:45.090", "Id": "211243", "ParentId": "211216", "Score": "3" } }, { "body": "<p>Putting the suggestions from Ludisposed together we can improve the code with <code>argparse</code>, <code>getpass</code> and <code>pathlib</code> like this:</p>\n\n<pre><code>def get_password_from_user() -&gt; str:\n \"\"\"\n Asks the user to enter a password\n \"\"\"\n while True:\n password: str = getpass(promt=\"Enter password: \")\n if password:\n return input_string\n\n\ndef get_path_from_user() -&gt; str:\n \"\"\"Asks for a path from the User\"\"\"\n while True:\n path = Path(input(\"Enter absolute Path:\"))\n\n if os.path.exists(path):\n return path\n print(\"Path doesn't exist\\n\")\n\n\ndef get_path_and_password() -&gt; Tuple[str, str]:\n \"\"\"\n Gets path and password from command line or\n if not available from the user\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--path\", help=\"provide root folder to look for PDFs to encrypt\",\n type=str)\n parser.add_argument(\n \"--password\", help=\"password to encrypt PDFs with\", type=str)\n args = parser.parse_args()\n if args.path and args.password:\n return Path(args.path), args.password\n return get_path_from_user(), get_password_from_user()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:45:53.027", "Id": "211279", "ParentId": "211216", "Score": "0" } } ]
{ "AcceptedAnswerId": "211243", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:09:12.497", "Id": "211216", "Score": "9", "Tags": [ "python", "beginner", "pdf" ], "Title": "Encrypt PDF-Files" }
211216
<p>I thought it might be useful if reading could at least sort of mirror writing. For example, if I write some output like:</p> <pre><code>somefile &lt;&lt; "foo: " &lt;&lt; foo &lt;&lt; ", bar: " &lt;&lt; bar; </code></pre> <p>...it would be nice if I could read it back in like:</p> <pre><code>somefile &gt;&gt; "foo: " &gt;&gt; foo &gt;&gt; ", bar: " &gt;&gt; bar; </code></pre> <p>So, this code attempts to support that:</p> <pre><code>#ifndef FMT_READ_H_ #define FMT_READ_H_ #include &lt;cctype&gt; #include &lt;iostream&gt; #include &lt;locale&gt; template &lt;class charT&gt; std::basic_istream&lt;charT&gt; &amp;operator&gt;&gt;(std::basic_istream&lt;charT&gt; &amp;is, charT const *fmt) { if (fmt == nullptr) return is; if (is.flags() &amp; std::ios_base::skipws) { std::locale const &amp;loc = is.getloc(); if (std::has_facet&lt;std::ctype&lt;charT&gt;&gt;(loc)) { auto const &amp;ct = std::use_facet&lt;std::ctype&lt;charT&gt;&gt;(loc); while (ct.is(std::ctype_base::blank, is.peek())) is.ignore(1); } else while (std::isspace(is.peek())) is.ignore(1); } while (*fmt) { if (*fmt != is.peek()) is.setstate(std::ios_base::failbit); ++fmt; is.ignore(1); } return is; } #endif </code></pre> <p>Here's a little bit of test code:</p> <pre><code>#include &lt;sstream&gt; #include &lt;iostream&gt; #include "fmt_read.hpp" int main() { std::istringstream b("START(0, 0)\nGOAL(1,2)"); int startX, startY; b &gt;&gt; "START(" &gt;&gt; startX &gt;&gt; "," &gt;&gt; startY &gt;&gt; ")"; std::cout &lt;&lt; "start_x: " &lt;&lt; startX &lt;&lt; ", start_y: " &lt;&lt; startY &lt;&lt; "\n"; int goalX, goalY; b &gt;&gt; "GOAL(" &gt;&gt; goalX &gt;&gt; "," &gt;&gt; goalY &gt;&gt; ")"; std::cout &lt;&lt; "goal_x: " &lt;&lt; goalX &lt;&lt; ", goal_y: " &lt;&lt; goalY &lt;&lt; "\n"; } </code></pre> <p>One big question in my mind is about what it does if it finds that the stream has been imbued with <code>locale</code> that doesn't contain a <code>ctype</code> facet. Right now, in that case it falls back to the global <code>locale</code>--but I'm wondering whether it might be better to treat that as an error instead (but even then, not sure if it should set the failbit, or maybe throw an exception, or...)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T22:16:22.280", "Id": "408694", "Score": "0", "body": "Seems to only ignore leading white space. If I had a format of \"Poo Paa\" don't you think the internal space should match multiple space on the input stream. This is how space works for the `scanf()` family of functions." } ]
[ { "body": "<p>You should use a <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/sentry\" rel=\"nofollow noreferrer\"><code>std::basic_istream&lt;CharT&gt;::sentry</code></a> to skip the whitespace.</p>\n\n<p>Also, <code>basic_istream</code> takes a second template parameter, which you could also implement.</p>\n\n<p>And you might want to rethink your design: Do you really want to skip whitespace?</p>\n\n<p>Three possible scenarios I can think of:</p>\n\n<ol>\n<li>Always skip white space if the <code>std::ios_base::skipws</code> bit is set</li>\n<li>Only skip white space if the <code>std::ios_base::skipws</code> bit is set and <code>fmt != nullptr</code></li>\n<li>Never skip white space (Be an <a href=\"https://en.cppreference.com/w/cpp/named_req/UnformattedInputFunction\" rel=\"nofollow noreferrer\"><em>UnformattedInputFunction</em></a>)</li>\n</ol>\n\n<p>Whatever the case, your code should look more like this:</p>\n\n<pre><code>template &lt;class CharT, class Traits&gt;\nstd::basic_istream&lt;CharT, Traits&gt; &amp;operator&gt;&gt;(std::basic_istream&lt;CharT, Traits&gt; &amp;is, CharT const *fmt) {\n typedef typename std::basic_istream&lt;CharT, Traits&gt;::sentry sentry_t;\n\n// Case 1: Always skip\n sentry_t s(is);\n\n if (fmt == nullptr)\n return is;\n\n// Case 2: Skip if there is a fmt\n\n if (fmt == nullptr)\n return is;\n\n sentry_t s(is);\n\n// Case 3: Never skip\n\n if (fmt == nullptr)\n return is;\n\n sentry_t s(is, false);\n\n// And also consider some edge cases: If EOF is reached, and we tried to read `\"\"`, should we set failbit?\n\n // Check the sentry before using the stream\n if (s) {\n while (*fmt) {\n // is.peek() returns Traits::int_type. Convert first before comparing.\n if (!Traits::eq_int_type(Traits::to_int_type(*fmt), is.peek()))\n is.setstate(std::ios_base::failbit); // Why don't you return here?\n ++fmt;\n // If an error occurred when ignoring the character, stop reading\n if (!is.ignore(1)) {\n return is;\n }\n }\n }\n return is;\n}\n</code></pre>\n\n<p>Also, currently your solution is very undefined. When overloading an operator, at least one of the parameters must be not-builtin and not-stl (What if someone else overloaded the same operator but completely unrelated to you?)</p>\n\n<p>A simple fix would be to make it a function instead.</p>\n\n<p>You can carry on with your solution (As there probably won't be a conflict) but I would suggest doing it like this:</p>\n\n<pre><code>namespace my_namespace {\n inline namespace operators {\n template &lt;class CharT, class Traits&gt;\n std::basic_istream&lt;CharT, Traits&gt; &amp;operator&gt;&gt;(std::basic_istream&lt;CharT, Traits&gt; &amp;is, CharT const *fmt) {\n // ...\n }\n }\n}\n\n// And explicitly \"enable\" it in functions by using it\nint main() {\n // one of:\n using namespace my_namespace;\n using namespace my_namespace::operators;\n using my_namespace::operator&gt;&gt;;\n using my_namespace::operators::operator&gt;&gt;;\n\n // And do this in every function you use this.\n // Note that this is still UB but less likely\n // to be unable to compile.\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T17:25:41.980", "Id": "408534", "Score": "0", "body": "It would be even better to create a small struct in that namespace, so ADL could slam in." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T21:40:05.607", "Id": "211224", "ParentId": "211217", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:47:43.450", "Id": "211217", "Score": "4", "Tags": [ "c++", "io", "stream" ], "Title": "Formatted reading" }
211217
<p>Fairly new to writing tests. I hoping to get feedback about test writing. I am curious to know if there is a convention/standard for short is better or more informative is better?</p> <p>A) expect(mqError).to.not.be.null;</p> <p>B) expect(mqError).to.be.an.instanceof(MonqadeError);</p> <p>C) expect(mqError.code).to.eq('MongooseValidationError'); </p> <p>C will be precluded B which will precluded by A. In simple English. Is it better to determine a test failed.. or to determine where/why a test failed. Thoughts?</p> <pre><code>const doSomethingWithPromise = ()=&gt; { return new Promise((resolve,reject)=&gt;{ this.getMongooseModelClass().findById(_ID,(error,doc)=&gt;{ if(error){ return reject(new MonqadeError('MongooseError','Mongoose/MongoDB threw error model.find' , error) ); } if(!doc){ return reject( new MonqadeError("NoMatchingDocumentFound","No Records Found",undefined) ) ; } return resolve(new MonqadeResponse([JSON.parse(JSON.stringify(doc))])); // monqade always returns Array .. Return Array will be an issue of }); } } </code></pre> <p>Given A)</p> <pre><code>doSomethingWithPromise({}) .then(mqResponse=&gt;{ //MonqadeResponse expect(mqResponse).to.be.null; done(); }).catch(mqError=&gt;{ //MonqadeError expect(mqError).to.not.be.null; expect(mqError).to.be.an.instanceof(MonqadeError); expect(mqError.code).to.eq('MongooseValidationError'); done() }) </code></pre> <p>Or B)</p> <pre><code>.catch(mqError=&gt;{ //MonqadeError expect(mqError.code).to.eq('MongooseValidationError'); done() }) </code></pre> <p>Where the expects in A overlap but will catch where the failure occurs.</p>
[]
[ { "body": "<p>Turns out best practice is fewer tests. Write a test for the specific test case. This way when tests fail the cause is obvious. </p>\n\n<p>B) above would be the bast practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:55:01.207", "Id": "211220", "ParentId": "211219", "Score": "-1" } } ]
{ "AcceptedAnswerId": "211220", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T19:53:19.683", "Id": "211219", "Score": "-2", "Tags": [ "mocha" ], "Title": "Mocha with overlapping tests" }
211219
<p>For an assignment, I had to loop through a text file, and report any positions that a user entered sequence was found. Is there any way I can make this code more efficient, because it seems like I'm writing a lot of nested loops, which I've learned can be dangerous/complicated. Any and all help is appreciated!</p> <pre><code>import os #OperatingSystem import sys #System import re #Regex (Regular Expressions) def checkSequenceCharacters(seq): for c in seq: if c != 'A' and c != 'G' and c != 'T' and c != 'C': print("[!] ERROR: Not a valid sequence (A/G/T/C ONLY)") sys.exit(0) def checkSequenceLength(seq): if len(seq) != 5: print("[!] ERROR: Has to be exactally 5 letters long!") sys.exit(0) seq = raw_input("Enter a 5 basepair sequence using only A,G,T,C: \n") checkSequenceCharacters(seq) checkSequenceLength(seq) input_file_path = os.getenv("HOME") + "/Desktop/sequencer/inputfile.txt" output_file_path = os.getenv("HOME") + "/Desktop/sequencer/output/" + seq + ".txt" try: input_file = open(input_file_path) output_file = open(output_file_path, 'w') count = 0 line_location = 0 lines = [] for line in input_file: line_location = line_location + 1 arr = re.findall(seq,line) if arr: x = arr[0] if x == seq: count = count + 1 lines.append(line) print("[+] Sequence found at line " + str(line_location)) output_file.write("Line " + str(line_location) + ": " + line + "\n") if count != 0: print("[*] Matches: " + str(count)) print("[*] FILE CREATED AT: " + output_file_path) else: print("[!] ERROR: No matches found!") finally: input_file.close() output_file.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:57:29.070", "Id": "408464", "Score": "0", "body": "Any chance that a sequence may cross a line boundary?" } ]
[ { "body": "<p><strong>TL;DR:</strong> See end of answer for updated code with suggested improvements</p>\n\n<p>While I don't have many suggestions regarding nested for-loops, as you only seem to have two of them, I do have a few other suggestions:</p>\n\n<h1>Suggestions</h1>\n\n<h3>1. Use <code>with</code> for file opening</h3>\n\n<p>You use try/finally to open/close your files, and while you're absolutely right to close your files, Python's <code>with</code> statement takes care of this for you. Another lesser-known characteristic of the <code>with</code> statement is that <a href=\"https://docs.python.org/3/reference/compound_stmts.html#the-with-statement\" rel=\"nofollow noreferrer\">you can \"nest\" them in a single line</a>, which is useful in your case. </p>\n\n<p>So, I would recommend updating</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try:\n input_file = open(input_file_path)\n output_file = open(output_file_path, 'w')\n ... # Do stuff\nfinally:\n input_file.close()\n output_file.close()\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(input_file_path) as input_file, open(output_file_path, \"w\") as output_file:\n ... # Do stuff\n</code></pre>\n\n<p>When the context of the <code>with</code> statement is exited, your opened files will automatically be closed.</p>\n\n<h3>2. Clean up variable naming</h3>\n\n<p>Python convention is to use lower snake-case for normal variable names and function names - Camel-case (upper) is <em>usually</em> only used for class definitions. Therefore, I would recommend renaming your <code>checkSequenceCharacters</code> and <code>checkSequenceLength</code> functions to <code>check_sequence_characters</code> and <code>check_sequence_length</code>, respectively. This might be considered nitpicking, but maintaining consistent naming conventions always makes things easier for me.</p>\n\n<h3>3. Use str <code>in</code> str, instead of checking individual equality</h3>\n\n<p>In <code>check_sequence_characters</code>, you can more easily ensure that each character in <code>seq</code> is in an allowed set of characters using the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if any(c not in \"AGTC\" for c in seq):\n raise ValueError(\"Not a valid sequence (A/G/T/C ONLY)\")\n</code></pre>\n\n<h3>4. Raise Exceptions, instead of printing \"ERROR\"</h3>\n\n<p>There are a few places in your example where you print error messages. That's fine if you really don't want to raise actual exceptions, but that does seem to be the behavior your code is dancing around. I would recommend reading <a href=\"https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement\" rel=\"nofollow noreferrer\">Python's documentation on <code>raise</code></a> if you're unfamiliar with it.</p>\n\n<h3>5. Use <code>if __name__ == \"__main__\"</code> when running module as source</h3>\n\n<p>If you don't know what <code>if __name__ == \"__main__\"</code> means, check out <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">this explanation</a>. Basically, my recommendation is to start using this pattern even if it may not be strictly <em>necessary</em> in your example (although it does protect you from the lurking <code>seq</code> name-shadowing bug). This will facilitate maintenance of your code should you need to import your example code as a module in the future, for example.</p>\n\n<h3>6. Use <code>enumerate</code> to loop through <code>input_file</code> with line index</h3>\n\n<p>Instead of using the <code>line_location</code> variable, you can remove the <code>line_location = 0</code> line, and change</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for line in input_file:\n line_location = line_location + 1\n</code></pre>\n\n<p>to </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for line_location, line in enumerate(input_file):\n</code></pre>\n\n<p>If you still want <code>line_location</code> to be 1-indexed, just add 1 when you <code>print</code>/<code>write</code> it below.</p>\n\n<h1>Other Notes</h1>\n\n<ul>\n<li>For more recent versions of Python, you'll need to use <code>input</code> instead of <code>raw_input</code></li>\n<li>If there is any chance your output file has not already been created by you (which seems likely), you should <code>open</code> it using <code>mode=\"x\"</code>, which will create and open the file</li>\n<li>If any of the subdirectories in the output file path have not already been created, you'll need to use <a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"nofollow noreferrer\">something like <code>os.makedirs</code></a> to handle directory creation</li>\n<li>The line <code>print(\"[*] FILE CREATED AT: \" + output_file_path)</code> near the bottom may be misleading, as the output file is created when you call <code>open</code>, not when you call <code>write</code>. This means that even if <code>count == 0</code>, an output file was created (albeit a blank one)</li>\n<li>In the provided suggested code, I removed the <code>lines</code> variable, since it isn't used; however, if you actually do need it for something not shown in your example, it can be safely re-added, along with the <code>lines.append(line)</code> line</li>\n<li>I would recommend embracing <a href=\"https://docs.python.org/3.4/library/string.html#format-examples\" rel=\"nofollow noreferrer\">Python's string <code>format</code> method</a>, instead of using <code>+</code> to construct strings</li>\n</ul>\n\n<h1>TL;DR</h1>\n\n<p>If you decide to follow the above suggestions, your code will probably end up looking something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport re\n\ndef check_sequence_characters(seq):\n if any(c not in \"AGTC\" for c in seq):\n raise ValueError(\"Not a valid sequence (A/G/T/C ONLY)\")\n\ndef check_sequence_length(seq):\n if len(seq) != 5:\n raise ValueError(\"Has to be exactly 5 letters long!\")\n\ndef _execute():\n seq = raw_input(\"Enter a 5 basepair sequence using only A,G,T,C: \\n\")\n count = 0\n check_sequence_characters(seq)\n check_sequence_length(seq)\n input_file_path = os.getenv(\"HOME\") + \"/Desktop/sequencer/inputfile.txt\"\n output_file_path = os.getenv(\"HOME\") + \"/Desktop/sequencer/output/\" + seq + \".txt\"\n\n with open(input_file_path) as input_file, open(output_file_path, 'x+') as output_file:\n for line_location, line in enumerate(input_file):\n arr = re.findall(seq, line)\n\n if arr and arr[0] == seq:\n count += 1\n print(\"[+] Sequence found at line \" + str(line_location + 1))\n output_file.write(\"Line \" + str(line_location + 1) + \": \" + line + \"\\n\")\n\n if count != 0:\n print(\"[*] Matches: \" + str(count))\n print(\"[*] FILE CREATED AT: \" + output_file_path)\n else:\n raise RuntimeError(\"No matches found!\")\n\nif __name__ == \"__main__\":\n _execute()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T06:36:04.253", "Id": "408493", "Score": "2", "body": "`enumerate` takes as an optional second argument the number to start counting from. So if you want 1-indexed you can just do `for i, line in enumerate(input_file, 1):`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T08:58:43.427", "Id": "408499", "Score": "0", "body": "@Graipher, thanks for bringing that up! I completely forgot about it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T01:36:29.943", "Id": "211234", "ParentId": "211227", "Score": "4" } } ]
{ "AcceptedAnswerId": "211234", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:34:14.850", "Id": "211227", "Score": "2", "Tags": [ "python", "regex", "file", "homework", "bioinformatics" ], "Title": "Looping through file finding sequences" }
211227
<p>I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?</p> <pre><code>import inspect import my_module my_module_class_names = [ name for name, clazz in inspect.getmembers(my_module, inspect.isclass) if clazz.__module__ == my_module.__name__ ] </code></pre> <ul> <li><code>inspect.getmembers(my_module, inspect.isclass)</code> gets any class members of <code>my_module</code>.</li> <li><code>if clazz.__module__ == my_module.__name__</code> ensures that classes <code>import</code>ed into <code>my_module</code> are <em>excluded</em> from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had already <code>import</code>ed other classes, and therefore the list had extraneous members.</li> </ul> <p>Alternatively, from within <code>my_module</code>:</p> <pre><code>import inspect import sys def class_names() -&gt; List[str]: return [ name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass) if clazz.__module__ == sys.modules[__name__].__name__ ] </code></pre>
[]
[ { "body": "<p>I have already used similar code and it looks rather fine. Some nitpicks:</p>\n\n<ul>\n<li>I’d name the variable <code>cls</code> to mimic the name often used as first parameters of <code>@classmethod</code>s; or <code>class_</code> as it is more common;</li>\n<li>I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as <code>cls.__name__</code> if need be);</li>\n<li><code>sys.modules[__name__].__name__</code> should be just <code>__name__</code>.</li>\n</ul>\n\n<hr>\n\n<p>Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:</p>\n\n<pre><code>[cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>my_module.CommonBase.__subclasses__()\n</code></pre>\n\n<p>if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:51:43.737", "Id": "408546", "Score": "0", "body": "Excellent! I do need the actual class names rather than the `type`s, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T09:30:47.950", "Id": "211246", "ParentId": "211235", "Score": "3" } } ]
{ "AcceptedAnswerId": "211246", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T02:22:09.507", "Id": "211235", "Score": "3", "Tags": [ "python", "object-oriented", "python-3.x", "reflection", "modules" ], "Title": "Snippet to get all local classes from a module" }
211235
<p>So I've been experimenting various way to get data from different variety of website; as such, between the use of JSON or BeautifulSoup. Currently, I have written a scrapper to collect data such as <code>[{Title,Description,Replies,Topic_Starter, Total_Views}]</code>; but it pretty much has no reusable code. I've been figuring out how to correct my approach of appending data to one singular list for simplicity and reusability. But I've pretty much hit a stone with my current capability. </p> <pre><code>from requests import get from bs4 import BeautifulSoup import pandas as pd from time import sleep url = 'https://forum.lowyat.net/ReviewsandGuides' list_topic = [] list_description = [] list_replies = [] list_topicStarted = [] list_totalViews = [] def getContentFromURL(_url): try: response = get(_url) html_soup = BeautifulSoup(response.text, 'lxml') return html_soup except Exception as e: print('Error.getContentFromURL:', e) return None def iterateThroughPages(_lastindexpost, _postperpage, _url): indices = '/+' index = 0 for i in range(index, _lastindexpost): print('Getting data from ' + url) try: extractDataFromRow1(getContentFromURL(_url)) extractDataFromRow2(getContentFromURL(_url)) print('current page index is: ' + str(index)) print(_url) while i &lt;= _lastindexpost: for table in get(_url): if table != None: new_getPostPerPage = i + _postperpage newlink = f'{url}{indices}{new_getPostPerPage}' print(newlink) bs_link = getContentFromURL(newlink) extractDataFromRow1(bs_link) extractDataFromRow2(bs_link) # threading to prevent spam. Waits 0.5 secs before executing sleep(0.5) i += _postperpage print('current page index is: ' + str(i)) if i &gt; _lastindexpost: # If i gets more than the input page(etc 1770) halts print('No more available post to retrieve') return except Exception as e: print('Error.iterateThroughPages:', e) return None def extractDataFromRow1(_url): try: for container in _url.find_all('td', {'class': 'row1', 'valign': 'middle'}): # get data from topic title in table cell topic = container.select_one( 'a[href^="/topic/"]').text.replace("\n", "") description = container.select_one( 'div.desc').text.replace("\n", "") if topic or description is not None: dict_topic = topic dict_description = description if dict_description is '': dict_description = 'No Data' # list_description.append(dict_description) #so no empty string# list_topic.append(dict_topic) list_description.append(dict_description) else: None except Exception as e: print('Error.extractDataFromRow1:', e) return None def extractDataFromRow2(_url): try: for container in _url.select('table[cellspacing="1"] &gt; tr')[2:32]: replies = container.select_one('td:nth-of-type(4)').text.strip() topic_started = container.select_one( 'td:nth-of-type(5)').text.strip() total_views = container.select_one( 'td:nth-of-type(6)').text.strip() if replies or topic_started or total_views is not None: dict_replies = replies dict_topicStarted = topic_started dict_totalViews = total_views if dict_replies is '': dict_replies = 'No Data' elif dict_topicStarted is '': dict_topicStarted = 'No Data' elif dict_totalViews is '': dict_totalViews = 'No Data' list_replies.append(dict_replies) list_topicStarted.append(dict_topicStarted) list_totalViews.append(dict_totalViews) else: print('no data') None except Exception as e: print('Error.extractDataFromRow2:', e) return None # limit to 1740 print(iterateThroughPages(1740, 30, url)) new_panda = pd.DataFrame( {'Title': list_topic, 'Description': list_description, 'Replies': list_replies, 'Topic Starter': list_topicStarted, 'Total Views': list_totalViews}) print(new_panda) </code></pre> <p>I'm sure the use of my <code>try</code> is redundant at this point as well, my large variety of List including, and the use of <code>While</code> and <code>For</code> is most likely practiced wrongly. </p>
[]
[ { "body": "<p>I would separate the two concerns of getting the table data and processing it a bit more. For this it might make sense to have one generator that just yields rows from the table and gets the next page if needed:</p>\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup, SoupStrainer\n\nSESSION = requests.Session()\n\ndef get_table_rows(base_url, posts_per_page=30):\n \"\"\"Continously yield rows from the posts table.\n\n Requests a new page only when needed.\n \"\"\"\n start_at = 0\n while True:\n print(f'current page index is: {start_at // posts_per_page + 1}')\n response = SESSION.get(base_url + f\"/+{start_at}\")\n response.raise_for_status()\n soup = BeautifulSoup(response.text, 'lxml',\n parse_only=SoupStrainer(\"table\", {\"cellspacing\": \"1\"}))\n yield from soup.find_all(\"tr\")\n start_at += posts_per_page\n</code></pre>\n\n<p>This already chooses only the correct table, but still contains the header row. It also reuses the connection to the server by using a <a href=\"http://docs.python-requests.org/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>requests.Session</code></a>. This is an infinite generator. Choosing to only get the first n entries is done later using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a>.</p>\n\n<p>Now we just need to parse a single table row, which can go to another function:</p>\n\n<pre><code>def parse_row(row):\n \"\"\"Get info from a row\"\"\"\n columns = row.select(\"td\")\n try:\n if not columns or columns[0][\"class\"] in ([\"darkrow1\"], [\"nopad\"]):\n return\n except KeyError: # first column has no class\n # print(row)\n return\n try:\n title = row.select_one(\"td.row1 a[href^=/topic/]\").text.strip() or \"No Data\"\n description = row.select_one(\"td.row1 div.desc\").text.strip() or \"No Data\"\n replies = row.select_one(\"td:nth-of-type(4)\").text.strip() or \"No Data\"\n topic_starter = row.select_one('td:nth-of-type(5)').text.strip() or \"No Data\"\n total_views = row.select_one('td:nth-of-type(6)').text.strip() or \"No Data\"\n except AttributeError: # something is None\n # print(row)\n return\n return {\"Title\": title,\n \"Description\": description,\n \"Replies\": replies,\n \"Topic Starter\": topic_starter,\n \"Total Views\": total_views}\n\ndef parse_rows(url):\n \"\"\"Filter out rows that could not be parsed\"\"\"\n yield from filter(None, (parse_row(row) for row in get_table_rows(url)))\n</code></pre>\n\n<p>Then your main loop just becomes this:</p>\n\n<pre><code>from itertools import islice\nimport pandas as pd\n\nif __name__ == \"__main__\":\n url = 'https://forum.lowyat.net/ReviewsandGuides'\n max_posts = 1740\n df = pd.DataFrame.from_records(islice(parse_rows(url), max_posts))\n print(df)\n</code></pre>\n\n<p>Note that I (mostly) followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, especially when naming variables (<code>lower_case</code>). This code also has a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script and the functions have (probably too short) <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> describing what each function does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T02:31:59.433", "Id": "408595", "Score": "0", "body": "after hitting index 53; the response becomes a `<Response [403]>` and goes into an infinite loop; while all previous ones before index 53 are `200`, am I understanding the concept wrongly atm ~? Does the page index through each row one by one or is it indexing each page~? Sorry that I'm asking more when you've taken the time to help and explain many of them. I'm trying to understand most of them, using the referral you've given but at the same time I'm having that return output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T02:53:39.647", "Id": "408597", "Score": "1", "body": "oh; I realized what happened. I got IP blocked from the site for requesting too often." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T03:34:15.050", "Id": "408599", "Score": "0", "body": "After adding threading to prevent spam; it worked beautifully~ thank you so much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T06:44:22.447", "Id": "408602", "Score": "0", "body": "@Minial I added `response.raise_for_status()` so at least it dies with an exception in that case instead of being stuck in an infinite loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T06:46:36.197", "Id": "408603", "Score": "0", "body": "Ah, alright ~ but i had to thread it to avoid being blocked from the site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T06:49:42.277", "Id": "408604", "Score": "1", "body": "@Minial Yeah that is probably the real solution to that problem, but not being stuck in an infinite loop is nice in addition :-)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T06:50:24.113", "Id": "408605", "Score": "1", "body": "Yup; once it reaches the end post it stops~ but regardless; thanks for your time and effort :) much appreciation in helping me improve my coding; I've pretty much applied to my other methods and reduced lots of unnecessary and repetitive for loops after understanding how yours worked." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:13:11.713", "Id": "211262", "ParentId": "211238", "Score": "3" } } ]
{ "AcceptedAnswerId": "211262", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T04:54:18.267", "Id": "211238", "Score": "4", "Tags": [ "python", "python-3.x", "web-scraping", "beautifulsoup" ], "Title": "Cleaner way of appending data to List in BeautifulSoup" }
211238
<p>I made an A* pathfinder and it was too slow so i did some research into priority queues, i got it working but i am wondering if there is any improvements i can make for this class.</p> <p>I opted to make a constructor that allows the option of min or max order, since it runs on the pathfinder the performance of this is quite crucial as well. So hopefully some one has some suggestions on ways to improve it.</p> <p>Here is the class:</p> <pre><code>public class Heap : IEnumerable { private readonly bool _isMinHeap; public readonly IMinHeap[] _items; private int _count; public int Size =&gt; _count; public Heap(int size, bool isMinHeap = true) { _items = new IMinHeap[size]; _count = 0; _isMinHeap = isMinHeap; } public void Insert(IMinHeap item, int priority) { item.SetPriority(priority); if (Contains(item)) { UpdateItem(item); return; } _items[_count] = item; item.HeapIndex = _count; _count++; CascadeUp(item); } private void UpdateItem(IMinHeap item) { int parentIndex = item.HeapIndex / 2; if (parentIndex &gt; 0 &amp;&amp; !HasCorrectParent(item.Value,_items[parentIndex].Value)) { CascadeUp(item); } else { CascadeDown(item); } } public bool Contains(IMinHeap item) { if(item.HeapIndex &lt; 0 || item.HeapIndex &gt; _items.Length-1 || !Equals(_items[item.HeapIndex], item)) return false; return true; } /// &lt;summary&gt; /// Clear the priority queue and reset all nodes /// &lt;/summary&gt; public void Wipe() { for (int i = 0; i &lt; _items.Length; i++) { _items[i].HeapIndex = -1; } Array.Clear(_items,0,_items.Length); _count = 0; } /// &lt;summary&gt; /// Clear the priority but does not reset node indexes /// &lt;/summary&gt; public void Clear() { Array.Clear(_items, 0, _items.Length); _count = 0; } public bool Pop(out IMinHeap item) { item = null; if (_count == 0) return false; item = _items[0]; IMinHeap newRoot = _items[_count]; _items[0] = newRoot; newRoot.HeapIndex = 0; _items[_count] = null; _count--; CascadeDown(newRoot); return true; } private void CascadeDown(IMinHeap item) { do { int childLeftIndex = item.HeapIndex * 2; int childRightIndex = childLeftIndex + 1; if (!HasCorrectChild(item.Value, _items[childLeftIndex])) { Swap(item.HeapIndex,childLeftIndex); } else if (!HasCorrectChild(item.Value, _items[childRightIndex])) { Swap(item.HeapIndex, childLeftIndex); } int parentIndex = item.HeapIndex / 2; SortChildren(parentIndex); if (!HasCorrectParent(item.Value, _items[parentIndex].Value)) { Swap(item.HeapIndex, parentIndex); } else { return; } } while (true); } private bool HasCorrectChild(int itemValue, IMinHeap child) { return _isMinHeap &amp;&amp; child.Value &gt;= itemValue || !_isMinHeap &amp;&amp; child.Value &lt;= itemValue; } private void CascadeUp(IMinHeap item) { if (item.HeapIndex == 0) return; // there is no parents to look for do { int parentIndex = item.HeapIndex / 2; if (_items[parentIndex] == null) return; var parentValue = _items[parentIndex].Value; if (!HasCorrectParent(item.Value, parentValue)) { Swap(item.HeapIndex, parentIndex); SortChildren(parentIndex); } else { return; } } while (true); } private void SortChildren(int parentIndex) { int leftChildIndex = 2 * parentIndex; int rightChildIndex = leftChildIndex + 1; var leftChild = _items[leftChildIndex]; var rightChild = _items[rightChildIndex]; if(leftChild == null || rightChild == null) //the parent has only one or no children - nothing to sort return; else if(leftChild.Value &gt; rightChild.Value &amp;&amp; _isMinHeap || leftChild.Value &lt; rightChild.Value &amp;&amp; !_isMinHeap) Swap(leftChildIndex,rightChildIndex); } private void Swap(int itemIndexA, int itemIndexB) { var item = _items[itemIndexA]; var parent = _items[itemIndexB]; _items[itemIndexA] = parent; _items[itemIndexB] = item; parent.HeapIndex = itemIndexA; item.HeapIndex = itemIndexB; } private bool HasCorrectParent(int itemValue, int parentValue) { return _isMinHeap &amp;&amp; parentValue &lt;= itemValue || !_isMinHeap &amp;&amp; parentValue &gt;= itemValue; } public IEnumerator&lt;IMinHeap&gt; GetEnumerator() { for (int i = 0; i &lt; _count; i++) yield return _items[i]; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } </code></pre> <p>Interface used for it:</p> <pre><code>public interface IMinHeap { int HeapIndex { get; set; } int Value { get; } void SetPriority(int priority); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T07:17:23.663", "Id": "408495", "Score": "5", "body": "What is `IMinHeap`? Did you forget to include it? Your class also implements the `IEnumerator<IMinHeap> GetEnumerator()` API but the interface it implements is non-generic. Why this mismatch?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T23:12:28.073", "Id": "408584", "Score": "1", "body": "Oh sorry i thought i had added it at the bottom, my mistake. I have edited it in." } ]
[ { "body": "<blockquote>\n <p>I opted to make a constructor that allows the option of min or max\n order, since it runs on the pathfinder the performance of this is\n quite crucial as well. So hopefully some one has some suggestions on\n ways to improve it.</p>\n</blockquote>\n\n<p>Sure: take an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.icomparer-1?view=netframework-4.7.2\" rel=\"noreferrer\">IComparer</a> (defaulting to <code>Comparer&lt;T&gt;.Default</code> if you have a simpler constructor which doesn't take one) and use that for all comparisons.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public class Heap : IEnumerable\n</code></pre>\n</blockquote>\n\n<p>Why is this not generic?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private int _count;\n public int Size =&gt; _count;\n</code></pre>\n</blockquote>\n\n<p>Why not</p>\n\n<pre><code> public int Size { get; private set; }\n</code></pre>\n\n<p>? And why <code>Size</code> rather than <code>Count</code>? It might even be worth implementing the full <code>ICollection&lt;T&gt;</code> interface.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void Insert(IMinHeap item, int priority)\n {\n item.SetPriority(priority);\n</code></pre>\n</blockquote>\n\n<p>Yikes! This is exposing internal data to the whole world. I could call <code>Insert</code> and then <code>SetPriority</code> and break your class.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private void UpdateItem(IMinHeap item)\n {\n int parentIndex = item.HeapIndex / 2;\n</code></pre>\n</blockquote>\n\n<p>Are you sure? Bear in mind that C# arrays are indexed from 0, not 1.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool Contains(IMinHeap item)\n {\n if(item.HeapIndex &lt; 0 || item.HeapIndex &gt; _items.Length-1 || !Equals(_items[item.HeapIndex], item)) return false;\n</code></pre>\n</blockquote>\n\n<p>Again, this is exposing internal data. If you want to implement <code>Contains</code> and <code>UpdateItem</code> without exposing internal data then the standard approach would be to wrap two data structures: an array for the heap itself and a <code>Dictionary&lt;T, int&gt;</code> for the heap index.</p>\n\n<blockquote>\n<pre><code> return true;\n</code></pre>\n</blockquote>\n\n<p>But if you're going to do it this way, why not invert the test and just have</p>\n\n<pre><code> public bool Contains(IMinHeap item) =&gt; item.HeapIndex &gt;= 0 &amp;&amp; item.HeapIndex &lt; _items.Length &amp;&amp; Equals(_items[item.HeapIndex], item);\n</code></pre>\n\n<p>? That seems clearer to me.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> /// &lt;summary&gt;\n /// Clear the priority queue and reset all nodes\n /// &lt;/summary&gt;\n public void Wipe()\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> /// &lt;summary&gt;\n /// Clear the priority but does not reset node indexes\n /// &lt;/summary&gt;\n public void Clear()\n</code></pre>\n</blockquote>\n\n<p>I'm puzzled as to why both are needed.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool Pop(out IMinHeap item)\n</code></pre>\n</blockquote>\n\n<p>I would prefer <code>public T Pop()</code> and throw an exception if it's empty. If I implemented this method I'd call it <code>TryPop</code>. IMO that's more consistent with the standard library.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private void CascadeDown(IMinHeap item)\n {\n do\n {\n int childLeftIndex = item.HeapIndex * 2;\n int childRightIndex = childLeftIndex + 1;\n</code></pre>\n</blockquote>\n\n<p>Again, are you sure?</p>\n\n<blockquote>\n<pre><code> if (!HasCorrectChild(item.Value, _items[childLeftIndex]))\n {\n Swap(item.HeapIndex,childLeftIndex);\n }\n else if (!HasCorrectChild(item.Value, _items[childRightIndex]))\n {\n Swap(item.HeapIndex, childLeftIndex);\n }\n\n int parentIndex = item.HeapIndex / 2;\n SortChildren(parentIndex);\n</code></pre>\n</blockquote>\n\n<p>I'm really not convinced that this is correct. The standard implementation is to first compare the left and right children to work out which should be popped first, and then compare just that one with the parent.</p>\n\n<p>Incidentally, what tests do you have for the queue?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n</code></pre>\n</blockquote>\n\n<p>You used <code>=&gt;</code> notation earlier: why not use it here?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T23:19:48.690", "Id": "408585", "Score": "0", "body": "Regarding the compare for popping, i always pop the left child since i sort them on insertion, the swaps makes sure the left is the correct priority over the right. I was not aware there was a standard implementation for this.\n\nI think i understand what you mean with the `/2` to get parent index, i'm assuming the fix for that is to use indexes from 1 and up and leave 0 empty?\n\nCould you elaborate on `This is exposing internal data to the whole world`. Not sure what you mean by that since the interface implements the set priority - how else will an object have its priority set?e" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T03:12:33.170", "Id": "408598", "Score": "0", "body": "Additionally you mention making it generic, not sure how that would work, i use an interface to set the priority on objects, how would i apply generics to it ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T09:11:00.610", "Id": "408612", "Score": "0", "body": "1. \"*i always pop the left child since i sort them on insertion*\": but have you proved that cascading always maintains that invariant for the entire heap? I'm nervous about that. 2. Indexing from 1 is one way to solve the parent index problem. Alternatively, indexing from 0, the children of `x` are `2*x+1` and `2*x+2` and the parent is `(x-1)/2`. 3. Rather than take an `IMinHeap` as an argument, take the value and then wrap it in an `IMinHeap` inside the `Insert` method. That way the caller doesn't have access to it and can't change its priority." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T09:15:06.120", "Id": "408613", "Score": "0", "body": "For a standard implementation, see [Wikipedia](https://en.wikipedia.org/wiki/Binary_heap) or any algorithms textbook. For examples of generic heaps, see https://codereview.stackexchange.com/q/152998/1402 or https://codereview.stackexchange.com/q/84530/1402 . Given that you want to support updating priority, I would use a more general approach: `BinaryHeap<TValue, TPriority>` which has ctor `BinaryHeap(IComparer<TPriority>)` and methods `Push(TValue, TPriority)`, `Update(TValue, TPriority)`, `TValue Pop()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T21:15:49.263", "Id": "408749", "Score": "0", "body": "Hm i'm not too familiar with the IComparer i'll have to research it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T09:15:40.607", "Id": "211245", "ParentId": "211239", "Score": "10" } } ]
{ "AcceptedAnswerId": "211245", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T04:58:04.450", "Id": "211239", "Score": "3", "Tags": [ "c#", "priority-queue" ], "Title": "C# binary heap priority queue" }
211239
<p>Here is a simple reimplementation of most of <code>std::vector</code>. I want to check if I implement it correctly but the standard libraries source code is not very readable for me.</p> <pre><code>namespace nonstd { template&lt;typename Ty&gt; class vector { public: using iterator = Ty * ; using const_iterator = const Ty*; vector(); explicit vector(const size_t count); vector(const size_t count, const Ty&amp; val); vector(const vector&amp; other); vector(vector&amp;&amp; other); ~vector(); vector&amp; operator=(const vector&amp; other); vector&amp; operator=(vector&amp;&amp; other); size_t size() const; size_t capacity() const; void push_back(const Ty&amp; val); void push_back(Ty&amp;&amp; val); void pop_back(); Ty&amp; front(); const Ty&amp; front() const; Ty&amp; back(); const Ty&amp; back() const; Ty&amp; operator[](const size_t pos); const Ty&amp; operator[](const size_t pos) const; iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; private: Ty * buffer; iterator m_first; iterator m_last; iterator m_end; void realloc(const size_t factor, const size_t carry); void alloc(const size_t cap); }; template&lt;typename Ty&gt; vector&lt;Ty&gt;::vector() : buffer(new Ty[10]), m_first(buffer), m_last(buffer), m_end(buffer + 10) { } template&lt;typename Ty&gt; vector&lt;Ty&gt;::vector(const size_t count) : buffer(new Ty[count]), m_first(buffer), m_last(buffer + count), m_end(buffer + count) { } template&lt;typename Ty&gt; vector&lt;Ty&gt;::vector(const size_t count, const Ty&amp; val) : buffer(new Ty[count]), m_first(buffer), m_last(buffer + count), m_end(buffer + count) { while (count--) { buffer[count] = val; } } template&lt;typename Ty&gt; vector&lt;Ty&gt;::vector(const vector&amp; other) : buffer(new Ty[other.capacity()]), m_first(buffer), m_last(buffer + other.size()), m_end(buffer + other.capacity()) { for (size_t i = 0; i &lt; size(); ++i) { buffer[i] = other[i]; } } template&lt;typename Ty&gt; vector&lt;Ty&gt;::vector(vector&amp;&amp; other) : buffer(other.buffer), m_first(other.m_first), m_last(other.m_last), m_end(other.m_end) { other.buffer = nullptr; other.m_first = other.m_last = other.m_end = nullptr; } template&lt;typename Ty&gt; vector&lt;Ty&gt;::~vector() { if (buffer != nullptr) { m_first = m_last = m_end = nullptr; delete[] buffer; } } template&lt;typename Ty&gt; vector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(const vector&lt;Ty&gt;&amp; other) { if (this == &amp;other) { return *this; } this-&gt;~vector(); buffer = new Ty[other.capacity()]; m_first = buffer; m_last = buffer + other.size(); m_end = buffer + other.capacity(); for (size_t i = 0; i &lt; size(); ++i) { buffer[i] = other[i]; } return *this; } template&lt;typename Ty&gt; vector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(vector&lt;Ty&gt;&amp;&amp; other) { if (this == &amp;other) { return *this; } this-&gt;~vector(); buffer = other.buffer; m_first = other.m_first; m_last = other.m_last; m_end = other.m_end; other.buffer = nullptr; other.m_first = other.m_last = other.m_end = nullptr; return *this; } template&lt;typename Ty&gt; size_t vector&lt;Ty&gt;::size() const { return static_cast&lt;size_t&gt;(m_last - m_first); } template&lt;typename Ty&gt; size_t vector&lt;Ty&gt;::capacity() const { return static_cast&lt;size_t&gt;(m_end - m_first); } template&lt;typename Ty&gt; void vector&lt;Ty&gt;::push_back(const Ty&amp; val) { if (size() &lt; capacity()) { *(m_last++) = val; return; } realloc(2, 2); *(m_last++) = val; } template&lt;typename Ty&gt; void vector&lt;Ty&gt;::push_back(Ty&amp;&amp; val) { if (size() &lt; capacity()) { *(m_last++) = std::move(val); return; } realloc(2, 2); *(m_last++) = std::move(val); } template&lt;typename Ty&gt; void vector&lt;Ty&gt;::pop_back() { if (size() == 0) { throw std::exception("vector is empty"); } (--m_last)-&gt;~Ty(); } template&lt;typename Ty&gt; Ty&amp; vector&lt;Ty&gt;::front() { if (size() == 0) { throw std::exception("front(): vector is empty"); } return *begin(); } template&lt;typename Ty&gt; const Ty&amp; vector&lt;Ty&gt;::front() const { if (size() == 0) { throw std::exception("front(): vector is empty"); } return *begin(); } template&lt;typename Ty&gt; Ty&amp; vector&lt;Ty&gt;::back() { if (size() == 0) { throw std::exception("back(): vector is empty"); } return *(end() - 1); } template&lt;typename Ty&gt; const Ty&amp; vector&lt;Ty&gt;::back() const { if (size() == 0) { throw std::exception("back(): vector is empty"); } return *(end() - 1); } template&lt;typename Ty&gt; Ty&amp; vector&lt;Ty&gt;::operator[](const size_t pos) { if (pos &gt;= size()) { throw std::exception("index out of range"); } return buffer[pos]; } template&lt;typename Ty&gt; const Ty&amp; vector&lt;Ty&gt;::operator[](const size_t pos) const { if (pos &gt;= size()) { throw std::exception("index out of range"); } return buffer[pos]; } template&lt;typename Ty&gt; typename vector&lt;Ty&gt;::iterator vector&lt;Ty&gt;::begin() { return m_first; } template&lt;typename Ty&gt; typename vector&lt;Ty&gt;::iterator vector&lt;Ty&gt;::end() { return m_last; } template&lt;typename Ty&gt; typename vector&lt;Ty&gt;::const_iterator vector&lt;Ty&gt;::begin() const { return m_first; } template&lt;typename Ty&gt; typename vector&lt;Ty&gt;::const_iterator vector&lt;Ty&gt;::end() const { return m_last; } template&lt;typename Ty&gt; void vector&lt;Ty&gt;::realloc(const size_t factor, const size_t carry) { alloc(capacity() * factor + carry); } template&lt;typename Ty&gt; void vector&lt;Ty&gt;::alloc(const size_t cap) { Ty* new_buffer = new Ty[cap]; size_t sz = size(); for (size_t i = 0; i &lt; sz; ++i) { new_buffer[i] = buffer[i]; } this-&gt;~vector(); buffer = new_buffer; m_first = buffer; m_last = buffer + sz; m_end = buffer + cap; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:34:46.720", "Id": "408572", "Score": "1", "body": "You should take a look at the articles I wrote about building your own vector: https://lokiastari.com/series/ The main improvement I think you need to make is `Lazy Construction of elements` which requires you to use placement new. See: https://lokiastari.com/blog/2016/02/27/vector/index.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:42:55.423", "Id": "408576", "Score": "0", "body": "Note: If you manually run the destructor of the object `this->~vector();` then the object is no longer valid until you re-run the constructor. Since you are inside the object you would need to call the constructor via placement new." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T23:02:32.863", "Id": "408583", "Score": "0", "body": "@MartinYork Thank you, your articles are awesome! Will try again and post it here." } ]
[ { "body": "<h1>Undefined type</h1>\n\n<p>We use <code>size_t</code> with no definition. It seems like we want to use <code>std::size_t</code>, in which case, we need a suitable include, such as <code>&lt;cstddef&gt;</code>.</p>\n\n<p>We also need to include <code>&lt;utility&gt;</code> for <code>std::move()</code> and <code>&lt;stdexcept&gt;</code> for <code>std::exception</code>.</p>\n\n<h1>Missing types</h1>\n\n<p>This template accepts only one argument, but a standard vector also has an <code>Allocator</code> template argument (which defaults to <code>std::allocator&lt;T&gt;</code>). There's quite a lot that will need to be changed to accept and use a provided allocator class.</p>\n\n<p><code>std::vector</code> must provide member types <code>value_​type</code>, <code>allocator_t​ype</code>, <code>size_t​ype</code>, <code>difference_​type</code>, <code>reference</code>, <code>const_​reference</code>, <code>pointer</code>, <code>const_​pointer</code>, <code>reverse_​iterator</code> and <code>const_​reverse_​iterator</code>, but these are all missing from this implementation.</p>\n\n<h1>Missing member functions</h1>\n\n<p>There's no public <code>assign()</code>, <code>at()</code>, <code>data()</code>, <code>empty()</code>, <code>max_​size()</code>, <code>reserve()</code>, <code>shrink_​to_​fit()</code>, <code>clear()</code>, <code>insert()</code>, <code>emplace()</code>, <code>erase()</code>, <code>emplace_​back()</code>, <code>resize()</code> or <code>swap()</code> members. Were also missing the const/reverse versions of <code>begin()</code> and <code>end()</code>, such as <code>rbegin()</code> and <code>crend()</code>.</p>\n\n<h1>Constructors and assignment</h1>\n\n<p>We're missing the initializer-list versions of the constructor and assignment operator.</p>\n\n<p>The line lengths are very long - consider using a separate line for each initializer, like this:</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;::vector()\n : buffer(new Ty[10]),\n m_first(buffer),\n m_last(buffer),\n m_end(buffer + 10)\n{\n}\n</code></pre>\n\n<p>I'm not sure where the magic number <code>10</code> comes from in the above - it's probably worth defining a private constant <code>default_initial_capacity</code> for this.</p>\n\n<p>The constructor that accepts a single <code>count</code> argument fails to initialize its elements (<code>std::vector&lt;int&gt;(5)</code> will create a vector containing five zeros, but our equivalent will have five uninitialized values, which may well cause bugs). This could be avoided by delegating to <code>vector(count, T{})</code>. We should also check for a size of zero and either avoid allocating, or round up to our default capacity in that case.</p>\n\n<p>The <code>(count, val)</code> constructor won't compile, as it attempts to modify <code>const count</code>. We could make <code>count</code> mutable, but I think we should simply use <code>std::fill()</code> (from <code>&lt;algorithm&gt;</code>):</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;::vector(const std::size_t count, const Ty&amp; val)\n : buffer(new Ty[count]),\n m_first(buffer),\n m_last(buffer + count),\n m_end(buffer + count)\n{\n std::fill(m_first, m_last, val);\n}\n</code></pre>\n\n<p>Copy constructor could usefully shrink to fit, using the size rather than the capacity of the source vector to determine the new vector's capacity:</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;::vector(const vector&amp; other)\n : buffer(new Ty[other.size()]),\n m_first(buffer),\n m_last(buffer + other.size()),\n m_end(m_last)\n{\n std::copy(other.m_first, other.m_last, m_first);\n}\n</code></pre>\n\n<p>Again, I use a standard algorithm to avoid hand-coding my own loop.</p>\n\n<p>Move-construction and move-assignment are most easily implemented using <code>swap()</code>:</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;::vector(vector&amp;&amp; other)\n : vector()\n{\n swap(other);\n}\n\ntemplate&lt;typename Ty&gt;\nvector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(vector&lt;Ty&gt;&amp;&amp; other)\n{\n swap(other);\n return *this;\n}\n</code></pre>\n\n<p>It certainly looks wrong to explicitly call the destructor in the assignment operator. All we're using it for is to <code>delete[] buffer</code>, so just do that. Better still, use the copy-and-swap idiom:</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(const vector&lt;Ty&gt;&amp; other)\n{\n swap(vector&lt;Ty&gt;(other)); // copy and swap\n return *this;\n}\n</code></pre>\n\n<h1>Destructor</h1>\n\n<p>There's no need to assign <code>nullptr</code> to the members - they are about to go out of scope, so can't be accessed after the destructor finishes. Also, there's no need to test that <code>buffer</code> is non-null, for two reasons: first, our logic never allows a non-null buffer to exist, and secondly, <code>delete[]</code> will happily do nothing if its argument is null.</p>\n\n<h1>Modifiers</h1>\n\n<p>Look at <code>push_back()</code>:</p>\n\n<blockquote>\n<pre><code>template&lt;typename Ty&gt;\nvoid vector&lt;Ty&gt;::push_back(const Ty&amp; val) {\n if (size() &lt; capacity()) {\n *(m_last++) = val;\n return;\n }\n realloc(2, 2);\n *(m_last++) = val;\n}\n</code></pre>\n</blockquote>\n\n<p>See how <code>*(m_last++) = val;</code> is common to both paths? We can reorder the test so that we don't duplicate that; to my eyes at least, that makes a more natural expression (\"ensure there's room, then add the element\"):</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvoid vector&lt;Ty&gt;::push_back(const Ty&amp; val)\n{\n if (capacity() &lt;= size()) {\n realloc(2, 2);\n }\n *(m_last++) = val;\n}\n</code></pre>\n\n<p>Once <code>rbegin()</code> is implemented, <code>back()</code> can be re-written to use that rather than doing arithmetic on the result of <code>end()</code>.</p>\n\n<h1>Exceptions</h1>\n\n<p><code>std::exception</code> has no constructor that accepts a string literal - we need to use a more specific sub-class, such as <code>std::out_of_range</code>. We should consider whether we have range-checking at all, outside of methods such as <code>at()</code> which mandate it - standard C++ practice is to impose minimum overhead unless it's asked for.</p>\n\n<h1>Private members</h1>\n\n<p>Mostly looks okay, though <code>alloc</code> could be improved using <code>std::move()</code> algorithm instead of a hand-written copy loop, and simple <code>delete[] buffer</code> instead of calling destructor, as described above. It's also wise to allow this function to shrink the buffer; we'll need that for some of the as-yet-unimplemented code:</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvoid vector&lt;Ty&gt;::alloc(const std::size_t cap) {\n Ty* new_buffer = new Ty[cap];\n auto sz = size();\n if (sz &lt; cap) {\n sz = cap;\n }\n std::move(m_first, m_first + sz, new_buffer);\n delete[] buffer;\n buffer = new_buffer;\n m_first = buffer;\n m_last = buffer + sz;\n m_end = buffer + cap;\n}\n</code></pre>\n\n<h1>Redundant member</h1>\n\n<p>Is there any need for separate <code>buffer</code> and <code>m_first</code> members? They have the same type, and as far as I can see, they always hold the same value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:42:43.763", "Id": "408540", "Score": "0", "body": "> This could be avoided by delegating to vector(count, T{})\nyou can't delegate this way in general case, in case there's no copy constructor and/or default ctor does something unusual e.g. fills its element with random value (and on copy values is copied)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:44:15.610", "Id": "408542", "Score": "0", "body": "that's why they have replaced one ctor `vector (size_type n, const value_type& val = value_type()` with two separate ctors since c++11" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:51:36.610", "Id": "408545", "Score": "0", "body": "You're right @RiaD. I was misremembering, and thought that `value_type` needed to be `DefaultConstructible`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:12:48.137", "Id": "408554", "Score": "0", "body": "@Incomputable, sorry, but I don't understand how copy elision is relevant at all" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:21:23.507", "Id": "408557", "Score": "0", "body": "I apologize for my negligence. Somehow I thought the story is only about one object being constructed. Perhaps I dismissed the rest of the problem too quickly." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T10:55:22.650", "Id": "211253", "ParentId": "211241", "Score": "9" } }, { "body": "<p><strong>Code:</strong></p>\n\n<ul>\n<li><p>I realise you're not implementing <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"noreferrer\">the complete functionality</a>, but you probably want add and use at least the <code>value_type</code>, <code>size_type</code>, <code>reference</code> and <code>const_reference</code> typedefs.</p></li>\n<li><p><code>operator==</code> and <code>operator!=</code> are simple to implement and quite useful.</p></li>\n<li><p>Use <code>std::size_t</code>, not <code>size_t</code> (the latter is the C version).</p></li>\n<li><p>Prefer named constants to magic numbers (e.g. declare a <code>static const std::size_t m_initial_size = 10u;</code>).</p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p><code>m_first</code> is the same as <code>buffer</code>, so we don't need it.</p></li>\n<li><p>It's simpler to store the <code>size</code> and <code>capacity</code>, and calculate <code>last</code> and <code>end</code> when needed (we seem to need the size and capacity quite often).</p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li>Good job with <code>const</code>-correctness. Note that function arguments passed by value may be better left non-<code>const</code> because:\n\n<ul>\n<li><code>const</code> is very important for reference / pointer types since with these the function can affect a variable outside its scope. It's easier to read a function definition where these \"important\" <code>const</code>s stand out. e.g. <code>(int foo, T const* bar)</code> vs <code>(const int foo, T const* const bar)</code>.</li>\n<li>C++ will actually match a function declaration that includes / omits a <code>const</code> for a pass-by-value argument with a function definition that omits / includes it respectively.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>Note that the standard version of the single argument constructor <code>explicit vector(const size_t count);</code> does initialize elements (as if it were calling <code>vector(const size_t count, const Ty&amp; val);</code> with a default constructed <code>Ty</code>). In fact, we can use a delegating constructor to do this:</p>\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;::vector(const size_t count) : vector(count, Ty()) { }\n</code></pre></li>\n</ul>\n\n<hr>\n\n<ul>\n<li>Don't call the class destructor in the copy / move operators. The destructor should be called only once (usually automatically) when a class is destroyed. Calling it multiple times may be undefined behaviour. The memory cleanup should be moved into a separate function (e.g. <code>deallocate()</code>), which should be called wherever necessary.</li>\n</ul>\n\n<hr>\n\n<p><strong>Design:</strong></p>\n\n<p>The difference between memory allocation and object construction is an important feature of <code>std::vector</code> that isn't mirrored completely in this <code>nonstd</code> version. With <code>std::vector</code>, a memory buffer of the appropriate size is allocated without any constructor calls. Then objects are constructed in place inside this buffer using <a href=\"https://en.cppreference.com/w/cpp/language/new\" rel=\"noreferrer\">\"placement new\"</a>.</p>\n\n<p>As such, it might be cleaner to abstract the memory buffer into a separate class that only allocates / deallocates memory. This is separate from the construction, copying, and destruction of the elements contained within this buffer, which can be handled by the <code>vector</code> class.</p>\n\n<p>Various standard algorithms also exist to help with placement new, e.g. <a href=\"https://en.cppreference.com/w/cpp/memory/uninitialized_copy_n\" rel=\"noreferrer\"><code>std::uninitialized_copy_n</code></a> and <a href=\"https://en.cppreference.com/w/cpp/memory/uninitialized_fill_n\" rel=\"noreferrer\"><code>std::uninitialized_fill_n</code></a>.</p>\n\n<p>As a (largely untested) example:</p>\n\n<pre><code>#include &lt;cassert&gt;\n#include &lt;cstddef&gt;\n#include &lt;algorithm&gt;\n\nnamespace nonstd {\n\n template&lt;class Ty&gt;\n class memory_block\n {\n public:\n\n using size_type = std::size_t;\n using value_type = Ty;\n using pointer = Ty*;\n using const_pointer = Ty const*;\n\n memory_block():\n m_size(size_type{ 0 }),\n m_buffer(nullptr) { }\n\n explicit memory_block(size_type count):\n m_size(count),\n m_buffer(allocate(m_size)) { }\n\n memory_block(memory_block const&amp; other):\n m_size(other.m_size),\n m_buffer(allcoate(m_size)) { }\n\n memory_block(memory_block&amp;&amp; other):\n m_size(std::move(other.m_size)),\n m_buffer(std::move(other.m_buffer))\n {\n other.m_size = size_type{ 0 };\n other.m_buffer = nullptr;\n }\n\n ~memory_block()\n {\n deallocate(m_buffer);\n }\n\n void swap(memory_block&amp; other)\n {\n using std::swap;\n swap(m_size, other.m_size);\n swap(m_buffer, other.m_buffer);\n }\n\n memory_block&amp; operator=(memory_block const&amp; other)\n {\n auto temp = memory_block(other);\n swap(temp);\n return *this;\n }\n\n memory_block&amp; operator=(memory_block&amp;&amp; other)\n {\n auto temp = memory_block(std::move(other));\n swap(temp);\n return *this;\n }\n\n size_type size() const\n {\n return m_size;\n }\n\n pointer data()\n {\n return m_buffer;\n }\n\n const_pointer data() const\n {\n return m_buffer;\n }\n\n pointer at(size_type index)\n {\n assert(index &lt; m_size); // maybe throw instead\n return m_buffer + index;\n }\n\n const_pointer at(size_type index) const\n {\n assert(index &lt; m_size); // maybe throw instead\n return m_buffer + index;\n }\n\n private:\n\n static pointer allocate(std::size_t size)\n {\n return static_cast&lt;pointer&gt;(::operator new (sizeof(value_type) * size));\n }\n\n static void deallocate(pointer buffer)\n {\n delete static_cast&lt;void*&gt;(buffer);\n }\n\n std::size_t m_size;\n Ty* m_buffer;\n };\n\n template&lt;class Ty&gt;\n inline void swap(memory_block&lt;Ty&gt;&amp; a, memory_block&lt;Ty&gt;&amp; b)\n {\n a.swap(b);\n }\n\n template&lt;class Ty&gt;\n class vector\n {\n public:\n\n using size_type = std::size_t;\n using value_type = Ty;\n\n vector();\n explicit vector(size_type count);\n vector(size_type count, const value_type&amp; val);\n\n vector(const vector&amp; other);\n vector(vector&amp;&amp; other);\n\n ~vector();\n\n void swap(vector&amp; other);\n\n vector&amp; operator=(const vector&amp; other);\n vector&amp; operator=(vector&amp;&amp; other);\n\n size_t size() const;\n size_t capacity() const;\n\n void push_back(const value_type&amp; val);\n void pop_back();\n\n private:\n\n static const size_type M_INITIAL_SIZE = size_type{ 10 };\n\n size_type m_size;\n memory_block&lt;Ty&gt; m_buffer;\n\n void grow(size_type amount);\n void reallocate(size_type min_size);\n\n void construct(size_type index, const value_type&amp; value);\n void destruct(size_type index);\n void destruct_all();\n };\n\n template&lt;class Ty&gt;\n inline void swap(vector&lt;Ty&gt;&amp; a, vector&lt;Ty&gt;&amp; b)\n {\n a.swap(b);\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;::vector(): \n m_size(0u), \n m_buffer(M_INITIAL_SIZE)\n {\n\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;::vector(size_type count):\n m_size(count),\n m_buffer(m_size)\n {\n std::uninitialized_value_construct_n(m_buffer.data(), m_size); // value construct each element w/ placement new (C++17)\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;::vector(size_type count, const value_type&amp; value) : \n m_size(count),\n m_buffer(m_size)\n {\n std::uninitialized_fill_n(m_buffer.data(), m_size, value); // copy construct each element w/ placement new\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;::vector(const vector&amp; other):\n m_size(other.m_size),\n m_buffer(m_size) // note: allocates only what we need to contain the existing elements, not the same as the capacity of the other buffer\n {\n std::uninitialized_copy_n(other.m_buffer.data(), other.m_size, m_buffer.data()); // copy construct each element from old buffer to new buffer w/ placement new\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;::vector(vector&amp;&amp; other):\n m_size(std::move(other.m_size)),\n m_buffer(std::move(other.m_buffer)) // take ownership of the buffer\n {\n other.m_size = size_type{ 0 }; // other vector is now empty (nothing needs to be constructed / destructed)\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;::~vector()\n {\n destruct_all();\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::swap(vector&amp; other)\n {\n using std::swap;\n swap(m_size, other.m_size);\n swap(m_buffer, other.m_buffer);\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(const vector&amp; other)\n {\n auto temp = vector(other);\n swap(temp);\n return *this;\n }\n\n template&lt;class Ty&gt;\n vector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(vector&amp;&amp; other)\n {\n auto temp = vector(std::move(other));\n swap(temp);\n return *this;\n }\n\n template&lt;class Ty&gt;\n size_t vector&lt;Ty&gt;::size() const\n {\n return m_size;\n }\n\n template&lt;class Ty&gt;\n size_t vector&lt;Ty&gt;::capacity() const\n {\n return m_buffer.size();\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::push_back(const value_type&amp; value)\n {\n grow(size_type{ 1 });\n construct(m_size, value);\n ++m_size;\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::pop_back()\n {\n assert(m_size &gt; 0); // maybe throw instead\n\n destruct(m_size - 1);\n --m_size;\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::grow(size_type amount)\n {\n if (m_buffer.size() - m_size &lt; amount)\n reallocate(m_size + amount);\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::reallocate(size_type min_size)\n {\n assert(min_size &gt; m_size);\n\n auto capacity = std::max(min_size, m_buffer.size() + std::max(m_buffer.size() / size_type{ 2 }, size_type{ 1 })); // growth factor of 1.5ish\n\n auto buffer = memory_block&lt;value_type&gt;(capacity);\n std::uninitialized_copy_n(m_buffer.data(), m_size, buffer.data()); // copy each element from old buffer to new buffer w/ placement new\n\n destruct_all(); // clean up the old buffer (call destructors on each of the old elements)\n\n m_buffer = std::move(buffer); // take ownership of the new buffer\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::construct(size_type index, const value_type&amp; value)\n {\n new (m_buffer.at(index)) value_type(value); // placement new w/ copy constructor\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::destruct(size_type index)\n {\n assert(index &lt; m_size);\n\n m_buffer.at(index)-&gt;~value_type(); // explictly call destructor (because we used placement new)\n }\n\n template&lt;class Ty&gt;\n void vector&lt;Ty&gt;::destruct_all()\n {\n for (auto index = size_type{ 0 }; index != m_size; ++index)\n destruct(index);\n }\n\n} // nonstd\n\nint main()\n{\n {\n nonstd::vector&lt;int&gt; v;\n v.push_back(10);\n }\n {\n nonstd::vector&lt;int&gt; v(5);\n v.pop_back();\n }\n {\n nonstd::vector&lt;int&gt; v(5, 1);\n }\n {\n nonstd::vector&lt;int&gt; v1(2, 2);\n nonstd::vector&lt;int&gt; v2(v1);\n }\n {\n nonstd::vector&lt;int&gt; v1(2, 2);\n nonstd::vector&lt;int&gt; v2(std::move(v1));\n }\n}\n</code></pre>\n\n<p>Note the use of the \"copy and swap\" idiom in the copy and move assignment operators, which makes implementing them quite a lot easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:26:24.607", "Id": "408538", "Score": "0", "body": "This is amazing, I learnt a lot from your code, especially the placement new and memory block part. Thanks a lot!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T13:50:11.517", "Id": "211260", "ParentId": "211241", "Score": "11" } }, { "body": "<ol>\n<li>Missing includes:\n\n<ul>\n<li>You need an include for <code>std::size_t</code> (though you could just use <code>size_type</code> everywhere, and declare that as <code>using size_type = decltype(sizeof 0);</code>.</li>\n<li>You use <code>std::move</code>, and thus need <code>&lt;utility&gt;</code>.</li>\n</ul></li>\n</ol>\n\n\n\n<pre><code>namespace nonstd {\n\n template&lt;typename Ty&gt;\n class vector\n</code></pre>\n\n<ol start=\"2\">\n<li><p>If (nearly) everything is in the same namespace, it is conventional <em>not</em> to indent it.</p></li>\n<li><p>Obviously, you forego allocator-support (for now?).</p></li>\n<li><p>Using <code>Ty</code> instead of <code>T</code> is very unconventional. Following convention reduces cognitive load, allowing you to expend it elsewhere more profitably. I'll pretend you followed convention for the rest of the review.</p></li>\n</ol>\n\n\n\n<pre><code> using iterator = Ty * ;\n using const_iterator = const Ty*;\n</code></pre>\n\n<ol start=\"5\">\n<li><p>The whitespace around the first <code>*</code> is misplaced. Consider auto-formatting, or just be a bit more careful to stay consistent.</p></li>\n<li><p>Those aliases are good. You are missing myriad other useful (and necessary) ones though, namely <code>value_type</code>, <code>size_type</code>, <code>difference_type</code>, <code>reference</code>, <code>const_reference</code>, <code>pointer</code>, and <code>const_pointer</code>.<br>\nAnd when you add reverse-iterator-support, <code>reverse_iterator</code> and <code>const_reverse_iterator</code>.</p></li>\n</ol>\n\n\n\n<pre><code> vector();\n explicit vector(const size_t count);\n vector(const size_t count, const Ty&amp; val);\n vector(const vector&amp; other);\n vector(vector&amp;&amp; other);\n ~vector();\n\n vector&amp; operator=(const vector&amp; other);\n vector&amp; operator=(vector&amp;&amp; other);\n</code></pre>\n\n<ol start=\"7\">\n<li><p>There is no reason not to make the default-ctor <code>noexcept</code> and <code>constexpr</code>, even if that means not allocating <em>any</em> memory. Especially as passing a zero count to a ctor or invoking the move-ctor can <em>already</em> result in a 0-capacity vector.<br>\nAlso, the magic constant you chose is pretty arbitrary, and should be a (private) named constant if you decide to keep it.</p></li>\n<li><p>Having <code>const</code> parameters in an API is at best irritating to the reader: It doesn't actually <em>do</em> anything.</p></li>\n<li><p>You are missing constructors from <code>std::initializer_list&lt;T&gt;</code> and iterator-pair. At least copy-ctor and creating from initializer-list should then delegate to iterator-pair for code-reuse.</p></li>\n<li><p>The move-ctor cannot throw by design, and should thus be marked <code>noexcept</code>.</p></li>\n<li><p>Dito for move-assignment.</p></li>\n</ol>\n\n\n\n<pre><code> size_t size() const;\n size_t capacity() const;\n</code></pre>\n\n<ol start=\"12\">\n<li><p>Both observers above could be <code>constexpr</code> if you have at least one <code>constexpr</code> ctor...</p></li>\n<li><p>You are missing <code>empty()</code>, and <code>max_size()</code>.</p></li>\n</ol>\n\n\n\n<pre><code> void push_back(const Ty&amp; val);\n void push_back(Ty&amp;&amp; val);\n void pop_back();\n</code></pre>\n\n<ol start=\"14\">\n<li><p>You are missing <code>emplace_back()</code>, which the first two should delegate to.</p></li>\n<li><p>Also missing are <code>clear()</code>, <code>insert()</code>, <code>emplace()</code>, <code>erase()</code>, and <code>swap()</code>. The last one is crucial for a simple, efficient and exception-safe implementation of much of the class.</p></li>\n</ol>\n\n\n\n<pre><code> Ty&amp; front();\n const Ty&amp; front() const;\n Ty&amp; back();\n const Ty&amp; back() const;\n Ty&amp; operator[](const size_t pos);\n const Ty&amp; operator[](const size_t pos) const;\n</code></pre>\n\n<ol start=\"16\">\n<li><p>All the mutable versions can be implemented by delegating to the <code>const</code> variant and applying a judicious <code>const_cast</code> to the result.<br>\nEspecially as you decided that \"undefined behavior\" means \"throws exception\" in your case.</p></li>\n<li><p>Even though you gave the above observers the behavior of <code>at()</code>, you shouldn't leave it out.</p></li>\n<li><p>You are missing <code>data()</code> completely. Yes, it behaves the same as <code>begin()</code> for you, but there you have it.</p></li>\n</ol>\n\n\n\n<pre><code> iterator begin();\n const_iterator begin() const;\n iterator end();\n const_iterator end() const;\n</code></pre>\n\n<ol start=\"19\">\n<li>You are missing the reverse_iterator equivalents.</li>\n</ol>\n\n\n\n<pre><code> Ty * buffer;\n iterator m_first;\n iterator m_last;\n iterator m_end;\n</code></pre>\n\n<ol start=\"20\">\n<li>Either <code>buffer</code> or <code>m_first</code> is redundant.</li>\n</ol>\n\n\n\n<pre><code> void realloc(const size_t factor, const size_t carry);\n void alloc(const size_t cap);\n</code></pre>\n\n<ol start=\"21\">\n<li><p>Centralizing allocation to enforce policy and reduce repetition is a good idea. You aren't quite there though, and implementing the wrong signature. You need one private member for automatic growth <code>void grow(size_type n = 1)</code> and the rest should be public, so a consumer who <em>knows</em> can use it:</p>\n\n<pre><code>void reserve(size_type n);\nvoid resize(size_type n);\nvoid shrink_to_fit();\n</code></pre></li>\n<li><p>Your current allocation-policy is \"double plus constant\" on reallocation. That's actually the worst one you could choose, as it makes it impossible to reuse any memory over multiple consecutive reallocations (all the returned memory from earlier together is never enough). For that, it should be below two, maybe <code>m_new = max(needed, m_old * 7 / 4)</code> for automatic reallocation.</p></li>\n<li><p>You are missing assignment from <code>std::initializer_list&lt;T&gt;</code>, the more versatile <code>assign()</code>, </p></li>\n</ol>\n\n<p>Now only implementation-details:</p>\n\n<pre><code>vector&lt;Ty&gt;::vector() : buffer(new Ty[10]), m_first(buffer), m_last(buffer), m_end(buffer + 10) {\n// and many more\n</code></pre>\n\n<ol start=\"24\">\n<li>You are aware that <code>new T[n]</code> doesn't only reserve space for <code>n</code> <code>T</code>s, but also constructs them? That extra-work might be quite involved, and is most emphatically <em>not</em> expected. You should only allocate raw memory (by calling e. g. <code>void* operator new(std::size_t)</code>) and construct the members on demand as needed.</li>\n</ol>\n\n\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;::~vector() {\n if (buffer != nullptr) {\n m_first = m_last = m_end = nullptr;\n delete[] buffer;\n }\n}\n</code></pre>\n\n<ol start=\"25\">\n<li>Why do you guard against deleting a nullpointer? Also, why repaint the house when demolishing it?</li>\n</ol>\n\n\n\n<pre><code>template&lt;typename Ty&gt;\nvector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(const vector&lt;Ty&gt;&amp; other) {\n if (this == &amp;other) {\n return *this;\n }\n this-&gt;~vector();\n buffer = new Ty[other.capacity()];\n m_first = buffer;\n m_last = buffer + other.size();\n m_end = buffer + other.capacity();\n for (size_t i = 0; i &lt; size(); ++i) {\n buffer[i] = other[i];\n }\n return *this;\n}\n\ntemplate&lt;typename Ty&gt;\nvector&lt;Ty&gt;&amp; vector&lt;Ty&gt;::operator=(vector&lt;Ty&gt;&amp;&amp; other) {\n if (this == &amp;other) {\n return *this;\n }\n this-&gt;~vector();\n\n buffer = other.buffer;\n m_first = other.m_first;\n m_last = other.m_last;\n m_end = other.m_end;\n\n other.buffer = nullptr;\n other.m_first = other.m_last = other.m_end = nullptr;\n return *this;\n}\n</code></pre>\n\n<ol start=\"26\">\n<li><p>Don't pessimise the common case, by optimising self-assignment.</p></li>\n<li><p>Calling the dtor means the lifetime ended. Pretending it didn't causes Undefined Behavior.</p></li>\n<li><p>Assignment should be transactional: Either succeed, or have no effect. Look into the <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">copy-and-swap idiom</a>.</p></li>\n<li><p>Move-assignment should be simple and efficient: Just <code>swap()</code>.</p></li>\n</ol>\n\n\n\n<pre><code>template&lt;typename Ty&gt;\nvoid vector&lt;Ty&gt;::pop_back() {\n if (size() == 0) {\n throw std::exception(\"vector is empty\");\n }\n (--m_last)-&gt;~Ty();\n}\n</code></pre>\n\n<ol start=\"30\">\n<li><code>pop_back()</code> seems to be the only part of <code>vector</code> assuming you construct and destruct elements on demand. That mismatch can be explosive.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:23:59.213", "Id": "211267", "ParentId": "211241", "Score": "5" } } ]
{ "AcceptedAnswerId": "211260", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T07:19:22.730", "Id": "211241", "Score": "11", "Tags": [ "c++", "reinventing-the-wheel", "vectors" ], "Title": "Simple re-implementation of std::vector" }
211241
<p>I've coded a React component which should display search result and give the user the option to scroll down and retrieve 25 more objects to be displayed when the scrollbar hits the bottom. What I've noticed when I compile and test the component is that the filter buttons to mark is really slow: it takes a couple of seconds after I click on it till it gets marked, and the same applies for bookmark buttons. The component feels really sluggish when it loads in. However, for each time more items are loaded in, it also generates more <code>publishedStates</code> for the <code>publishedButton</code>. I notice that as when it gets generated over 1000 states and 1000 objects is loaded, when I click on buttons to change the state on filter etc is slow.</p> <p>How can I improve and optimize the performance of my component?</p> <pre><code>import * as React from "react"; import * as _ from "lodash"; declare const $: any interface Props { userId: number; } interface State { objects: Object | null isVisible: Boolean searchString: string bookmarkStates: Array&lt;boolean&gt; publishedStates: Array&lt;boolean&gt; categories: Array&lt;String&gt; languages: Array&lt;String&gt; published: Array&lt;String&gt; hasMoreObjects: Boolean, storiesLoaded: number } const getStateName = function (isFiltered, state) { if (JSON.stringify(isFiltered)==JSON.stringify(state.commodityStates)) return 'commodityStates'; else if (JSON.stringify(isFiltered)==JSON.stringify(state.languageStates)) return 'languageStates'; else return 'publishedStates'; } const handlePublishedTime = function (publishedTime) { let publishedTimeCopy = publishedTime.split(' ') let monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; let todayDate = new Date(); let dd = todayDate.getDate(); let mm = todayDate.getMonth(); let yyyy = todayDate.getFullYear(); // Used for comparison of dates. let todayDateFormat = dd + ', ' + monthNames[mm] + ' ' + yyyy; let publishedTimeFormat = publishedTimeCopy[2].split(',') + ' ' + publishedTimeCopy[3] + ' ' + publishedTimeCopy[4]; if (todayDateFormat == publishedTimeFormat) { return publishedTimeCopy[0]; } return publishedTimeCopy[2].replace(',',' ') + ' ' + Resources[publishedTimeCopy[3]].substring(0,3) } export default class SearchResult extends React.PureComponent&lt;Props, State&gt; { constructor(props) { super(props); this.state = { Object: null, isVisible: true, searchString: "", bookmarkStates: [], commodityStates: [], languageStates: [], publishedStates: [], categories: [], languages: [], published: ['1D', '2D', '1W', '1Y', '5Y'], hasMoreObjects: true, objectsLoaded: 25 } $.get('/webapi/test, function (data) { this.setState({ Object: data }); }.bind(this)); } handleScroll = (e) =&gt; { const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight; if (bottom) { this.setState({ storiesLoaded: this.state.storiesLoaded + 25 }); } } handleSearchTextInput (event) { this.setState({ searchString: event }); } handleSearchButton () { this.setState({ isVisible: true }); } addNewBookmark = function (userId, newsId, isBookmarked, bookmarkIndex) { $.post('/webapi/newstestAddNewBookmark?userId=' + (userId), { UserID: userId, }) .done(function () { this.changeBookmarkState(isBookmarked, bookmarkIndex); }.bind(this)) } removeBookmark = function (userId, newsId, isBookmarked, bookmarkIndex) { $.post('/webapi/test/RemoveBookmark?userId=' + (userId), {}) .done(function () { this.changeBookmarkState(isBookmarked, bookmarkIndex); }.bind(this)) } changeBookmarkState(isBookmarked, index) { let bookmarkStatesCopy = this.state.bookmarkStates.slice(); // Create a copy to avoid mutation. bookmarkStatesCopy[index] = isBookmarked == true ? false : true; this.setState({ bookmarkStates: bookmarkStatesCopy }); } changeFilterState(filterByState, index) { const stateName = getStateName(filterByState, this.state); let filterByStateCopy = filterByState.slice(); // Create a copy to avoid mutation. if (index == 0) { filterByStateCopy[index] = filterByState[index] === false; if (stateName != 'publishedStates') filterByStateCopy.map(({}, index1) =&gt; { filterByStateCopy[index1+1] = false; }); } else { filterByStateCopy[index] = filterByState[index] === false; stateName != 'publishedStates' ? filterByStateCopy[0] = false : null }; this.setState({ [stateName]: filterByStateCopy } as any); } renderBookmarkButton(userId, newsId, isBookmarked, bookmarkIndex) { return ( &lt;a onClick={()=&gt;{isBookmarked == false ? this.addNewBookmark(userId, newsId, isBookmarked, bookmarkIndex) : this.removeBookmark(userId, newsId, isBookmarked, bookmarkIndex);}}&gt; &lt;img className={isBookmarked == false ? "bookmark-button" : "bookmark-button bookmark-button-fill-color"} src="/images/logo/Bookmark.svg" /&gt; &lt;/a&gt; ); } renderCategories(Object , isFiltered) { let categories = this.state.categories; Object.map((object) =&gt; { if (Object == null) return null; object.Categories.map((categoryObj, index) =&gt; { if (categories[index] == null) categories.push(categoryObj) if(index === 0) categories.splice(0, 0, 'All'); }); }); // Used to create a new array which contains all elements that pass the test. categories = categories.filter((value, index, array) =&gt; !array.filter((v, i) =&gt; JSON.stringify(value) == JSON.stringify(v) &amp;&amp; i &lt; index).length); const mappedCategories = categories.map((category, index) =&gt; { if (isFiltered[index] == null) { isFiltered[index] = false; if (isFiltered[0] == false) { isFiltered[0] = true; } }; return ( &lt;div key={index}&gt; &lt;a className="checkbox-display" onClick={()=&gt;{ this.changeFilterState(isFiltered, index);}}&gt; {isFiltered[index] ? &lt;div className={ isFiltered[index] ? "checkbox-rectangle checkbox-rectangle-fill-color horizontal-row-filterby" : "checkbox-rectangle horizontal-row-filterby"}&gt; &lt;img className="checkbox-image-size" src="/images/logo/checkmark.svg"/&gt; &lt;/div&gt; : &lt;div className="checkbox-rectangle horizontal-row-filterby"/&gt; } &lt;/a&gt; &lt;span className="category1"&gt;{index == 0 ? 'All' : category['Name']}&lt;/span&gt; &lt;/div&gt; ); }); return ( &lt;div&gt; &lt;div className="filter-by-commodity"&gt;{Resources.Commodity}&lt;/div&gt; {mappedCategories} &lt;/div&gt; ); } renderLanguage(Object , languageFilter) { let languages = this.state.languages; Object.map((object ) =&gt; { if (Object == null) return null; object.Languages.map((languageObj, index) =&gt; { if (languages[index] == null){ languages.push(languageObj) if(index === 0){ languages.splice(0, 0, 'All'); }; }; }); }); // Used to create a new array which contains all elements that pass the test. languages = languages.filter((value, index, array) =&gt; !array.filter((v, i) =&gt; JSON.stringify(value) == JSON.stringify(v) &amp;&amp; i &lt; index).length); const mappedLanguages = languages.map((language, index) =&gt; { if (languageFilter[index] == null) { languageFilter[index] = false; if (languageFilter[0] == false) { languageFilter[0] = true; } }; return ( &lt;div key={index}&gt; &lt;a onClick={()=&gt;{ this.changeFilterState(languageFilter, index);}}&gt; {languageFilter[index] ? (&lt;div className={languageFilter[index] ? "checkbox-rectangle checkbox-rectangle-fill-color horizontal-row-filterby" : "checkbox-rectangle horizontal-row-filterby"}&gt; &lt;img className="checkbox-image-size" src="/images/logo/checkmark.svg"/&gt; &lt;/div&gt;) : &lt;div className="checkbox-rectangle horizontal-row-filterby"/&gt; } &lt;/a&gt; &lt;span className="category1"&gt;{index == 0 ? 'All' : language['LanguageName']}&lt;/span&gt; &lt;/div&gt; ); }); return ( &lt;div&gt; &lt;div className="horizonal-line-short" /&gt; &lt;div className="filter-by-commodity"&gt;{Resources.Languages}&lt;/div&gt; {mappedLanguages} &lt;/div&gt; ); } renderPublished(publishedFilter) { let published = this.state.published; const mappedPublished = published.map((pushlish , index) =&gt; { if (publishedFilter[index] == null) publishedFilter[index] = (false); return ( &lt;div key={index}&gt; &lt;a onClick={()=&gt;{ this.changeFilterState(publishedFilter, index);}}&gt; &lt;div className={publishedFilter[index] ? "checkbox-rectangle-large vertical-row-filterby checkbox-rectangle-fill-color" : "checkbox-rectangle-large vertical-row-filterby"}&gt; &lt;span&gt;{pushlish}&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; ); }); return ( &lt;div&gt; &lt;div className="horizonal-line-short" /&gt; &lt;div className="filter-by-commodity"&gt;{Resources.Published}&lt;/div&gt; &lt;div className='checkbox-display'&gt; {mappedPublished}&lt;/div&gt; &lt;/div&gt; ); } renderStories(Object ) { let isBookmarked = this.state.bookmarkStates; if(Object == null) return null; const mappedStories = Object.slice(0, this.state.objectsLoaded).map((object , index) =&gt; { if (isBookmarked[index] == null) isBookmarked[index] = object.IsBookmarkedMain; return ( &lt;div key={index} className={index == 0 ? "object-rectangle-no-bg" : index % 2 == 0 ? 'object-rectangle-no-bg' : 'object-rectangle'}&gt; &lt;span className="published-time"&gt;{handlePublishedTime(object.PublishedTime)} &lt;/span&gt; &lt;div&gt; &lt;a className="object-header" href={"/test/object.aspx?newsId=" + object.ID}&gt;{object.Header}&lt;/a&gt; {this.renderBookmarkButton(this.props.userId, object.Id, isBookmarked[index], index)} &lt;/div&gt; &lt;/div&gt; ); }); return ( &lt;div&gt; {mappedStories} &lt;/div&gt; ); } renderResults(Object, isVisible, commodityStates, languageStates, publishedStates) { if (isVisible){ return ( &lt;div className="search-result-master-container"&gt; &lt;span className="section-header"&gt;{Resources.Filter_By}&lt;/span&gt; &lt;span className="section-header"&gt;{Object.length} {Resources.Results}:&lt;/span&gt; &lt;div id="filterBySideBar"&gt; &lt;div className="horizontal-line-filter"&gt; &lt;div&gt;{this.renderCategories(Object , commodityStates)}&lt;/div&gt; &lt;div&gt;{this.renderLanguage(Object , languageStates)}&lt;/div&gt; &lt;div&gt;{this.renderPublished(publishedStates)}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="horizontal-line-stories-top"/&gt; &lt;div className="scrollbar" onScroll={this.handleScroll.bind(this)}&gt; &lt;div className="force-overflow"&gt; {this.renderStories(Object)} &lt;/div&gt; &lt;/div&gt; &lt;div className="horizontal-line-stories-bottom" /&gt; &lt;/div&gt; ); } } render() { let Object = this.state.Object; let isVisbible = this.state.isVisible; let commodityStates = this.state.commodityStates; let languageStates = this.state.languageStates; let publishedStates = this.state.publishedStates; if (Object == null) return null; let renderShowResults = this.renderResults(Object , isVisbible, commodityStates, languageStates, publishedStates); return renderShowResults }; } </code></pre>
[]
[ { "body": "<h3>rerenders from <code>bind</code> and anonymous functions</h3>\n\n<p>You have a really bad rerendering problem. Every click handler you have is either <code>bind</code>ed or an anonymous function. Turn these into named functions</p>\n\n<pre><code>&lt;div className=\"scrollbar\" onScroll={this.handleScroll.bind(this)}&gt;\n</code></pre>\n\n<p><code>bind</code> creates a new instance of the function during render cycles, which will add up when you have 10 of them with each instance of the function.</p>\n\n<p>Instead, make it an arrow function inside your <code>class</code>. Arrow functions do not need <code>bind</code></p>\n\n<pre><code>handleScroll = () =&gt; {}\n&lt;div className=\"scrollbar\" onScroll={this.handleScroll}&gt;\n</code></pre>\n\n<p>anonymous functions have the exact same problem in event listeners/handlers</p>\n\n<pre><code>&lt;a className=\"checkbox-display\" onClick={()=&gt;{ this.changeFilterState(isFiltered, index);}}&gt;\n</code></pre>\n\n<p>But a function that takes in arguments are immediately invoked, so you can do an arrow function as a double <code>return</code>.</p>\n\n<pre><code>changeFilterState = (isFiltered, index) =&gt; () =&gt; {} // two arrow functions. this function returns another function\n\n&lt;a className=\"checkbox-display\" onClick={this.changeFilterState(isFiltered, index)}&gt;\n</code></pre>\n\n<h3>separate your UI elements into smaller components</h3>\n\n<p>When you have a large component, its render cycle will go through every single ui element in the component. But not all elements need to be rerendered. Elements whose values never change (or almost never) don't need to go through another render cycle. In order to accomplish this, you need to split them up into their own components.</p>\n\n<h3>memoize those smaller components with <code>React.memo</code> for easy wins.</h3>\n\n<p><code>React.memo</code> makes an initial check to see if anything has changed between the the current and next set of data inside the component. If <code>React.memo</code> finds them to be equal, the component doesn't go through a render cycle.</p>\n\n<p>A method that returns many ui elements</p>\n\n<pre><code>&lt;div key={index}&gt;\n &lt;a className=\"checkbox-display\" onClick={()=&gt;{ this.changeFilterState(isFiltered, index);}}&gt;\n {isFiltered[index] ? \n &lt;div className={ isFiltered[index] ? \"checkbox-rectangle checkbox-rectangle-fill-color horizontal-row-filterby\" : \"checkbox-rectangle horizontal-row-filterby\"}&gt;\n &lt;img className=\"checkbox-image-size\" src=\"/images/logo/checkmark.svg\"/&gt;\n &lt;/div&gt; \n : \n &lt;div className=\"checkbox-rectangle horizontal-row-filterby\"/&gt;\n }\n &lt;/a&gt;\n &lt;span className=\"category1\"&gt;{index == 0 ? 'All' : category['Name']}&lt;/span&gt; \n&lt;/div&gt;\n</code></pre>\n\n<p>How often should the image change? More likely than not, those images aren't going to change for every single one of them each time you load more images. You can pull out that UI element and <code>React.memo</code> it so it does an initial check and skips the render process completely if the values are the same.</p>\n\n<pre><code> const CategoryImage = (props) =&gt; {\n const { isFiltered } = props\n return (\n &lt;React.Fragment&gt;\n {isFiltered ? \n &lt;div className={ isFiltered ? \"checkbox-rectangle checkbox-rectangle-fill-color horizontal-row-filterby\" : \"checkbox-rectangle horizontal-row-filterby\"}&gt;\n &lt;img className=\"checkbox-image-size\" src=\"/images/logo/checkmark.svg\"/&gt;\n &lt;/div&gt; \n : \n &lt;div className=\"checkbox-rectangle horizontal-row-filterby\"/&gt;\n }\n &lt;/React.Fragment&gt;\n )\n\nexport default React.memo(CategoryImage)\n</code></pre>\n\n<p>and now it is this:</p>\n\n<pre><code>&lt;div key={index}&gt;\n &lt;a className=\"checkbox-display\" onClick={()=&gt;{ this.changeFilterState(isFiltered, index);}}&gt;\n &lt;CategoryImage isFiltered={isFiltered[index]} /&gt;\n &lt;/a&gt;\n &lt;span className=\"category1\"&gt;{index == 0 ? 'All' : category['Name']}&lt;/span&gt; \n&lt;/div&gt;\n</code></pre>\n\n<p>Smaller components are better for performance, because you get to pick and choose what should rerender and what should not. They are also much easier to reason.</p>\n\n<p>Note that <code>React.memo</code> isn't the silver bullet to all render problems and you have to split up components intelligently. <code>React.memo</code> does a shallow check, which means it's very good with primitives, like strings, booleans and numbers. Notice that the parts I pulled out into its own separate component only has a boolean as a prop. That was very intentional. <code>React.memo</code> can easily do a comparison and stop a rerender.</p>\n\n<p>Edit:\nApologies, I didn't notice that <code>this.handleScroll</code> is already an arrow function. You don't need to <code>bind</code> in that case. Here, all I did was remove the <code>bind</code> inside the click handler.</p>\n\n<pre><code>handleScroll = (e) =&gt; {\n const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;\n if (bottom) { \n this.setState({\n storiesLoaded: this.state.storiesLoaded + 25\n });\n }\n}\n\nrenderResults(Object, isVisible, commodityStates, languageStates, publishedStates) {\n if (isVisible){\n return (\n &lt;div className=\"search-result-master-container\"&gt;\n &lt;span className=\"section-header\"&gt;{Resources.Filter_By}&lt;/span&gt;\n &lt;span className=\"section-header\"&gt;{Object.length} {Resources.Results}:&lt;/span&gt;\n &lt;div id=\"filterBySideBar\"&gt;\n &lt;div className=\"horizontal-line-filter\"&gt;\n &lt;div&gt;{this.renderCategories(Object , commodityStates)}&lt;/div&gt;\n &lt;div&gt;{this.renderLanguage(Object , languageStates)}&lt;/div&gt;\n &lt;div&gt;{this.renderPublished(publishedStates)}&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div className=\"horizontal-line-stories-top\"/&gt;\n &lt;div className=\"scrollbar\" onScroll={this.handleScroll}&gt;\n &lt;div className=\"force-overflow\"&gt;\n {this.renderStories(Object)}\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div className=\"horizontal-line-stories-bottom\" /&gt;\n &lt;/div&gt; \n ); \n } \n}\n</code></pre>\n\n<p>But for a function with a callback, you can write it out to have the functions be double returns:</p>\n\n<pre><code>addNewBookmark = (userId, newsId, isBookmarked, bookmarkIndex) =&gt; () =&gt; {\n $.post('/webapi/newstestAddNewBookmark?userId=' + (userId), \n { \n UserID: userId,\n })\n .done(() =&gt; {\n this.changeBookmarkState(isBookmarked, bookmarkIndex);\n }\n}\n\nremoveBookmark = (userId, newsId, isBookmarked, bookmarkIndex) =&gt; () =&gt; {\n $.post('/webapi/test/RemoveBookmark?userId=' + (userId), {})\n .done(() =&gt; {\n this.changeBookmarkState(isBookmarked, bookmarkIndex);\n }\n}\n\nrenderBookmarkButton(userId, newsId, isBookmarked, bookmarkIndex) { \n return (\n &lt;a onClick={isBookmarked == false ? this.addNewBookmark(userId, newsId, isBookmarked, bookmarkIndex) : this.removeBookmark(userId, newsId, isBookmarked, bookmarkIndex)}&gt;\n &lt;img className={isBookmarked == false ? \"bookmark-button\" : \"bookmark-button bookmark-button-fill-color\"} src=\"/images/logo/Bookmark.svg\" /&gt;\n &lt;/a&gt;\n );\n}\n</code></pre>\n\n<p>Notice how I don't have <code>() =&gt;</code> inside the <code>onClick</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:55:31.757", "Id": "409522", "Score": "0", "body": "Hi, thanks for the answer.\nCould you provide me an example of the code with\nhandleScroll = () => {}\n<div className=\"scrollbar\" onScroll={this.handleScroll}>?\n\nI'm not sure how it should look like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T20:55:09.443", "Id": "409546", "Score": "0", "body": "Apologies, `handleScroll` isn't the best example because you already have it as an arrow function. I left the arguments off and the rest of the function's content blank. But if you truly need a complete version, I'll do that now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:01:30.467", "Id": "409547", "Score": "0", "body": "That being said, memoizing is far more effective for your purposes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:43:20.553", "Id": "409551", "Score": "0", "body": "thanks a lot my friend! I understand the () => part now. \nWhat does it mean with callback?\n\nI'm really interested in learning the memo method, but how can I adapt my code to work with it? I'm also not sure how I can split up my component into smaller parts, do you have any example? :) \n\nI really appreciate your help, since I feel like I learn a lot more from seeing how you think and solve this, rather than reading bad examples." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:53:25.750", "Id": "409553", "Score": "0", "body": "When you say split up into smaller component, do you mean const in same file, or many several files?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T22:28:13.330", "Id": "409557", "Score": "0", "body": "<a onClick={()=>{this.handleSearchButton; this.SearchNewsArchive()}}>\n\nand SearchNewsArchive = function () {\n\nIs there another way for me to write this? Do I need to bind in the SearchNewsArchive?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T22:51:51.933", "Id": "409558", "Score": "0", "body": "what defines a anonymous function? Should I do the arrow with double returns whenever I write a function that take arguments? And if there is no arguments, it is okay with just a single return?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T23:55:27.713", "Id": "211297", "ParentId": "211247", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T09:43:24.120", "Id": "211247", "Score": "1", "Tags": [ "performance", "react.js", "typescript" ], "Title": "Search Result with infinite scroll React component" }
211247
<p>I have a assignment to find which season has the biggest temperature amplitude. Input par is the <code>int</code> array with temperatures: </p> <pre><code>int T[]= {-1,-10,10,5,30,15,20,-10,30,10,29,20} </code></pre> <p>which means:</p> <pre class="lang-none prettyprint-override"><code>winter: -1,-10,10 spring: 5,30,15 summer: 20,-10,30 autumn: 10,29,20 </code></pre> <ul> <li><code>temp</code> is always an <code>int</code>, </li> <li><code>int[] T</code> - <code>T.length%4</code> is equal to 0 (same number of temperatures for every season, could be 2, 3 etc.)</li> </ul> <pre><code>{ public String solution(int[] T){ int length = T.length; int count = length/4; int i=0,j=0,indx=0; String name=""; int maxAmpl; int[] winter = new int[count]; int[] spring = new int[count]; int[] summer = new int[count]; int[] autumn = new int[count]; int[] diff = new int[4]; for(j=0,i=0;j&lt;count; j++,i++){ winter[i] = T[j]; } for(j=count,i=0;j&lt;count*2; j++,i++){ spring[i] = T[j]; } for(j=count*2,i=0;j&lt;count*3; j++,i++){ summer[i] = T[j]; } for(j=count*3,i=0;j&lt;count*4; j++,i++){ autumn[i] = T[j]; } Arrays.sort(winter); Arrays.sort(spring); Arrays.sort(summer); Arrays.sort(autumn); diff[0] = winter[count-1]-winter[0]; diff[1] = spring[count-1]-spring[0]; diff[2] = summer[count-1]-summer[0]; diff[3] = autumn[count-1]-autumn[0]; maxAmpl=diff[0]; for(int k=1; k&lt;4; k++){ if (diff[k]&gt;maxAmpl){ maxAmpl = diff[k]; indx = k; } } switch(indx){ case 0: name = "WINTER"; break; case 1: name = "SPRING"; break; case 2: name = "SUMMER"; break; case 3: name = "AUTUMN"; break; } return name; } </code></pre>
[]
[ { "body": "<p>Some key points:</p>\n\n<ul>\n<li>No need to sort the array to find min/max value</li>\n<li>No need to copy the array, can search in the original array using an offset <code>count * N</code></li>\n</ul>\n\n<p>Have a look at this:</p>\n\n<pre><code>public String solution(int[] T) {\n final int count = T.length / 4;\n int indx = 0;\n int last = Integer.MIN_VALUE;\n for (int i = 0; i &lt; 4; ++i) {\n int diff = IntStream.of(T).skip(count * i).limit(count).max().getAsInt()\n - IntStream.of(T).skip(count * i).limit(count).min().getAsInt();\n if (diff &gt; last) {\n indx = i;\n last = diff;\n }\n }\n final String[] seasons = { \"WINTER\", \"SPRING\", \"SUMMER\", \"AUTUMN\" };\n return seasons[indx];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T09:57:10.970", "Id": "211249", "ParentId": "211248", "Score": "2" } }, { "body": "<h3>Steps to solve this problem:</h3>\n<ul>\n<li>Get slice of array related to season</li>\n<li>Sort slice (we could use custom <code>for loop</code> to get min and max but sorting is quite similar in performance and takes one line instead of few)</li>\n<li>Get first and last value from sorted slice</li>\n<li>Calculate amplitude and save this result in Array or List</li>\n</ul>\n<h3>Example implementation (C#):</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Linq;\n\nnamespace application\n{\n class Program\n {\n static void Main(string[] args)\n { \n var T1 = new int[] { 13, 2, 3, 4, 1, 6, 11, 8, 2, 10, 11, 4 };\n var T2 = new int[] { 26, 2, 3, 4, 1, 6, 11, 33, 2, 10, 11, 4 };\n var T3 = new int[] { 13, 2, 3, 27, 1, 6, 11, 8, 2, 10, 11, 4 };\n var T4 = new int[] { 13, 2, 3, 4, 1, 6, 11, 8, 2, 10, 11, 33 };\n\n Console.WriteLine($&quot;Solution: {Solution(T1)}&quot;);\n Console.WriteLine($&quot;Solution: {Solution(T2)}&quot;);\n Console.WriteLine($&quot;Solution: {Solution(T3)}&quot;);\n Console.WriteLine($&quot;Solution: {Solution(T4)}&quot;);\n }\n\n static string Solution(int[] T)\n {\n const int numberOfSeasons = 4;\n int offset = T.Length / numberOfSeasons;\n var amplitudes = new int[numberOfSeasons];\n var seasons = new string[] { &quot;WINTER&quot;, &quot;SPRING&quot;, &quot;SUMMER&quot;, &quot;AUTUMN&quot; };\n for (int i = 0; i &lt; numberOfSeasons; i++)\n {\n var slice = new ArraySegment&lt;int&gt;(T, i * offset, offset).ToArray();\n Array.Sort(slice);\n var min = slice[0];\n var max = slice[slice.Length - 1];\n var amplitude = max - min;\n amplitudes[i] = amplitude;\n }\n var index = Array.IndexOf(amplitudes, amplitudes.Max());\n return seasons[index];\n }\n }\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>Solution: WINTER\nSolution: SUMMER\nSolution: SPRING\nSolution: AUTUMN\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T13:02:31.493", "Id": "533860", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T10:33:37.130", "Id": "270350", "ParentId": "211248", "Score": "1" } } ]
{ "AcceptedAnswerId": "211249", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T09:53:30.393", "Id": "211248", "Score": "2", "Tags": [ "java" ], "Title": "Search for the biggest amplitude in an array" }
211248
<p>I am testing my repository class:</p> <pre><code>interface AccountRepository{ void save(Account account); Optional&lt;Account&gt; findById(Long id); } </code></pre> <p>And when writing tests, I ended up with two semantically different tests, but they essentially contain exactly the same code:</p> <pre><code>@DisplayName("user exists -- account does not exist -- save persists") @Test void save_userExistsAccountDoesNotExist_persisted() { //arrange User existingUser = userRepo.save(new User("John", "Smith")); Account account = new Account(existingUser, null); //act repo.save(account); //assert assertThat(repo.findById(account.getId())).contains(account); } @DisplayName("user exists -- account exists -- findById finds") @Test void findById_userExistsAccountExists_found() { //arrange User existingUser = userRepo.save(new User("John", "Smith")); Account existingAccount = repo.save(new Account(existingUser, null)); //act &amp; assert assertThat(repo.findById(existingAccount.getId())).contains(existingAccount); } </code></pre> <p>I don't really want to remove one of them because that serves different purposes in my head but I am worried that I may have understood something wrong. </p>
[]
[ { "body": "<p>In my opinion, if you think that each test has a different meaning, there is nothing wrong with them.</p>\n\n<p>What you can do to extract the duplication is to have a dedicated method to arrange your test. But in this case there will be no real gain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:08:13.863", "Id": "408520", "Score": "0", "body": "@Sam, please consider accepting an answer if you have one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:24:39.567", "Id": "408521", "Score": "4", "body": "It's very reasonable to wait more than three hours to see if a better reply come in before accepting the first answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T11:31:49.587", "Id": "211255", "ParentId": "211250", "Score": "2" } }, { "body": "<p>One of the hardest piece of knowledge to learn as a developer is: <em>code duplication does not mean responsibility duplication</em>.</p>\n\n<p>Having said this, you are testing different methods so it's ok to have more than one test. In this case, you are testing complementary (or were they supplementary? I never remember it) methods, so to test one, you need to have the other one working properly. </p>\n\n<p>However, there are some code duplication that will bite you in the future (but since this question is from the past, you can tell me if I'm wrong or not).</p>\n\n<ol>\n<li>You are duplicating the way a User entity is created, so if you change its constructor, you will have to modify your tests, even though it might not matter in the actual logic you are testing. It happens something similar with the Account entity. To avoid this you can have a private method or to a public builder.</li>\n<li>You are duplicating the way a User is created and persisted. The same problem as in point #1 happens. You probably don't care how or when is created, you just need it to be created and persisted properly. This applies also for the Account entity with a slight different: in the first test you need to make the code of save into the repo explicit since it's what you are testing.</li>\n</ol>\n\n<p>Besides all of this, when you are writing tests you need to tell the reader what's important and what's not and describe that accordingly. It's a balance between explicitness and abstraction. For instance in the example, I've written a method called createAccount to encapsulate the logic of creation and persistence of the Account entity. However, someone would say that if a developer reading the test needs to know what the arrange does, it has to move to the method implementation (a test should be self-explanatory and auto).</p>\n\n<pre><code>@DisplayName(\"user exists -- account does not exist -- save persists\")\n@Test\nvoid save_userExistsAndAccountDoesNotExist_accountIsSaved() {\n // Arrange\n User existingUser = createUser();\n Account createdAccount = makeAccount(existingUser);\n\n // Act\n repo.save(createdAccount);\n\n // Assert\n assertThat(repo.findById(createdAccount.getId())).contains(createdAccount);\n}\n\n@DisplayName(\"user exists -- account exists -- findById finds\")\n@Test\nvoid findById_userExistsAndAccountExists_returnTheAccount() {\n // Arrange\n User existingUser = createUser();\n Account existingAccount = createAccount(existingUser);\n\n // Act\n Optional&lt;Account&gt; foundAccount = repo.findById(existingAccount.getId());\n\n // Assert\n assertThat(foundAccount).contains(existingAccount);\n}\n\nprivate User createUser(){\n return userRepo.save(new User(\"John\", \"Smith\")); \n}\n\nprivate Account createAccount(User existingUser){\n return repo.save(makeAccount(existingUser));\n}\n\nprivate Account makeAccount(User user){\n new Account(user, null);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T08:53:46.773", "Id": "426425", "Score": "0", "body": "I don't get point #2. Isn't it more readable if you call the repositories in the tests? Let's just have `createUser` and `createAccount` and then explicitly call repositories if we need to" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T13:11:50.083", "Id": "426472", "Score": "1", "body": "That was exactly what I was trying to explain the following paragraph: you have to find the balance between duplication, coupling, expressiveness, conciseness... It also depends on the business, the project, the team, the language..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:57:13.653", "Id": "220679", "ParentId": "211250", "Score": "3" } } ]
{ "AcceptedAnswerId": "211255", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T10:08:41.617", "Id": "211250", "Score": "1", "Tags": [ "java", "unit-testing", "junit", "bdd" ], "Title": "Two BDD unit tests for an account repository with identical code" }
211250
<p>I'm trying to model a tournament with Python (Django) and I've got a function that assigns teams of the previous stage to the groups of the new one. The teams in the first stage are assigned manually.</p> <p>Every Stage have OneToOneRel to the previous Stage. Team model is related to the Group through Score model, that has ForeignKeyRel with both Team and Group and store every score too.</p> <p>The code down here is working but I really think he is not the best way to do it (especially the while loop).</p> <pre><code>def update_groups(request): if request.method == 'POST': stage = Stage.objects.get(id=request.POST.get('stage_id')) if stage.protected: return redirect('master_area:home') current_groups = [] precedent_groups = [] leader_boards = [] temp = [] rank = [] for group in stage.precedent_stage.groups.all(): leader_board = [] for score in group.scores.all(): leader_board.append(score) leader_board.sort(key=lambda x: x.score, reverse=True) # sort best in group leader_boards.append(leader_board) leader_boards = [list(filter(None, i)) for i in zip_longest(*leader_boards)] # transpose leader_boards for leader_board in leader_boards: leader_board.sort(key=lambda x: x.score, reverse=True) # sort best firsts, seconds... for score in leader_board: temp.append(score) temp.sort(key=lambda x: x.group.importance, reverse=True) # sort for the importance of the previous group for score in temp: rank.append(score.team) for group in stage.groups.all(): current_groups.append(group) current_groups.sort(key=lambda x: x.importance, reverse=True) i = 0 t = 1 while len(rank) and len(current_groups): if len(current_groups[i].scores.all()) &lt; current_groups[i].number_of_teams: Score.objects.get_or_create(team=rank[0], group=current_groups[i]) rank.pop(0) if i+t &lt; 0 or i+t &gt;= len(current_groups) or current_groups[i+t].importance is not current_groups[i].importance: t = -1 if t == 1 else 1 if len(current_groups[i].scores.all()) == current_groups[i].number_of_teams: rem = current_groups[i].importance current_groups.pop(i) if t == 1: i -= 1 elif i &lt; len(current_groups) and rem is not current_groups[i].importance: t = 1 elif len(current_groups) == 1: i=0 else: i += t if len(current_groups[i].scores.all()) &gt;= current_groups[i].number_of_teams: current_groups.pop(i) if t == 1: i -= 1 return redirect('master_area:home') </code></pre> <p>Here my models:</p> <pre><code>class Team(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True, related_name='teams') name = models.CharField(max_length=24) short_name = models.CharField(max_length=12, blank=True) city = models.CharField(max_length=36, blank=True) slug = models.SlugField(blank=True) class Tournament(models.Model): year = models.CharField(max_length=99) title = models.CharField(max_length=99, blank=True) slug = models.SlugField(blank=True) active = models.BooleanField(default=False) class Stage(models.Model): # Fase name = models.CharField(max_length=16, blank=True) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, related_name='stages') precedent_stage = models.OneToOneField('self', on_delete=models.SET_NULL, blank=True, null=True, related_name='next_stage') protected = models.BooleanField(default=False) class Group(models.Model): # Girone name = models.CharField(max_length=16, blank=True) FORMAT_TYPES = (('Round-Robin', "All'italiana"), ('Elimination', 'Ad eliminazione')) stage = models.ForeignKey(Stage, on_delete=models.CASCADE, related_name='groups') format = models.CharField(max_length=32, choices=FORMAT_TYPES, default='Round-Robin') number_of_teams = models.IntegerField(validators=[MinValueValidator(0)], default=0) importance = models.IntegerField(validators=[MinValueValidator(0)], default=0) class Score(models.Model): # Punteggio team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='scores') group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, related_name='scores') score = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) games_played = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) wins = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) losses = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) points_made = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) points_conceded = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) goals_made = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) goals_conceded = models.IntegerField(validators=[MinValueValidator(0)], blank=True, null=True, default=0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T23:43:57.483", "Id": "408587", "Score": "2", "body": "@MathiasEttinger Thanks, it was `temp.sort(....`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T22:38:41.270", "Id": "412432", "Score": "0", "body": "Without having an understanding of how new groups are generated, it's honestly very difficult to review this code. I took a shot at it and gave up once I realized I was going to need to draw a few diagrams for myself." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T11:31:41.457", "Id": "211254", "Score": "2", "Tags": [ "python", "performance", "sorting", "django" ], "Title": "Generate automatically new groups in a tournament" }
211254
<p>I have a function that looks up in a <code>list</code> the elements which share same values in order to group them.</p> <p>As a fast summary, this should be the input/output:</p> <blockquote> <p>[A, A', B, C, B', A''] --> [[A, A', A''], [B, B'], [C]]</p> </blockquote> <p>I do not care about order. It could also produce:</p> <blockquote> <p>[A, A', B, C, B', A''] --> [[B, B'], [A, A', A''], [C]]</p> </blockquote> <p>This is my test code to see the output samples:</p> <blockquote> <pre><code>class A { private Long id; private String name; private Object param; A(Long id, String name, Object param) { this.id = id; this.name = name; this.param = param; } @Override public String toString() { return "{\tid:" + id + ",\tname:" + name + ",\tparam:" + param + "}"; } } public class ListsTest { private final A a1 = new A(1L, "A", 100); private final A a2 = new A(2L, "B", 200); private final A a3 = new A(1L, "A", 300); private final A a4 = new A(1L, "B", 400); @Test public void groupByIdAndName() throws IllegalAccessException, NoSuchFieldException { List&lt;A&gt; aList = List.of(a1, a2, a3, a4); System.out.println("groupByIdAndName"); System.out.println("Input: ---&gt; " + aList); List&lt;List&lt;A&gt;&gt; aGroupedBy = Lists.groupByFields(aList, "id", "name"); System.out.println("Output: --&gt; " + aGroupedBy); System.out.println("------------------------------------------------------------------------"); assertThat(aGroupedBy, is(List.of(List.of(a1, a3), List.of(a2), List.of(a4)))); } @Test public void groupById() throws IllegalAccessException, NoSuchFieldException { List&lt;A&gt; aList = List.of(a1, a2, a3, a4); System.out.println("groupById"); System.out.println("Input: ---&gt; " + aList); List&lt;List&lt;A&gt;&gt; aGroupedBy = Lists.groupByFields(aList, "id"); System.out.println("Output: --&gt; " + aGroupedBy); System.out.println("------------------------------------------------------------------------"); assertThat(aGroupedBy, is(List.of(List.of(a1, a3, a4), List.of(a2)))); } @Test public void groupByName() throws IllegalAccessException, NoSuchFieldException { List&lt;A&gt; aList = List.of(a1, a2, a3, a4); System.out.println("groupByName"); System.out.println("Input: ---&gt; " + aList); List&lt;List&lt;A&gt;&gt; aGroupedBy = Lists.groupByFields(aList, "name"); System.out.println("Output: --&gt; " + aGroupedBy); System.out.println("------------------------------------------------------------------------"); assertThat(aGroupedBy, is(List.of(List.of(a1, a3), List.of(a2, a4)))); } } </code></pre> </blockquote> <p>Which outputs:</p> <blockquote> <p>groupById</p> <p>Input: ---> [{ id:1, name:A, param:100}, { id:2, name:B, param:200}, { id:1, name:A, param:300}, { id:1, name:B, param:400}] Output: --> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}], [{ id:2, name:B, param:200}], [{ id:1, name:B, param:400}]]</p> <p>Output: --> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}, { id:1, name:B, param:400}], [{ id:2, name:B, param:200}]]</p> <hr> <p>groupByIdAndName</p> <p>Input: ---> [{ id:1, name:A, param:100}, { id:2, name:B, param:200}, { id:1, name:A, param:300}, { id:1, name:B, param:400}]</p> <p>Output: --> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}], [{ id:2, name:B, param:200}], [{ id:1, name:B, param:400}]]</p> <hr> <p>groupByName</p> <p>Input: ---> [{ id:1, name:A, param:100}, { id:2, name:B, param:200}, { id:1, name:A, param:300}, { id:1, name:B, param:400}]</p> <p>Output: --> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}], [{ id:2, name:B, param:200}, { id:1, name:B, param:400}]]</p> <hr> </blockquote> <p>The code I developed for it is the following:</p> <pre><code>public class Lists { private static &lt;T&gt; Object getObjectFieldsHash(T obj, String... fields) throws NoSuchFieldException, IllegalAccessException { List&lt;Object&gt; vals = new ArrayList&lt;&gt;(); for (String field: fields) { Field f = obj.getClass().getDeclaredField(field); f.setAccessible(true); vals.add(f.get(obj)); } return Objects.hash(vals); } public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; groupByFields(List&lt;T&gt; objects, String... fields ) throws NoSuchFieldException, IllegalAccessException { List&lt;List&lt;T&gt;&gt; result = new ArrayList&lt;&gt;(); // Is it possible to create same type of original List instead of always ArrayList? Map&lt;Object, Integer&gt; indexes = new HashMap&lt;&gt;(); for (T obj: objects) { Object hash = getObjectFieldsHash(obj, fields); indexes.computeIfAbsent(hash, (_unused) -&gt; indexes.size()); // How can I remove _unused variable? Integer nextIndex = indexes.get(hash); if (nextIndex &gt;= result.size()) { // Maybe I could use ==. Does it improve anything? result.add(new ArrayList&lt;T&gt;()); // Is it possible to create same type of original List instead of always ArrayList? } result.get(nextIndex).add(obj); } return result; } } </code></pre> <p>Is there any way to improve this?</p> <p>I'm thinking of:</p> <ol> <li>I can pass as argument any subtype of <code>List</code>, but I'm always returning <code>ArrayList</code>s.</li> <li>I was forced to declare the <code>_unused</code> variable in my <code>lambda function</code>, or won't compile, producing error: "Cannot infer functional interface type".</li> <li>Does using <code>==</code> instead of <code>&gt;=</code> to check if I already created a sublist provide me any kind of improvement?</li> <li>I named this method <code>groupByFields</code>, but I feel like is the opposite of "flatMap" kind functions. Is there any concept which gives me a more standarized method name?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T10:44:34.267", "Id": "408620", "Score": "1", "body": "Prefer method-references over reflection." } ]
[ { "body": "<p><code>object</code> is easier to read than <code>obj</code>. <code>values</code> is easier to read than <code>vals</code>. Avoid unnecessary abbreviations.</p>\n\n<p>Don’t give things misleading names. You’re calling something a <code>field</code> when it’s really a <code>fieldName</code>.</p>\n\n<p>Using a <code>Map</code> in <code>groupByFields</code> is a good idea, but you’re making it a lot harder than it needs to be by sticking everything in a list right away. Just keep the hash as the key and a set of objects as the value. </p>\n\n<p>There’s a good chance this is a big performance sink because of how much reflection you’re doing. Rather than reflect on every instance of every object, just do the reflection work once.</p>\n\n<p>Your <code>getObjectsFieldHash</code> method is finding the has of a List of values, rather than on the actual values. Is that intentional?</p>\n\n<p>To answer your questions,</p>\n\n<blockquote>\n <p>Is it possible to create same type of original List instead of always ArrayList?</p>\n</blockquote>\n\n<p>Yes, but why? This method should be a lot more generic - it can handle arbitrary collections unless you need your grouping function to be stable. You should be doing most of your work behind the Collections API interfaces. If you really need a specific concrete type yourself, it's preferable to make that type and dump the existing collection into it via a constructor. That will copy all the members over.</p>\n\n<blockquote>\n <p>How can I remove _unused variable?</p>\n</blockquote>\n\n<p>You can’t. <code>computeIfAbsent</code> requires a function that takes in a key.</p>\n\n<blockquote>\n <p>Maybe I could use ==. Does it improve anything? </p>\n</blockquote>\n\n<p>It might affect performance in some trivial way, but you’re better off refactoring the code to be easier to read.</p>\n\n<blockquote>\n <p>Is it possible to create same type of original List instead of always ArrayList?</p>\n</blockquote>\n\n<p>See above</p>\n\n<p>So, if you're OK with using what I think are more appropriate collections than lists, you can try:</p>\n\n<pre><code>public static &lt;T&gt; Collection&lt;Set&lt;T&gt;&gt; groupByFields(\n final Class&lt;T&gt; objectClazz,\n final Collection&lt;T&gt; objects,\n final String... fieldNames)\n throws NoSuchFieldException, IllegalAccessException {\n\n final Field[] fields = fieldsFor(objectClazz, fieldNames);\n final Map&lt;Integer, Set&lt;T&gt;&gt; groupings = new HashMap&lt;&gt;();\n for (final T object : objects) {\n final int hash = hashOf(object, fields);\n groupings.computeIfAbsent(hash, k -&gt; new HashSet&lt;T&gt;()).add(object);\n }\n\n return groupings.values();\n}\n</code></pre>\n\n<p>If you feel strongly about lists, but don't have a really good reason to require specific list types, try:</p>\n\n<pre><code>public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; groupByFields(\n final List&lt;T&gt; objects,\n final String... fieldNames)\n throws NoSuchFieldException, IllegalAccessException {\n\n final Field[] fields = fieldsFor(objects.get(0).getClass(), fieldNames);\n final Map&lt;Integer, List&lt;T&gt;&gt; groupings = new HashMap&lt;&gt;();\n for (final T object : objects) {\n final int hash = hashOf(object, fields);\n groupings.computeIfAbsent(hash, k -&gt; new ArrayList&lt;T&gt;()).add(object);\n }\n\n return new ArrayList&lt;&gt;(groupings.values());\n}\n</code></pre>\n\n<p>And if you feel really strongly about controlling the types of lists being used, you can use:</p>\n\n<pre><code>public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; groupByFields(\n final Class&lt;? extends List&lt;T&gt;&gt; listClazz,\n final Class&lt;? extends List&lt;List&lt;T&gt;&gt;&gt; listOfListsClazz,\n final List&lt;T&gt; objects,\n final String... fieldNames)\n throws NoSuchFieldException, IllegalAccessException, InstantiationException {\n\n final Field[] fields = fieldsFor(objects.get(0).getClass(), fieldNames);\n final Map&lt;Integer, List&lt;T&gt;&gt; groupings = new HashMap&lt;&gt;();\n for (final T object : objects) {\n final int hash = hashOf(object, fields);\n groupings.computeIfAbsent(hash, k -&gt; {\n try {\n return listClazz.newInstance();\n } catch (IllegalAccessException | InstantiationException e) {\n throw new IllegalStateException(\"Cannot instantiate a new instance of \" + listClazz.getCanonicalName());\n }\n })\n .add(object);\n\n }\n\n final List&lt;List&lt;T&gt;&gt; result = listOfListsClazz.newInstance();\n result.addAll(groupings.values());\n return result;\n}\n</code></pre>\n\n<p>All three top-level methods use the same two helpers:</p>\n\n<pre><code>private static final &lt;T&gt; Field[] fieldsFor(final Class&lt;T&gt; clazz, final String[] fieldNames)\n throws NoSuchFieldException {\n\n final Field[] fields = new Field[fieldNames.length];\n for (int i = 0; i &lt; fieldNames.length; i++) {\n final Field field = clazz.getDeclaredField(fieldNames[i]);\n field.setAccessible(true);\n fields[i] = field;\n }\n\n return fields;\n}\n\nprivate static final &lt;T&gt; Integer hashOf(final T object, final Field... fields)\n throws IllegalAccessException {\n\n final Object[] values = new Object[fields.length];\n for (int i = 0; i &lt; values.length; i++) {\n values[i] = fields[i].get(object);\n }\n return Objects.hash(values);\n}\n</code></pre>\n\n<p>Finally, note that I do agree with <code>RobAu</code> that avoiding reflection would be better, but we don't have enough context to consider alternatives.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:47:28.740", "Id": "211345", "ParentId": "211257", "Score": "1" } } ]
{ "AcceptedAnswerId": "211345", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T12:35:33.510", "Id": "211257", "Score": "2", "Tags": [ "java", "performance", "memory-optimization" ], "Title": "Grouping items in a list into inner lists" }
211257
<p>I have a "GetPersonsPerDepartment()" method returning a <code>IQueryable&lt;IEnumerable&lt;Person&gt;&gt;</code> while I'm trying to get a simple <code>List&lt;Person&gt;</code> or <code>IEnumerable&lt;Person&gt;</code> with all the persons from every department. I wrote a simple method GetAllPersons() that solves this with a loop but I feel I must be missing a simple command to get the same result: </p> <pre><code>private List&lt;Person&gt; GetAllPersons() { List&lt;Person&gt; allPersons = new List&lt;Person&gt;(); foreach(var Persons in GetPersonsPerDepartment()) { allPersons.AddRange(Persons); } return allPersons; } private IQueryable&lt;IEnumerable&lt;Person&gt;&gt; GetPersonsPerDepartment() { IQueryable&lt;IEnumerable&lt;Person&gt;&gt; Persons; using (var context = MySource.GetPersonsContext()) { var library = "Personlist"; var PersonFolderList = context.Web.Lists.GetByTitle(library); context.Load&lt;List&gt;(PersonFolderList); var PersonFolderListItems = PersonFolderList.GetItems(new CamlQuery()); context.Load&lt;ListItemCollection&gt;(PersonFolderListItems); context.ExecuteQuery(); Persons = PersonFolderListItems.Where(x =&gt; x.FileSystemObjectType == FileSystemObjectType.Folder).Select(x =&gt; GetPersonsFromFolderListItem(x, context, PersonFolderList)); } return Persons; } </code></pre>
[]
[ { "body": "<p>Use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?redirectedfrom=MSDN&amp;view=netframework-4.7.2#System_Linq_Enumerable_SelectMany__2_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Collections_Generic_IEnumerable___1___\" rel=\"noreferrer\"><code>SelectMany</code></a>. As in, <code>allPersons.SelectMany(s =&gt; s);</code>. This flattens the sequence for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T13:28:52.260", "Id": "408510", "Score": "11", "body": "Not only one-liner code but also a one-liner review - there should be a badge for it ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:48:04.067", "Id": "408524", "Score": "4", "body": "There seems to be :). The +10 answer badge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T02:03:57.077", "Id": "408593", "Score": "1", "body": "While correct, I find `SelectMany(s => s)` does not really convey the \"concatenate all of these together\" meaning very well. If you're not a heavy LINQ user, it's going to confuse you initially. (I've had coworkers be confused by it.) One might consider wrapping this inside a method: `public static ConcatAll<T>(this IEnumerable<IEnumerable<T>> e) { return e.SelectMany(i = i); }`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T14:30:10.473", "Id": "408725", "Score": "1", "body": "@jpmc26 _I've had coworkers be confused by it_ - then they either should learn how to use LINQ correctly or leave writing software to people who can understand something as simple as `SelectMany`.. Creating extensions like `ConcatAll` is even more confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T17:54:43.573", "Id": "408735", "Score": "0", "body": "@t3chb0t Giving things appropriate, straightforward names that clearly communicates their behavior increases confusion? *Wat.* The best kind of code is code that can be understood at a glance. There is absolutely nothing wrong with being clear enough that other people understand something immediately. Honestly, we'd all be better off if the .NET standard library was written with that mindset. How did you get 34k rep on a code review site thinking like that?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T13:24:08.103", "Id": "211259", "ParentId": "211258", "Score": "23" } }, { "body": "<h3>Is this a bug or dirty workaround?</h3>\n<p>There is one thing in your code that sooner or later will bite you and I don't quite understnd why it didn't...</p>\n<p>You're returing an <code>IQueryable&lt;IEnumerable&lt;Person&gt;&gt;</code> after you have disposed your <code>context</code>. I'm not sure what workarounds your are using there because you provided very little context but your code actually shouldn't work.</p>\n<p>I suppose it's Entity Framework and with it you should never return <code>IQuerybale</code> if you're disposing its context by the same method but always materialize the query before returnig the result, e.g. with <code>ToList</code> etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:29:30.253", "Id": "408549", "Score": "0", "body": "Returning an `IQueryable` is a perfectly valid strategy with EF--it won't actually do the query until you materialize it, and it allows other parts of the code to add additional filters/tranformations to the data that will be executed on the DB, making it more performant. Of course, this only works in certain cases where you get the context when you need it, instead of being in a `using` block (like if you are working from an `IGenericRepository` type thing)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:34:58.533", "Id": "408550", "Score": "2", "body": "@Hosch250 I know how it works and clarified what I meant ;-] OP does have a `using` block here thus it's super confusing why it actually works... it shouldn't and IMO there is some _dirty_ workaround becuase if it's materialized then it shouldn't be an `IQueryable` and if it's not then the context should not be disposed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T18:52:50.823", "Id": "211280", "ParentId": "211258", "Score": "3" } } ]
{ "AcceptedAnswerId": "211259", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T13:19:38.943", "Id": "211258", "Score": "5", "Tags": [ "c#", "beginner", ".net", "linq", "collections" ], "Title": "Going from IQueryable<IEnumerable<myObj>> to IEnumerable<myObj>" }
211258
<p>I developed a maze navigator in Java for a project for my school. It works fine, and it gets through the maze just fine. The program prints to the screen each time it loops through the maze to set the next position. Note: there is only one path because I haven't implemented a multiple path algorithm yet. Is there any way to make this more elegant/efficient? The main things I'm looking to reduce are (if possible):</p> <ul> <li>Switch/Case Statements</li> <li>Memory (re-printing to the screen each time)</li> <li>Code Improvements that made the program more efficient/elegant</li> </ul> <p>Any and all suggestions/improvements are welcome.</p> <pre><code>public class MazeAI { //maze layout below static int[][] maze = {{1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1,1,0,1,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1}, {1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,1,1,1,1,0,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1}, {1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,0,0,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1}, {1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1}, {1,1,0,0,0,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,1}, {1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1}, {1,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1}, {1,1,1,0,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1}, {1,1,1,1,1,0,0,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, }; public static void main() { MazeAI m = new MazeAI(); m.runAI(23,11); //where S is } void printMaze() { System.out.println(" MAZE "); System.out.println(); for(int i = 0; i &lt; maze.length; i++) { String output = ""; for(int j = 0; j &lt; 50; j++) { switch(maze[i][j]) { case 0: output += " "; break; case 1: output += "@"; break; case 2: output += "S"; break; case 3: output += "E"; break; } } System.out.println(output); } System.out.println(); } void printPath(int[][] array, boolean last) { System.out.println(" PATH "); System.out.println(); if(last) { array[1][1] = 4; } for(int i = 0; i &lt; array.length; i++) { String output = ""; for(int j = 0; j &lt; 50; j++) { switch(array[i][j]) { case 0: output += " "; break; case 1: output += "@"; break; case 2: output += "S"; break; case 3: output += "E"; break; case 4: output += "^"; break; case 5: output += "v"; break; case 6: output += "&lt;"; break; case 7: output += "&gt;"; break; } } System.out.println(output); } System.out.println(); } void runAI(int i, int j) { //S is at (i,j) -&gt; (9,11) | E is at (0,1) try { printMaze(); Thread.sleep(3000); System.out.print('\f'); } catch (Exception e) { e.printStackTrace(); } int[][] arr = maze; int[] currentPos = {i,j}; boolean running = true; while(running) { if(foundEnd(currentPos)) { running = false; printPath(arr, true); break; } if(canMoveUp(arr, currentPos)) { arr[currentPos[0]][currentPos[1]] = 4; currentPos[0] -= 1; } else if(canMoveDown(arr, currentPos)) { arr[currentPos[0]][currentPos[1]] = 5; currentPos[0] += 1; } else if(canMoveLeft(arr, currentPos)) { arr[currentPos[0]][currentPos[1]] = 6; currentPos[1] -= 1; } else if(canMoveRight(arr, currentPos)) { arr[currentPos[0]][currentPos[1]] = 7; currentPos[1] += 1; } printPath(arr, false); try { Thread.sleep(150); } catch (Exception e) { e.printStackTrace(); } System.out.print('\f'); } } boolean canMoveUp(int[][] arr, int[] pos) { try { if(arr[pos[0] - 1][pos[1]] == 0) { return true; } else { return false; } } catch (java.lang.ArrayIndexOutOfBoundsException e) { return false; } } boolean canMoveDown(int[][] arr, int[] pos) { try { if(arr[pos[0] + 1][pos[1]] == 0) { return true; } else { return false; } } catch (java.lang.ArrayIndexOutOfBoundsException e) { return false; } } boolean canMoveRight(int[][] arr, int[] pos) { try { if(arr[pos[0]][pos[1] + 1] == 0) { return true; } else { return false; } } catch (java.lang.ArrayIndexOutOfBoundsException e) { return false; } } boolean canMoveLeft(int[][] arr, int[] pos) { try { if(arr[pos[0]][pos[1] - 1] == 0) { return true; } else { return false; } } catch (java.lang.ArrayIndexOutOfBoundsException e) { return false; } } boolean foundEnd(int[] pos) { if(pos[0] == 1 &amp;&amp; pos[1] == 1) { return true; } else { return false; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T17:12:11.340", "Id": "408533", "Score": "0", "body": "You know about genetic algorithms?" } ]
[ { "body": "<p>Good job so far! I got some remarks, hopefully you'll find them useful.</p>\n\n<h2>Try Different Algorithms :)</h2>\n\n<p>See this nice Wikipedia entry for a list of possible algorithms to solve a maze:</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Maze_solving_algorithm\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Maze_solving_algorithm</a></p>\n\n<h2>Reuse code</h2>\n\n<p>This switch block appears 1.5 times in your code. Consider making it a method. </p>\n\n<pre><code> case 0: output += \" \"; break;\n case 1: output += \"@\"; break;\n case 2: output += \"S\"; break;\n case 3: output += \"E\"; break;\n case 4: output += \"^\"; break;\n case 5: output += \"v\"; break;\n case 6: output += \"&lt;\"; break;\n case 7: output += \"&gt;\"; break;\n</code></pre>\n\n<h2>Remove unnecessary code</h2>\n\n<p>You use this:</p>\n\n<pre><code> if(arr[pos[0]][pos[1] - 1] == 0) {\n return true;\n } else {\n return false;\n }\n</code></pre>\n\n<p>Which can be re-written to: </p>\n\n<pre><code> return arr[pos[0]][pos[1] - 1] == 0;\n</code></pre>\n\n<p>Which is much clearer to me :)</p>\n\n<h2>AIOOBE vs bounds check</h2>\n\n<p>You currently let the <code>canMove</code> throw an <code>ArrayIndexOutOfBoundsException</code>. Some consider this bad practice, because this is 'normal' flow. You should check before if your indices are valid.</p>\n\n<h2>String concatenation</h2>\n\n<p>Try to prevent String concatenation by using the <code>+</code> operator. It creates many unnecessary intermediate objects.</p>\n\n<p>See also here: <a href=\"https://redfin.engineering/java-string-concatenation-which-way-is-best-8f590a7d22a8\" rel=\"nofollow noreferrer\">https://redfin.engineering/java-string-concatenation-which-way-is-best-8f590a7d22a8</a></p>\n\n<h2>Consider using char directly</h2>\n\n<p>Your memory-model model is an <code>int[][]</code>. Your code uses 'magic values' that test <code>int</code> values. <code>char</code> is also well-suited to use as values in your grid, and you can then directly print and test these <code>char</code> values. Constructing the grid can start from a list of <code>Strings</code> with <code>toCharArray()</code> and your maze in code looks exactly like the output on the console</p>\n\n<p>(Or else, at least create readable constants for the <code>int</code>s in the <code>if</code> statements)</p>\n\n<h2>Consider coding the directions in an enum :</h2>\n\n<pre><code>enum Direction {\n UP(0,-1), LEFT(-1,0), RIGHT(1,0), DOWN(0,1);\n\n int dx;\n int dy;\n\n Direction(dx, dy)\n {\n this.dx=dx;\n this.dy=dy;\n }\n}\n\nfor (Direction d : Direction.values())\n{\n if (canMove(arr, currentPos, direction))\n {\n markMove(arr, currentPos, direction);\n }\n}\n</code></pre>\n\n<p>Something like this:</p>\n\n<pre><code> boolean canMove(int[][] arr, int[] pos, Direction d) {\n try {\n return arr[pos[0] + d.dx][pos[1] + d.dy] == 0\n } catch (java.lang.ArrayIndexOutOfBoundsException e) {\n return false;\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T07:47:18.883", "Id": "211308", "ParentId": "211261", "Score": "2" } } ]
{ "AcceptedAnswerId": "211308", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:04:59.553", "Id": "211261", "Score": "3", "Tags": [ "java", "homework", "pathfinding" ], "Title": "Maze navigator AI" }
211261
<p>I joined this 2 tables and dropped the user_id afterwards. I am defining the user_id elsewhere in my code based on my session/cookies and I do not want to return this value as a global. Is there a more compact or elegant way to write this:</p> <pre><code>public function test($user_id) { $stmt = $this-&gt;conn-&gt;prepare("CREATE TEMPORARY TABLE `temp_tb` SELECT a.*, b.token FROM $this-&gt;tableName a LEFT JOIN `requests` b ON a.$this-&gt;user_id = b.uid WHERE $this-&gt;user_id=:user_id "); $stmt-&gt;execute(array(":user_id"=&gt;$user_id)); $stmt = $this-&gt;conn-&gt;prepare("ALTER TABLE `temp_tb` DROP $this-&gt;user_id "); $stmt-&gt;execute(); $stmt = $this-&gt;conn-&gt;prepare("SELECT * FROM `temp_tb` "); $stmt-&gt;execute(); return $stmt-&gt;fetch(PDO::FETCH_ASSOC); } </code></pre> <p>Thank you!</p>
[]
[ { "body": "<p>Well, I hardly understand the whole affair but from what I can get about it</p>\n\n<pre><code>$sql = \"SELECT a.*, b.token FROM $this-&gt;tableName a\n LEFT JOIN `requests` b ON a.$this-&gt;user_id = b.uid\n WHERE $this-&gt;user_id=:user_id\";\n$this-&gt;conn-&gt;prepare($sql);\n$stmt-&gt;execute(array(\":user_id\"=&gt;$user_id));\n$row = $stmt-&gt;fetch(PDO::FETCH_ASSOC);\nunset($row[$this-&gt;user_id]);\nreturn $row;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:50:40.697", "Id": "408517", "Score": "0", "body": "This is a testing ground for me. I am defining the Cookie to regenerate each time someone logs in with it, plus the cookies have to match the IP it was initially created on. Never the less, I can also define this through the session to tell the database which user_id to fetch. The test function only gets some basic information about the user that will be used to populate the index page after the login has taken place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:31:21.800", "Id": "211264", "ParentId": "211263", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:13:25.717", "Id": "211263", "Score": "0", "Tags": [ "php", "pdo" ], "Title": "PDO multiple queries with 2 different tables" }
211263
<p>For a school project, I had to make a keylistener that would output whatever you typed to the screen. A JFrame would be initialized to have the focus required for the listener to work. It uses delete and shift methods to determine what to type/delete. Is there any way to make this more efficient, since I have two methods that I don't use and just take up space? Any and all help is appreciated!</p> <pre><code>import javax.swing.*; import java.awt.event.*; public class KeyHandler implements KeyListener { /* * KEY FUNCTIONS: * k.getKeyCode() returns ascii number * k.getKeyChar() returns char typed * * KEY CODES: * [delete] 8 * [shift] 16 */ private String output; public KeyHandler() { this.output = ""; } public void keyPressed(KeyEvent k) { if(k.getKeyCode() != 8) { if(k.getKeyCode() != 16) { this.output += k.getKeyChar(); } } else { if(this.output.length() - 1 &lt; 0) { //do nothing } else { this.output = this.output.substring(0,this.output.length() - 1); } } this.print(); } public void keyReleased(KeyEvent k) {} public void keyTyped(KeyEvent k) {} public void print() { System.out.print('\f'); //clear screen in BlueJ System.out.println(this.output); } public static void main(String[] args) { JFrame frame = new JFrame("KeyEvent Handler"); frame.setSize(400,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener(new KeyHandler()); frame.setVisible(true); } } </code></pre>
[]
[ { "body": "<p>Unless you intend (and have carefully designed) for your KeyHandler to be extended, you should make it <code>final</code>.</p>\n\n<p>If you <code>extend KeyAdapter</code> instead of <code>implements KeyListener</code>, you won’t have to implement <code>keyReleased</code> and <code>keyTyped</code>. The <code>Adapter</code> classes in Swing provide empty implementations of all the methods on the interface they implement, so you can just override the ones you care about.</p>\n\n<p>Don’t use int values to represent more complex concepts - those are called “magic numbers”. In this case, just use the constants defined on <code>KeyEvent</code>, namely <code>KeyEvent.VK_BACK_SPACE</code> and <code>KeyEvent.VK_SHIFT</code>.</p>\n\n<p>Put whitespace in between <code>if</code> and <code>(</code>. This visually differentiates control flow keywords from method names. Put whitespace after a <code>,</code> also, to make it easer to separate method arguments visually.</p>\n\n<p>In <code>keyPressed</code>, you don’t need to declare nested <code>if</code> statements. Prefer <code>&amp;&amp;</code>.</p>\n\n<p>Since <code>String</code> is immutable, a <code>StringBuilder</code> is preferred when doing String manipulation. You might not have covered that in class yet. It might be cleaner to use a <code>switch</code> statement on the value of the </p>\n\n<p>It’s probably overkill to have a separate method for printing in this case.</p>\n\n<p>You can clean up your logic by reversing the <code>this.output.length() - 1 &lt; 0</code> to be <code>this.output.length() &gt; 1</code> and getting rid of the empty clause. </p>\n\n<p>Note that you’re deleting a character when the shift key gets pressed. Also, no matter how many times shift or delete are pressed, you’re not deleting the first character. These are both probably bugs.</p>\n\n<p>You can just declare the initial value of <code>output</code> when you declare the variable. You don’t need a separate line in the constructor for that.</p>\n\n<p>If you were to implement all my suggestions, your code might look more like:</p>\n\n<pre><code>import java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\n\nimport javax.swing.JFrame;\n\npublic final class KeyHandler extends KeyAdapter {\n\n private String output = \"\";\n //private final StringBuilder stringBuilder = new StringBuilder();\n\n public KeyHandler() {\n super();\n }\n\n @Override\n public void keyPressed(final KeyEvent k) {\n if ((k.getKeyCode() != KeyEvent.VK_BACK_SPACE) &amp;&amp; (k.getKeyCode() != KeyEvent.VK_SHIFT)) {\n this.output += k.getKeyChar();\n } else if (this.output.length() &gt; 1) {\n this.output = this.output.substring(0, this.output.length() - 1);\n }\n\n System.out.print('\\f'); //clear screen in BlueJ\n System.out.println(this.output);\n\n /*\n switch (k.getKeyCode()) {\n case KeyEvent.VK_BACK_SPACE:\n if (this.output.length() &gt; 0) {\n this.stringBuilder.deleteCharAt(this.stringBuilder.length() - 1);\n }\n break;\n case KeyEvent.VK_SHIFT:\n break;\n default:\n this.stringBuilder.append(k.getKeyChar());\n }\n\n System.out.print('\\f'); //clear screen in BlueJ\n System.out.println(this.stringBuilder.toString());\n */\n }\n\n public static void main(final String[] args) {\n final JFrame frame = new JFrame(\"KeyEvent Handler\");\n frame.setSize(400,400);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.addKeyListener(new KeyHandler());\n frame.setVisible(true);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T17:46:33.010", "Id": "211278", "ParentId": "211265", "Score": "2" } } ]
{ "AcceptedAnswerId": "211278", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T14:32:26.817", "Id": "211265", "Score": "1", "Tags": [ "java", "homework", "swing", "event-handling" ], "Title": "Keypress output to screen" }
211265
<p>I got a programming question on an interview where performance was the focus. I couldnt come up with a better solution than the one below which I think has a time complexity of O(n^2 + n) and scored 20/100 on performance.</p> <p>The question in short was to find the highest result by adding two elements and in an array and the difference between the two indices e.g A[k] + A[j] + (j - k) - (k can be equal to j). </p> <p>The size of the array = [1...100 000]<br> The values in the array =[-1000 000 000...1000 000 000]</p> <p>I know using nested loops usally is a bad idea when It comes to handling larger arrays. So my question is simply how can it be improved to make it faster?</p> <pre><code>public static int solution(int [] A) { Set&lt;Integer&gt; occoured = new HashSet&lt;Integer&gt;(); int maxAppeal = 0; for(int i = 0; i &lt; A.length; i++) { if(occoured.add(A[i])) { for(int j = i; j &lt; A.length; j++) { int appeal = A[i] + A[j] + (j - i); if(appeal &gt; maxAppeal) maxAppeal = appeal; } } } return maxAppeal; } </code></pre>
[]
[ { "body": "<p>This is not a review, but an extended comment.</p>\n\n<p>Consider the question:</p>\n\n<blockquote>\n <p>Given two arrays, <code>A</code> and <code>B</code>, find the maximum of <code>A[i] + B[j]</code></p>\n</blockquote>\n\n<p>I suppose you can do it in linear time.</p>\n\n<p>Now rearrange the original equation as <code>(A[k] - k) + (A[j] + j)</code> and consider two auxiliary arrays, formed by <code>A[i] - i</code> and <code>A[i] + i</code>.</p>\n\n<p>Finally realize that you don't need these arrays at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T17:44:31.787", "Id": "211277", "ParentId": "211266", "Score": "3" } } ]
{ "AcceptedAnswerId": "211277", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:14:37.560", "Id": "211266", "Score": "1", "Tags": [ "java", "performance", "algorithm", "interview-questions" ], "Title": "Find the highest result between two elements in an array using their values and indices" }
211266
<p>Recently I found a question on StackOverflow that seemed very interesting: How to make HTML elements "zig zag" this way:</p> <pre><code> ----------------- |A &gt; B &gt; C &gt; D &gt; E| |J &lt; I &lt; H &lt; G &lt; F| ----------------- --- |A H| |B G| |C F| |D E| --- </code></pre> <p>I was able to implement a simple solution for this problem with Flexbox and a bit of JavaScript (works for any <strong>even number</strong> of elements):</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 reverseBoxes = function () { var flexItems = document.querySelectorAll(".child"), flexItemsCount = flexItems.length, reverseAt = flexItems.length / 2, breakPoint = 480; for (var i = reverseAt; i &lt; flexItemsCount; i++) { flexItems[i].style.order = flexItemsCount - i; } for (var j = 0; j &lt; flexItemsCount; j++) { if (window.innerWidth &gt; breakPoint) { flexItems[j].style.width = (100 / flexItemsCount) * 2 - 2 + "%"; flexItems[j].style.height = "auto"; } else { flexItems[j].style.height = (100 / flexItemsCount) * 2 - 2 + "%"; flexItems[j].style.width = "auto"; } } } reverseBoxes(); window.addEventListener("resize", reverseBoxes);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: Arial, sans-serif; font-size: 18px; margin: 0; padding: 0; } .parent { display: flex; flex-wrap: wrap; list-style-type: none; padding: 0; height: 100vh; } .child { margin: 1%; text-align: center; background: #069; color: #fff; display: flex; align-items: center; justify-content: center; } @media only screen and (max-width: 480px) { .parent { flex-direction: column; } .child { width: 48%; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; &lt;div class="child"&gt;A&lt;/div&gt; &lt;div class="child"&gt;B&lt;/div&gt; &lt;div class="child"&gt;C&lt;/div&gt; &lt;div class="child"&gt;D&lt;/div&gt; &lt;div class="child"&gt;E&lt;/div&gt; &lt;div class="child"&gt;F&lt;/div&gt; &lt;div class="child"&gt;G&lt;/div&gt; &lt;div class="child"&gt;H&lt;/div&gt; &lt;div class="child"&gt;I&lt;/div&gt; &lt;div class="child"&gt;J&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Tiny adjustment : you can update all your objects in your first loop and get rid of the second.</p>\n\n<pre><code>var reverseBoxes = function() {\n\n var flexItems = document.querySelectorAll(\".child\"),\n flexItemsCount = flexItems.length,\n reverseAt = flexItems.length / 2,\n breakPoint = 480;\n\n if (window.innerWidth &gt; breakPoint) {\n for (var i = reverseAt; i &lt; flexItemsCount; i++) {\n flexItems[i].style.order = flexItemsCount - i;\n // First half of items\n flexItems[flexItemsCount - i - 1].style.width = (100 / flexItemsCount) * 2 - 2 + \"%\";\n flexItems[flexItemsCount - i - 1].style.height = \"auto\";\n // Second half of items\n flexItems[i].style.width = (100 / flexItemsCount) * 2 - 2 + \"%\";\n flexItems[i].style.height = \"auto\";\n }\n } else {\n for (var i = reverseAt; i &lt; flexItemsCount; i++) {\n flexItems[i].style.order = flexItemsCount - i;\n // First half of items\n flexItems[flexItemsCount - i - 1].style.height = (100 / flexItemsCount) * 2 - 2 + \"%\";\n flexItems[flexItemsCount - i - 1].style.width = \"auto\";\n // Second half of items\n flexItems[i].style.height = (100 / flexItemsCount) * 2 - 2 + \"%\";\n flexItems[i].style.width = \"auto\";\n }\n }\n}\n</code></pre>\n\n<p>Edit : got the if out of the for loop</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:29:05.673", "Id": "408639", "Score": "0", "body": "Great piece of code. But mine is... slimmer. Why should I use yours?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:43:24.650", "Id": "408642", "Score": "0", "body": "Actually if you remove the comments it is the same amount of lines.\nIf I let the comments I can give it a small diet of one line by getting the if out of the for loop.\nMy bad I forgot a line. There is no diet by getting the if out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T13:25:21.900", "Id": "408645", "Score": "1", "body": "Find the original question, with my answer and many other, **[HERE](https://stackoverflow.com/questions/54024262/css-going-around-content-flow/)**." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:17:37.140", "Id": "211325", "ParentId": "211268", "Score": "2" } }, { "body": "<p>This code could be optimized by:</p>\n\n<ul>\n<li>selecting child elements by class name with <code>document.getElementsByClassName()</code>\nand only do this once instead of each time the function runs. Generally <code>document.getElementsByClassName</code> will be quicker than <code>document.querySelectorAll</code> (see <a href=\"https://stackoverflow.com/q/14377590/1575353\">this post</a> for more information) and the former also returns a live <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection\" rel=\"nofollow noreferrer\"><code>HTMLCollection</code></a> so it wouldn't need to be queried each time.</li>\n<li>only setting the <code>order</code> style on the items once, since that never changes between calls to <code>reverseBoxes()</code></li>\n<li>calculate the percentage height or width once instead of in each iteration of looping through the elements</li>\n</ul>\n\n<p>See this demonstrated in the updated code below. The code to set the <code>order</code> style will only run when those styles are not yet set so those won't get updated each time the function runs. That functionality could also be run when the page loads.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function() { //IIFE to keep scope of vars limited\n var flexItems = document.getElementsByClassName(\"child\"),\n flexItemsCount = flexItems.length,\n reverseAt = flexItems.length / 2,\n breakPoint = 480;\n var reverseBoxes = function() {\n let height = (100 / flexItemsCount) * 2 - 2 + \"%\";\n let width = \"auto\";\n let i = 0;\n if (window.innerWidth &gt; breakPoint) {\n width = height; //use value calculated above\n height = \"auto\"; //then set this to \"auto\"\n }\n for (const item of flexItems) {\n item.style.width = width;\n item.style.height = height;\n if (i++ &gt;= reverseAt &amp;&amp; !item.style.order) {\n item.style.order = flexItemsCount - i;\n }\n }\n }\n window.addEventListener(\"resize\", reverseBoxes);\n document.addEventListener(\"DOMContentLoaded\", reverseBoxes);\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-family: Arial, sans-serif;\n font-size: 18px;\n margin: 0;\n padding: 0;\n}\n\n.parent {\n display: flex;\n flex-wrap: wrap;\n list-style-type: none;\n padding: 0;\n height: 100vh;\n}\n\n.child {\n margin: 1%;\n text-align: center;\n background: #069;\n color: #fff;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n@media only screen and (max-width: 480px) {\n .parent {\n flex-direction: column;\n }\n .child {\n width: 48%;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"parent\"&gt;\n &lt;div class=\"child\"&gt;A&lt;/div&gt;\n &lt;div class=\"child\"&gt;B&lt;/div&gt;\n &lt;div class=\"child\"&gt;C&lt;/div&gt;\n &lt;div class=\"child\"&gt;D&lt;/div&gt;\n &lt;div class=\"child\"&gt;E&lt;/div&gt;\n &lt;div class=\"child\"&gt;F&lt;/div&gt;\n &lt;div class=\"child\"&gt;G&lt;/div&gt;\n &lt;div class=\"child\"&gt;H&lt;/div&gt;\n &lt;div class=\"child\"&gt;I&lt;/div&gt;\n &lt;div class=\"child\"&gt;J&lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T22:51:32.070", "Id": "233372", "ParentId": "211268", "Score": "2" } } ]
{ "AcceptedAnswerId": "211325", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:44:30.340", "Id": "211268", "Score": "4", "Tags": [ "javascript", "css", "event-handling", "iteration", "flex" ], "Title": "Zig-zag child element with Flexbox and JavaScript" }
211268
<p>I'm trying to learn how to use Qt (5.11.1) for GUI applications so I've done a simple memory game where 12 tiles are displayed and every time the user clicks on a tile it will show an image, so they have to match them into 6 pairs of images.</p> <p>There's a countdown of 1 minute. Game ends if the time is up before all 6 pairs have been matched, or if all 6 pairs are matched, only that it will show different messages to the user. There is no next level, saving score or anything, so it's very simple.</p> <p>I know there's room for adding many more features, but would like to know what can be improved from what I've done so far.</p> <p>My mainwindow.h file:</p> <pre><code>#ifndef MAINWINDOW_H #define MAINWINDOW_H #include &lt;QMainWindow&gt; #include &lt;QTimer&gt; #include &lt;QTime&gt; #include &lt;QString&gt; #include &lt;QVector&gt; #include &lt;QHash&gt; #include &lt;QRandomGenerator&gt; #include &lt;QPushButton&gt; #include &lt;QMessageBox&gt; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow{ Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); QTimer *timer=new QTimer(); QTime time; QVector&lt;QString&gt; tiles{"tile01", "tile02", "tile03", "tile04", "tile05", "tile06", "tile07", "tile08", "tile09", "tile10", "tile11", "tile12"}; QHash&lt;QString, QString&gt; tile_image; int score=0; bool isTurnStarted; QPushButton* previousTile; QPushButton* currentTile; int matchesLeft; QMessageBox msgBox; private slots: void updateCountdown(); void tileCliked(); void randomize(QVector&lt;QString&gt; &amp;tiles); void bindTileImage(QVector&lt;QString&gt; &amp;tiles, QHash&lt;QString, QString&gt; &amp;tile_image); void findTurnResult(); void restartTiles(); void showImage(); void findFinalResult(); void updateState(); void initalizeGame(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H </code></pre> <p>My mainwindow.cpp file:</p> <pre><code>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui-&gt;setupUi(this); //Connect timer to the slot that will handle the timer connect(timer, SIGNAL(timeout()), this, SLOT(updateState())); //Connect each button to the same slot, which will figure out which button was pressed and show its associated image file accordingly connect(ui-&gt;tiles01, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles02, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles03, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles04, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles05, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles06, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles07, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles08, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles09, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles10, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles11, SIGNAL(clicked()), this, SLOT(tileCliked())); connect(ui-&gt;tiles12, SIGNAL(clicked()), this, SLOT(tileCliked())); initalizeGame(); } void MainWindow::tileCliked(){ //get the tile that was clicked currentTile=qobject_cast&lt;QPushButton*&gt;(sender()); //get the image linked to that tile in the map and set tile background to it showImage(); //disable current tile so it can't be clicked again (unless there is no match, in which case it will be re-enabled) currentTile-&gt;setEnabled(false); //do something depending on whether the revealed tile is the first or the second tile in the turn if (!isTurnStarted){ previousTile=currentTile; isTurnStarted=true; } else{ //change score and display it findTurnResult(); ui-&gt;lblScore-&gt;setText(QString::number(score)); //reset turn isTurnStarted=false; } } void MainWindow::showImage(){ QString tile_name=currentTile-&gt;objectName(); QString img=tile_image[tile_name]; currentTile-&gt;setStyleSheet("#" + tile_name + "{ background-image: url(://" + img + ") }"); } void MainWindow::restartTiles(){ //return tiles from current turn to the default state (remove backgrounds) previousTile-&gt;setStyleSheet("#" + previousTile-&gt;objectName() + "{ }"); currentTile-&gt;setStyleSheet("#" + currentTile-&gt;objectName() + "{ }"); //re-enable both tiles so they can be used on another turn currentTile-&gt;setEnabled(true); previousTile-&gt;setEnabled(true); //re-enable the whole tile section ui-&gt;frame-&gt;setEnabled(true); } void MainWindow::findFinalResult(){ msgBox.setWindowTitle("Game has ended"); msgBox.setIcon(QMessageBox::Information); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); msgBox.setEscapeButton(QMessageBox::No); if (matchesLeft==0){ timer-&gt;stop(); msgBox.setText("Good job! Final score: " + QString::number(score) + "\nPlay again?"); if (QMessageBox::Yes == msgBox.exec()){ initalizeGame(); } else{ QCoreApplication::quit(); } } else{ if (time.toString()=="00:00:00"){ timer-&gt;stop(); ui-&gt;frame-&gt;setEnabled(false); msgBox.setText("Game over.\nPlay again?"); if (QMessageBox::Yes == msgBox.exec()){ initalizeGame(); } else{ QCoreApplication::quit(); } } } } void MainWindow::findTurnResult(){ //check if there is a match (the current tile matches the previous tile in the turn) if (tile_image[currentTile-&gt;objectName()]==tile_image[previousTile-&gt;objectName()]){ score+=15; matchesLeft--; //if there is a match, find out if all tiles have been matched. findFinalResult(); } else{ score-=5; //disable the whole tile section so no tiles can be turned during the 1-second "memorizing period" ui-&gt;frame-&gt;setEnabled(false); //if there is no match, let user memorize tiles and after 1 second hide tiles from current turn so they can be used on another turn QTimer::singleShot(1000, this, SLOT(restartTiles())); } } void MainWindow::initalizeGame(){ //start turn isTurnStarted=false; //Set score score=0; ui-&gt;lblScore-&gt;setText(QString::number(score));; //Set matches counter matchesLeft=6; //Set clock for countdown time.setHMS(0,1,0); //Initialize countdown ui-&gt;countdown-&gt;setText(time.toString("m:ss")); // Start timer with a value of 1000 milliseconds, indicating that it will time out every second. timer-&gt;start(1000); //Randomly sort tiles in container randomize(tiles); //Grab pairs of tiles and bind the name of an image file to each pair bindTileImage(tiles, tile_image); //enable tiles frame ui-&gt;frame-&gt;setEnabled(true); //enable every tile and reset its image QList&lt;QPushButton *&gt; btns = ui-&gt;centralWidget-&gt;findChildren&lt;QPushButton*&gt;(); foreach (QPushButton* b, btns) { b-&gt;setEnabled(true); b-&gt;setStyleSheet("#" + b-&gt;objectName() + "{ }"); } } void MainWindow::updateCountdown(){ time=time.addSecs(-1); ui-&gt;countdown-&gt;setText(time.toString("m:ss")); } void MainWindow::updateState(){ updateCountdown(); findFinalResult(); } void MainWindow::randomize(QVector&lt;QString&gt; &amp;tiles){ int a,b,min,max; min = 0; max = tiles.size()-1; for(int i=0; i&lt;tiles.size(); i++){ a=QRandomGenerator::global()-&gt;generate() % ((max + 1) - min) + min; b=QRandomGenerator::global()-&gt;generate() % ((max + 1) - min) + min; std::swap(tiles[a],tiles[b]); } } void MainWindow::bindTileImage(QVector&lt;QString&gt; &amp;tiles, QHash&lt;QString, QString&gt; &amp;tile_image){ auto iter=tiles.begin(); for (int i=1; i&lt;=6; i++){ QString file_name="0"+QString::number(i)+".png"; tile_image[(*iter)]=file_name; iter++; tile_image[(*iter)]=file_name; iter++; } } MainWindow::~MainWindow(){ delete ui; } </code></pre> <p>And the mainwindow.ui file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ui version="4.0"&gt; &lt;class&gt;MainWindow&lt;/class&gt; &lt;widget class="QMainWindow" name="MainWindow"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;800&lt;/width&gt; &lt;height&gt;600&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="windowTitle"&gt; &lt;string&gt;Memory game&lt;/string&gt; &lt;/property&gt; &lt;property name="styleSheet"&gt; &lt;string notr="true"&gt;#centralWidget { background-image: url(://background.png); } #howToPlay { color: white; } #countdown { color: white; } #scoring { color: white; } #lblScore { qproperty-alignment: AlignCenter; color: white; background: teal; border: 3px solid silver; border-radius: 7px; }&lt;/string&gt; &lt;/property&gt; &lt;widget class="QWidget" name="centralWidget"&gt; &lt;widget class="QLabel" name="howToPlay"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;160&lt;/x&gt; &lt;y&gt;40&lt;/y&gt; &lt;width&gt;471&lt;/width&gt; &lt;height&gt;31&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;14&lt;/pointsize&gt; &lt;weight&gt;75&lt;/weight&gt; &lt;bold&gt;true&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;Click on two tiles and try to match the images&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLabel" name="countdown"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;690&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;81&lt;/width&gt; &lt;height&gt;20&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;10&lt;/pointsize&gt; &lt;weight&gt;75&lt;/weight&gt; &lt;bold&gt;true&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;cronómetro&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLabel" name="scoring"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;330&lt;/x&gt; &lt;y&gt;520&lt;/y&gt; &lt;width&gt;71&lt;/width&gt; &lt;height&gt;21&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;12&lt;/pointsize&gt; &lt;weight&gt;75&lt;/weight&gt; &lt;bold&gt;true&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;Puntos:&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLabel" name="lblScore"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;410&lt;/x&gt; &lt;y&gt;510&lt;/y&gt; &lt;width&gt;41&lt;/width&gt; &lt;height&gt;31&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;14&lt;/pointsize&gt; &lt;weight&gt;75&lt;/weight&gt; &lt;bold&gt;true&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;0&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QFrame" name="frame"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;70&lt;/x&gt; &lt;y&gt;80&lt;/y&gt; &lt;width&gt;661&lt;/width&gt; &lt;height&gt;431&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="frameShape"&gt; &lt;enum&gt;QFrame::StyledPanel&lt;/enum&gt; &lt;/property&gt; &lt;property name="frameShadow"&gt; &lt;enum&gt;QFrame::Raised&lt;/enum&gt; &lt;/property&gt; &lt;widget class="QPushButton" name="tile10"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;180&lt;/x&gt; &lt;y&gt;300&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile05"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;160&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile06"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;180&lt;/x&gt; &lt;y&gt;160&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile09"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;300&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile07"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;340&lt;/x&gt; &lt;y&gt;160&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile03"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;340&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile11"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;340&lt;/x&gt; &lt;y&gt;300&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile01"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;130&lt;/width&gt; &lt;height&gt;110&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile04"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;500&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile12"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;500&lt;/x&gt; &lt;y&gt;300&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile02"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;180&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="tile08"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;500&lt;/x&gt; &lt;y&gt;160&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;111&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/widget&gt; &lt;zorder&gt;frame&lt;/zorder&gt; &lt;zorder&gt;howToPlay&lt;/zorder&gt; &lt;zorder&gt;countdown&lt;/zorder&gt; &lt;zorder&gt;score&lt;/zorder&gt; &lt;zorder&gt;lblScore&lt;/zorder&gt; &lt;/widget&gt; &lt;widget class="QToolBar" name="mainToolBar"&gt; &lt;attribute name="toolBarArea"&gt; &lt;enum&gt;TopToolBarArea&lt;/enum&gt; &lt;/attribute&gt; &lt;attribute name="toolBarBreak"&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/attribute&gt; &lt;/widget&gt; &lt;widget class="QStatusBar" name="statusBar"/&gt; &lt;/widget&gt; &lt;layoutdefault spacing="6" margin="11"/&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt; </code></pre> <p>Please note I translated variable and slot names into English for better understanding. I could have missed something.</p> <p>Thanks!!</p>
[]
[ { "body": "<p>When dealing with Qt 5+ prefer the new connect syntax:</p>\n\n<pre><code>QObject::connect(ui-&gt;tiles01, &amp;QPushButton::clicked, this, &amp;MainWindow::tileCliked);\n</code></pre>\n\n<p>Instead of using <code>sender()</code> in the slot you can use a functor to pass the sender along:</p>\n\n<pre><code>QObject::connect(ui-&gt;tiles01, &amp;QPushButton::clicked, this, [=](){tileCliked(ui-&gt;tiles01)});\n</code></pre>\n\n<p>Then <code>tileCliked</code> becomes </p>\n\n<pre><code>void MainWindow::tileCliked(QPushButton* sender){\n //...\n}\n</code></pre>\n\n<p>You shuffle isn't a proper shuffle. Instead you want to do a fisher-yates shuffle:</p>\n\n<pre><code>void MainWindow::randomize(QVector&lt;QString&gt; &amp;tiles){\n int a,b,min,max;\n max = tiles.size()-1;\n for(int i=0; i&lt;tiles.size(); i++){\n min = i;\n a = i;\n b = QRandomGenerator::global()-&gt;generate() % ((max + 1) - min) + min;\n if(b != a)\n std::swap(tiles[i],tiles[b]);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T16:07:56.313", "Id": "408529", "Score": "4", "body": "Any reason not to simply use `std::shuffle()`, and avoid re-implementing it entirely?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:43:41.480", "Id": "408552", "Score": "0", "body": "Not sure why I didn't use std::shuffle()... Would this be a better approach for my `randomize()` slot?: `unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n shuffle (tiles.begin(), tiles.end(), std::default_random_engine(seed));`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T16:02:31.180", "Id": "211271", "ParentId": "211269", "Score": "4" } } ]
{ "AcceptedAnswerId": "211271", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T15:44:37.267", "Id": "211269", "Score": "4", "Tags": [ "c++", "gui", "qt" ], "Title": "C++ Qt simple GUI game" }
211269
<p>I wrote an implementation of php <code>FilterIterator</code> objects that allows me to apply them in a "cascade" way, so I can finally obtain an array of objects which is the result of all those filters.</p> <p>It works fine, but - being new to SPL objects - I'm wondering if there is a better way to achieve the same results with <code>FilterIterators</code> <em>et similia</em>.</p> <h2>My implementation</h2> <p>I have a Factory class holding an array of objects in a static property:</p> <pre><code>class Factory { /** * @var Reservation[] */ public static $reservations; public function __construct(){ self::$reservations = $this-&gt;get_all(); } private function get_all(){ // Queries the database... return $results; // array of Reservation objects } // other unrelated things... } </code></pre> <p>As I need the ability to filter such array by some criteria on-demand, I defined a bunch of <code>FilterIterator</code> sub-classes. The following is <code>byOrder</code>, others (<code>byService</code>, <code>byProvider</code> etc.) are defined in a similar way:</p> <pre><code>class byOrder extends FilterIterator { protected $order; public function __construct(Iterator $iterator, $order){ parent::__construct($iterator); $this-&gt;order = $order; } public function accept(){ /** @var $current Reservation */ $current = $this-&gt;current(); return $current-&gt;order() === $this-&gt;order; } } </code></pre> <p>In order to apply just one filter to the array (I need it to stay as array) wherever in my application I can do:</p> <pre><code>// somewhere else... $factory = new Factory(); // later on... $reservations = new ArrayObject(Factory::$reservations); $iterator = $reservations-&gt;getIterator(); $filteredReservation = iterator_to_array(new byOrder($iterator, 'ORDER_ID')); </code></pre> <p>To be able to apply multiple filters in a "cascade" way, I created the following helper class:</p> <pre><code>class Select { /** * @var ArrayIterator */ private $reservations; public function __construct(array $reservations) { $obj = new ArrayObject($reservations); $this-&gt;reservations = $obj-&gt;getIterator(); } public function get(){ return iterator_to_array($this-&gt;reservations); } public function byOrder($order){ $this-&gt;reservations = new byOrder($this-&gt;reservations, $order); return $this; } public function byService($service){ $this-&gt;reservations = new byService($this-&gt;reservations, $service); return $this; } // ... and so on } </code></pre> <p>It is instantiated on-demand through a method inside the <code>Factory</code> class:</p> <pre><code>class Factory { // All the previously defined content, plus: public function select() { return new Select(self::$reservations); } } </code></pre> <p>So I'm able to apply multiple cascading filters like this:</p> <pre><code>// somewhere else... $factory = new Factory(); // later on... $filtered = $factory-&gt;select() -&gt;byOrder('ORDER_ID') -&gt;byService('SERVICE_NAME') -&gt;get(); </code></pre>
[]
[ { "body": "<p><strong>Edit</strong></p>\n\n<p>One suggestion is to make your helper class more dynamic. As it currently stands it is heavily tied to each filter class so you could not reuse it in another project. For example, imagine a new project that deals with selling cars. Your <code>Select</code> helper class only knows about <code>orders</code>, <code>services</code>, <code>providers</code>. You'd have to rewrite it to know about <code>cars</code>, <code>prices</code>, <code>colours</code> etc. </p>\n\n<p>To get around this, you can define a filter property which holds a list of filters. Then, when calling <code>get()</code>, loop over the filters and apply each one. The benefit here is that the helper class is now\nunaware of any filter implementations and can be used in any project. </p>\n\n<pre><code>&lt;?php\n\n/*************************************************/\n/******************** FILTERS ********************/\n/*************************************************/\nclass Order extends FilterIterator\n{\n private $_value = null;\n\n public function __construct(Iterator $iterator, $value)\n {\n $this-&gt;_value = $value;\n parent::__construct($iterator);\n }\n\n public function accept()\n {\n return $this-&gt;current()-&gt;order === $this-&gt;_value;\n }\n}\n\nclass Future extends FilterIterator\n{\n public function __construct(Iterator $iterator)\n {\n parent::__construct($iterator);\n }\n\n public function accept()\n {\n return $this-&gt;current()-&gt;date &gt; new DateTime();\n }\n}\n\nclass Date extends FilterIterator\n{\n private $_value = null;\n\n public function __construct(Iterator $iterator, $value)\n {\n $this-&gt;_value = $value;\n parent::__construct($iterator);\n }\n\n public function accept()\n {\n return $this-&gt;current()-&gt;date === $this-&gt;_value;\n }\n}\n\n/*************************************************/\n/*************** COLLECTION HELPER ***************/\n/*************************************************/\nclass Helper\n{\n private $_items = [];\n private $_filters = [];\n\n public function __construct(array $items)\n {\n $this-&gt;_items = (new ArrayObject($items))-&gt;getIterator();\n }\n\n public function filter($filter, $value = null)\n {\n $this-&gt;_filters[] = [$filter =&gt; $value];\n\n return $this;\n }\n\n public function get()\n {\n foreach ($this-&gt;_filters as $filter) {\n foreach ($filter as $name =&gt; $value) {\n\n if ($value) {\n $this-&gt;_items = new $name($this-&gt;_items, $value);\n } else {\n $this-&gt;_items = new $name($this-&gt;_items);\n }\n }\n }\n\n return iterator_to_array($this-&gt;_items);\n }\n}\n\n/*************************************************/\n/****************** TEST CASES *******************/\n/*************************************************/\nclass Reservation\n{\n public $order = null;\n public $date = null;\n public $status = null;\n\n public function __construct($order, $date, $status)\n {\n $this-&gt;order = $order;\n $this-&gt;date = $date;\n $this-&gt;status = $status;\n }\n}\n\n$reservations = new Helper([\n new Reservation(123, new DateTime('+1Day'), 'Active'),\n new Reservation(512, new DateTime('+2Month'), 'Active'),\n new Reservation(456, new DateTime('-6Hour'), 'Pending'),\n new Reservation(789, new DateTime('-17Day'), 'Cancelled'),\n new Reservation(264, new DateTime('+1Hour'), 'Pending'),\n new Reservation(151, new DateTime('+1Year'), 'Active'),\n]);\n\n$filtered = $reservations\n -&gt;filter('Future')\n -&gt;filter('Order', 151)\n -&gt;get();\n\nvar_dump($filtered);\n</code></pre>\n\n<p><strong>Final note</strong> - I played around with the implementation for a while and found FilterIterators to be rather cumbersome because I had to write a single filter class for each permutation of a property. For example, in a reservation system you'd need the following filters: <code>ByOrder</code>, <code>ByOrderNotEqualTo</code>, <code>ByDate</code>, <code>ByFuture</code>, <code>ByPast</code>, <code>By6MonthsFromNow</code>, <code>ByStatus</code>, <code>ByStatusNotEqualTo</code>, <code>ByCustomerId</code>, etc.</p>\n\n<p>One solution is to add a <code>where</code> method to your helper class which would accept a <em>comparison operator</em>. Again, I point you to <a href=\"https://github.com/illuminate/support/blob/master/Collection.php#L586\" rel=\"nofollow noreferrer\">Laravel's implementation</a> and a document <a href=\"https://stillat.com/blog/2018/04/22/laravel-5-collections-filtering-collection-elements-with-where\" rel=\"nofollow noreferrer\">highlighting its usage</a>. Food for thought. </p>\n\n<p><strong>EndEdit</strong></p>\n\n<p>If you're looking for a simple method, take a look at Laravel's implementation of their <a href=\"https://github.com/illuminate/support/blob/master/Collection.php#L489\" rel=\"nofollow noreferrer\">Collection::filter</a> which calls <a href=\"https://github.com/illuminate/support/blob/master/Arr.php#L607\" rel=\"nofollow noreferrer\">Arr::filter</a>. It provides a clean, chainable way to pass a callback to <code>array_filter</code>. </p>\n\n<p>Below, is a basic demonstration on how to use it. I've implemented it using <code>ArrayObject</code> but you can use any iterable class. The <code>filter</code> calls will be slightly longer to type out than your implementation since you must define a callback function each time, but it makes the source much cleaner since you don't have to define a separate filter class for every property. </p>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/cea564648d52c702e112d9775d1afe76f41fc810\" rel=\"nofollow noreferrer\">http://sandbox.onlinephpfunctions.com/code/cea564648d52c702e112d9775d1afe76f41fc810</a></p>\n\n<pre><code>&lt;?php\n\nclass Collection extends ArrayObject\n{\n public function filter(callable $callback = null)\n {\n if ($callback) {\n // This will return a new Collection object with the filtered results.\n // Late static binding - You **could use either `static`\n // or `self` here since both will resolve to Collection.\n // Going with `static` in case you want to extend this class.\n // See - https://stackoverflow.com/q/5197300/296555\n return new static (array_filter($this-&gt;getArrayCopy(), $callback, ARRAY_FILTER_USE_BOTH));\n }\n\n return new static (array_filter($this-&gt;getArrayCopy()));\n }\n}\n\nclass Reservation\n{\n public $order = null;\n public $date = null;\n public $status = null;\n\n public function __construct($order, $date, $status)\n {\n $this-&gt;order = $order;\n $this-&gt;date = $date;\n $this-&gt;status = $status;\n }\n}\n\n$reservations = new Collection([\n new Reservation(123, new DateTime('+1Day'), 'Active'),\n new Reservation(512, new DateTime('+2Month'), 'Active'),\n new Reservation(456, new DateTime('-6Hour'), 'Pending'),\n new Reservation(789, new DateTime('-17Day'), 'Cancelled'),\n new Reservation(264, new DateTime('+1Hour'), 'Pending'),\n new Reservation(151, new DateTime('+1Year'), 'Active'),\n]);\n\n$filtered = $reservations \n // Active reservations\n -&gt;filter(function ($value, $key) {\n return $value-&gt;status === 'Active';\n })\n // In the future\n -&gt;filter(function ($value, $key) {\n return $value-&gt;date &gt; new DateTime();\n });\n\nvar_dump($filtered);\n</code></pre>\n\n<p>Finally, <a href=\"https://github.com/cocur/chain\" rel=\"nofollow noreferrer\">here's a decent package</a> that took this idea a step further and implements most array functions so you can chain them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:33:01.513", "Id": "408676", "Score": "0", "body": "This is a nice and compact solution, although it doesn't use `FilterIterators` which I wanted to explore for the reason (which I should have probably explicited) of their flexibility and reusability. From a quick-and-dirty test, it also looks like my implementation uses less memory than _array_filter_ chaining at least when a high number of items and a certain number of filters are applied: [here](http://sandbox.onlinephpfunctions.com/code/30bf473c13e16a3fa3e2277fbc54030fdcb51d4f) versus [here](http://sandbox.onlinephpfunctions.com/code/abb00c0ed0f5e83ae4a5074a13be9c994d318ef0)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T13:12:25.630", "Id": "408901", "Score": "0", "body": "To answer your original question, you need that helper class to return `$this` to make your filters chainble. If you want to remove that helper class, you'd inject the filter into the next filter. Ex. `new ByOrder(new ByService(new ByProvider(...)))` but I'm not a fan of this approach - https://goo.gl/LcyqfU. \nAs for the memory usage, you're right about `array_filter`; it makes a copy of the array for each filter. Be careful using this approach on very large datasets. For me though, I value the simplicity, readability and reusability of the `Collection` class over the higher memory usage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T14:46:53.500", "Id": "409343", "Score": "0", "body": "Of course for a bunch of simple property comparisons, writing a class for each of them I agree it looks overkill. But for instance, I have a filter doing time comparison with some requirements about the timezone (those may change in the future): I found `FilterIterator` with `DateTime` computations in its _accept()_ method being a lifesaver... And I made it so it can accept any form of time source, not just - let's say - a timestamp for raw comparison. I really do like your suggestion to make the helper class unaware of the actual filters, I will play with it!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T15:58:19.010", "Id": "211331", "ParentId": "211273", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T16:59:31.760", "Id": "211273", "Score": "1", "Tags": [ "php", "iterator", "spl" ], "Title": "Applying multiple php FilterIterator instances in a cascading fashion" }
211273
<p>I'm trying to extract all files (XMLs) from an ftp site with python and the ftplib module, but it's incredibly slow so I suspect I'm doing something wrong.</p> <p>The files are in subfolders, and all at the same "depth" eg: 'startingdir/folder1/place1/file.xml', 'startingdir/folder1/place1/file2.xml', 'startingdir/folder1/place2/file.xml', 'startingdir/folder2/place1/file.xml'</p> <p>I want to extract everything regardless of location.</p> <p>As a side note, if this can be put into a function which iterates the process until it finds .xml files in the directory and then extracts those, that would be incredibly helpful (rather than knowing the "depth" and putting the right number of nested for loops).</p> <p>Code as it stands:</p> <pre><code>from ftplib import FTP import os destination = r'C:\Destination' ftp = FTP('ftp.com') ftp.login('user','pw') </code></pre> <p>Once I'm in, I get a list of all the folders in my starting directory:</p> <pre><code>ftp.cwd('startingdir') templist = [] ftp.retrlines('LIST',templist.append) subdirlist = [i.split(None,8)[-1].lstrip() for i in templist] </code></pre> <p>Then, I iterate this process a few times:</p> <pre><code>for i in subdirlist: ftp.cwd('startingdir/'+i) templist = [] ftp.retrlines('LIST',templist.append) subdirlist2 = [i.split(None,8)[-1].lstrip() for i in templist] for j in subdirlist2: ftp.cwd('startingdir/'+ i + '/' + j) templist = [] ftp.retrlines('LIST',templist.append) subdirlist3 = [i.split(None,8)[-1].lstrip() for i in templist] </code></pre> <p>Finally, I extract all files from the right "depth" folder:</p> <pre><code> for k in subdirlist3: local_filename = os.path.join(destination,k) lf = open(local_filename, 'wb') ftp.retbinary('RETR '+ k, lf.write, 8*1024) lf.close </code></pre> <p>The code works, but it's incredibly slow (without counting precisely, it looks like 3-4 files/second). Is there anything obvious I'm doing wrong? Having 4-5 nested for loops doesn't look good, but I don't know how else to achieve this.</p> <p>Thank you in advance for the suggestions!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:45:22.300", "Id": "408643", "Score": "0", "body": "Could you post your **entire** code instead of several stripped down snippets. To make life easier for a reviewer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T14:30:33.613", "Id": "408651", "Score": "0", "body": "Sorry if it wasn't clear - this is the entire code, just annotated to be clearer. There are two extra for loops that I excluded because they are exactly identical (this relates to the \"depth\" of the objects), so technically the final box would start with `for m in subdirlist5:`. That's all." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T17:02:31.287", "Id": "211274", "Score": "1", "Tags": [ "python", "python-3.x", "ftp" ], "Title": "Extracting many files from FTP site" }
211274
<p>In <a href="https://codereview.stackexchange.com/questions/211216/encrypt-pdf-files/211279#211279">Encrypt PDF-Files</a> I provided a Python program to encrypt PDF-Files in a folder.</p> <p>This program here does the oposite. Giving a password and path all PDFs which are encrypted are decrypted in the supplied path. If the password is wrong a message is displayed.</p> <p><strong>pdf_decrypter.py</strong></p> <pre><code>""" Decrypts all files in a folder and sub folder with provided password """ import os import argparse from typing import Tuple from getpass import getpass from pathlib import Path import PyPDF2 def get_password_from_user() -&gt; str: """Asks the user to enter a password""" while True: password: str = getpass(promt="Enter password: ") if password: return password def get_path_from_user() -&gt; str: """Asks for a path from the User""" while True: #input_string = "E:/Python Projekte\ATBS\CH13_EX1_pdf_decrypter\CH13_EX1_pdf_decrypter\CH13_EX1_pdf_decrypter\\testfolder" path = Path(input("Enter absolute Path:")) if os.path.exists(path): return path print("Path doesn't exist\n") def get_path_and_password() -&gt; Tuple[str, str]: """ Gets path and password from command line or if not available from the user """ parser = argparse.ArgumentParser() parser.add_argument( "--path", help="provide root folder to look for PDFs to encrypt", type=str) parser.add_argument( "--password", help="password to encrypt PDFs with", type=str) args = parser.parse_args() if args.path and args.password: return Path(args.path), args.password return get_path_from_user(), get_password_from_user() def is_encrypted(filename: str) -&gt; bool: """Checks if file is encrypted""" with open(filename, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) return pdf_reader.isEncrypted def decrypt(filename: str, password: str) -&gt; bool: """ Try to decrypt a file. If not successful a false is returned. If the file passed is not encrypted also a false is passed """ with open(filename, 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) pdf_reader.decrypt(password) pdf_writer = PyPDF2.PdfFileWriter() try: for page_number in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_number)) except PyPDF2.utils.PdfReadError: return False filename_decrypted = filename.strip('.pdf') + "_decrypted.pdf" with open(filename_decrypted, 'wb') as pdf_file_decrypted: pdf_writer.write(pdf_file_decrypted) return True def pdf_decrypter(): """ Main routine: Giving a password and path all PDFs which are encrypted get decrypted in the supplied path. If the password is wrong a message is displayed. """ path, password = get_path_and_password() for folder_name, _, filenames in os.walk(path): for filename in filenames: if not filename.endswith('.pdf'): continue if not is_encrypted(os.path.join(folder_name, filename)): continue if decrypt(os.path.join(folder_name, filename), password): os.remove(filename) else: print(filename + " could not be decrypted (wrong password)") if __name__ == "__main__": pdf_decrypter() </code></pre> <p>I already incorporated improvements suggested in the encrypter review in <a href="https://codereview.stackexchange.com/questions/211216/encrypt-pdf-files/211279#211279">Encrypt PDF-Files</a></p> <p>What else can be improved in the code?</p> <p>Let me know.</p>
[]
[ { "body": "<h3>Bugs:</h3>\n\n<ol>\n<li><p>Here, instead of <code>promt</code> it should be <code>prompt</code>:</p>\n\n<blockquote>\n<pre><code>password: str = getpass(promt=\"Enter password: \")\n</code></pre>\n</blockquote></li>\n<li><p>If PDF file is not in the current folder, this will throw an error:</p>\n\n<blockquote>\n<pre><code>if decrypt(os.path.join(folder_name, filename), password):\n os.remove(filename)\n</code></pre>\n</blockquote>\n\n<p>it should be <code>os.remove(os.path.join(folder_name, filename))</code> instead.</p></li>\n</ol>\n\n<h3>Docstring:</h3>\n\n<blockquote>\n<pre><code>\"\"\"\nDecrypts all files in a folder and sub folder with provided password\n\"\"\"\n</code></pre>\n</blockquote>\n\n<p>I think it would be better to specify that only PDF files will be decrypted. Also, it should mention that original copy will be removed. How about:</p>\n\n<pre><code>\"\"\"\nDecrypts all pdf files in a specified folder\nand all its sub-folders with provided password,\nsaves decrypted copy and removes original encrypted files.\n\"\"\"\n</code></pre>\n\n<h3><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8:</a></h3>\n\n<blockquote>\n <p>Imports should be grouped in the following order:</p>\n \n <ol>\n <li>Standard library imports. </li>\n <li>Related third party imports. </li>\n <li>Local application/library specific imports.</li>\n </ol>\n \n <p>You should put a blank line between each group of imports.</p>\n</blockquote>\n\n<p>Also, it is advised to sort imports <a href=\"https://stackoverflow.com/questions/20762662/whats-the-correct-way-to-sort-python-import-x-and-from-x-import-y-statement\">alphabetically</a>. </p>\n\n<p>So, instead of:</p>\n\n<blockquote>\n<pre><code>import os\nimport argparse\nfrom typing import Tuple\nfrom getpass import getpass\nfrom pathlib import Path\nimport PyPDF2\n</code></pre>\n</blockquote>\n\n<p>You will have:</p>\n\n<pre><code>import argparse\nimport os\nfrom getpass import getpass\nfrom pathlib import Path\nfrom typing import Tuple\n\nimport PyPDF2\n</code></pre>\n\n<p>Also, before the first function there should be two <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">blank lines</a>. Apart from that, well done! You follow the style guide pretty well!</p>\n\n<h3><a href=\"https://click.palletsprojects.com\" rel=\"nofollow noreferrer\">Click:</a></h3>\n\n<p>Instead of using argparse, I'd suggest to take a look at third-party library Click. <a href=\"http://click.palletsprojects.com/en/7.x/why/\" rel=\"nofollow noreferrer\">Why Click?</a></p>\n\n<p><strong>Example of usage:</strong><br>\nFor example, here is how you could wrap main function <code>pdf_decrypter</code>:</p>\n\n<pre><code>import click\n\n...\n\n@click.command()\n@click.option('--path', '-p',\n default='.',\n show_default=True,\n type=click.Path(),\n help='Folder path to look for PDFs to decrypt '\n '(absolute or relative).')\n@click.password_option(confirmation_prompt=False)\ndef pdf_decrypter(path: str,\n password: str):\n...\n</code></pre>\n\n<p>Running <code>python3 pdf_decrypter.py --help</code> from command line will print:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Usage: pdf_decrypter.py [OPTIONS]\n\n Main routine: Giving a password and path all PDFs which are encrypted get\n decrypted in the supplied path. If the password is wrong a message is\n displayed.\n\nOptions:\n -p, --path PATH Folder path to look for PDFs to decrypt (absolute or\n relative). [default: .]\n --password TEXT\n --help Show this message and exit.\n</code></pre>\n\n<p><strong>Confirmation messages:</strong><br>\nFurther in the body of the function you can add confirmation message as well, like:</p>\n\n<pre><code>...\nif not click.confirm(f'All PDF files will be encrypted in {path}\\n'\n 'Do you want to continue?'):\n return\n...\n</code></pre>\n\n<p>This will look like:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>python3 pdf_decrypter.py \nPassword: \nAll PDF files will be encrypted in /path/to/pdf_files\nDo you want to continue? [y/N]: \n</code></pre>\n\n<p><strong>Putting encryption and decryption together:</strong><br>\nAnd, probably, you would want to put both encryption from your previous post and decryption in the same module later, as they share a lot in common. In this case you would want to use <a href=\"http://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands\" rel=\"nofollow noreferrer\">Nesting Commands</a>, for example, like this:</p>\n\n<pre><code>@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.option('--path', '-p',\n default='.',\n show_default=True,\n type=click.Path(),\n help='Folder path to look for PDFs to decrypt '\n '(absolute or relative).')\n@click.password_option(confirmation_prompt=False)\ndef decrypt(path: str,\n password: str):\n...\n\n@cli.command()\n@click.option('--path', '-p',\n default='.',\n show_default=True,\n type=click.Path(),\n help='Folder path to look for PDFs to decrypt '\n '(absolute or relative).')\n@click.password_option(confirmation_prompt=False)\ndef encrypt(path: str,\n password: str) -&gt; None:\n...\n</code></pre>\n\n<p>And you would call your functions like <code>python pdf_utils.py encrypt</code> or <code>python pdf_utils.py decrypt</code>, etc.</p>\n\n<p><a href=\"http://click.palletsprojects.com/en/7.x/api/#click.Path\" rel=\"nofollow noreferrer\"><strong><code>click.Path</code>:</strong></a><br>\nYou can specify additional checks, like checking if path exists, path is not a file, and also make Click to resolve path automatically by setting <code>resolve_path</code> as <code>True</code>. So you wouldn't have to use <code>os.path.join</code> later in the code:</p>\n\n<pre><code>@click.option('--path', '-p',\n default='.',\n show_default=True,\n type=click.Path(exists=True,\n file_okay=False,\n resolve_path=True),\n help='Folder path to look for PDFs to decrypt '\n '(absolute or relative).')\n</code></pre>\n\n<h3>Iterating over files:</h3>\n\n<p>Right now you have two nested loops and two checks of extension and if file is encrypted:</p>\n\n<blockquote>\n<pre><code>for folder_name, _, filenames in os.walk(path):\n for filename in filenames:\n if not filename.endswith('.pdf'):\n continue\n\n if not is_encrypted(os.path.join(folder_name, filename)):\n continue\n\n # decryption logic\n</code></pre>\n</blockquote>\n\n<p>This looks pretty cumbersome. And I personally don't like it when the code is nested on two or more levels. We can use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> module to simplify this logic:</p>\n\n<pre><code>pdf_paths = Path(path).rglob('*.pdf')\nencrypted_pdfs = filter(is_encrypted, pdf_paths)\nfor pdf in encrypted_pdfs:\n # decryption logic\n</code></pre>\n\n<h3>Errors catching:</h3>\n\n<p>Now you catch <code>PyPDF2.utils.PdfReadError</code> on the deepest level, in <code>decrypt</code> function. I suggest you to take it out to main function, and not return <code>True</code> or <code>False</code> to indicate success/failure. See, for example, <a href=\"https://softwareengineering.stackexchange.com/questions/219320/when-and-how-should-i-use-exceptions\">When and how should I use exceptions?</a><br>\nSo, in the <code>pdf_decrypter</code>, you will have:</p>\n\n<pre><code>for pdf in encrypted_pdfs:\n try:\n decrypt(pdf, password)\n pdf.unlink()\n except PyPDF2.utils.PdfReadError:\n print(f'{pdf} could not be decrypted (wrong password)')\n</code></pre>\n\n<h3><code>pathlib</code> over <code>os</code>:</h3>\n\n<p>You almost don't use advantages of the <code>pathlib</code>. I already included some things in previous code examples. But here I will sum up everything. </p>\n\n<p><strong>Opening file:</strong><br>\nThis:</p>\n\n<blockquote>\n<pre><code>with open(filename, 'rb') as pdf_file:\n</code></pre>\n</blockquote>\n\n<p>will become:</p>\n\n<pre><code>with filepath.open('rb') as pdf_file:\n</code></pre>\n\n<p>Note that <code>filepath</code> would be a better name here.</p>\n\n<p><strong>Changing filename:</strong> </p>\n\n<blockquote>\n<pre><code>filename_decrypted = filename.strip('.pdf') + \"_decrypted.pdf\"\n</code></pre>\n</blockquote>\n\n<p>could be rewritten as:</p>\n\n<pre><code>decrypted_filename = f'{filepath.stem}_decrypted{filepath.suffix}' # new name\ndecrypted_filepath = filepath.parent / decrypted_filename # complete path\n</code></pre>\n\n<p><strong>Removing file:</strong><br>\n<code>os.remove(path)</code> can be replaced by <code>path.unlink()</code>.<br>\nBy this moment we removed all <code>os</code> module usages. So, we can remove that import.</p>\n\n<h3>Putting it all together:</h3>\n\n<pre><code>\"\"\"\nDecrypts or encrypts all pdf files in a specified folder\nand all its sub-folders with provided password,\nsaves processed copies and removes original files.\n\"\"\"\nfrom itertools import filterfalse\nfrom pathlib import Path\n\nimport click\nimport PyPDF2\n\n\ndef is_encrypted(filepath: Path) -&gt; bool:\n \"\"\"Checks if file is encrypted\"\"\"\n with filepath.open('rb') as pdf_file:\n pdf_reader = PyPDF2.PdfFileReader(pdf_file)\n return pdf_reader.isEncrypted\n\n\ndef write_copy(filepath: Path,\n password: str,\n *,\n mode: str) -&gt; None:\n \"\"\"\n Writes encrypted or decrypted copy of the file based on the mode\n :param filepath: path of the PDF file to be processed\n :param password: password to decrypt/encrypt PDF with\n :param mode: one of 'encrypt' or 'decrypt'\n \"\"\"\n with filepath.open('rb') as pdf_file:\n pdf_reader = PyPDF2.PdfFileReader(pdf_file)\n pdf_writer = PyPDF2.PdfFileWriter()\n\n if mode == 'decrypt':\n pdf_reader.decrypt(password)\n for page_number in range(pdf_reader.numPages):\n pdf_writer.addPage(pdf_reader.getPage(page_number))\n if mode == 'encrypt':\n pdf_writer.encrypt(password)\n\n suffix = {'decrypt': '_decrypted',\n 'encrypt': '_encrypted'}\n processed_filename = f'{filepath.stem}{suffix[mode]}{filepath.suffix}'\n processed_filepath = filepath.parent / processed_filename\n\n with processed_filepath.open('wb') as pdf_file_processed:\n pdf_writer.write(pdf_file_processed)\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.option('--path', '-p',\n default='.',\n show_default=True,\n type=click.Path(exists=True,\n file_okay=False,\n resolve_path=True),\n help='Folder path to look for PDFs to decrypt '\n '(absolute or relative).')\n@click.password_option(confirmation_prompt=False)\ndef decrypt(path: str,\n password: str) -&gt; None:\n \"\"\"\n Decrypts all encrypted PDFs in the supplied path.\n If the password is wrong a message is displayed.\n Saves processed copies and removes original files.\n :param path: folder path to look for PDFs to decrypt\n :param password: password to decrypt PDFs with\n \"\"\"\n pdf_paths = Path(path).rglob('*.pdf')\n encrypted_pdfs = filter(is_encrypted, pdf_paths)\n for pdf in encrypted_pdfs:\n try:\n write_copy(pdf, password, mode='decrypt')\n pdf.unlink()\n click.echo(f'Decrypted successfully: {pdf}')\n except PyPDF2.utils.PdfReadError:\n click.echo(f'{pdf} could not be decrypted (wrong password)')\n\n\n@cli.command()\n@click.option('--path', '-p',\n default='.',\n show_default=True,\n type=click.Path(exists=True,\n file_okay=False,\n resolve_path=True),\n help='Folder path to look for PDFs to decrypt '\n '(absolute or relative).')\n@click.password_option(confirmation_prompt=False)\ndef encrypt(path: str,\n password: str) -&gt; None:\n \"\"\"\n Encrypts all non-encrypted PDFs in the supplied path.\n Saves processed copies and removes original files.\n :param path: folder path to look for PDFs to encrypt\n :param password: password to encrypt PDFs with\n \"\"\"\n if not click.confirm(f'All PDF files will be encrypted in {path}\\n'\n 'Do you want to continue?'):\n return\n\n pdf_paths = Path(path).rglob('*.pdf')\n not_encrypted_pdfs = filterfalse(is_encrypted, pdf_paths)\n\n for pdf in not_encrypted_pdfs:\n write_copy(pdf, password, mode='encrypt')\n pdf.unlink()\n click.echo(f'Encrypted successfully: {pdf}')\n\n\nif __name__ == '__main__':\n cli()\n</code></pre>\n\n<p>Probably, <code>encrypt</code> and <code>decrypt</code> could be put in one function with a <code>mode</code> parameter, like what I did in a <code>write_copy</code> function; but see for yourself if it will make the code more clear.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T17:04:48.677", "Id": "211865", "ParentId": "211281", "Score": "2" } } ]
{ "AcceptedAnswerId": "211865", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:03:57.800", "Id": "211281", "Score": "4", "Tags": [ "python", "beginner", "pdf" ], "Title": "Decrypting PDF-Files" }
211281
<p>I've written a lot of C++ but now I'm learning Swift. I did an exercise, the standard Sieve of Erastosthenes. It works fine, but it seems a bit clunky and I wonder if I'm missing some language features that might streamline it a bit and make it more idiomatic Swift.</p> <p>Here's the code:</p> <pre><code>struct Sieve { let primes: [Int] init(_ maxValue: Int) { var numbers = Array&lt;Int?&gt;(repeating: nil, count:maxValue + 1) for n in 2...maxValue { numbers[n] = n } var start = 2 while start &lt; maxValue { guard let prime = numbers.first(where: {$0 != nil &amp;&amp; $0! &gt;= start}) else {break} let lo = 2 * prime! if lo &lt; maxValue { for x in stride(from: lo, to: numbers.count, by: prime!) { numbers[x] = nil } } start = prime! + 1 } primes = numbers.compactMap{$0} } } </code></pre> <p>With the line starting "guard let prime", I'd like to supply a starting index for the 'find' operation, which would be a lot more efficient and would let me drop the comparison <code>$0! &gt;= start</code> altogether. Something along the lines of</p> <pre><code>guard let prime = numbers.first(where: {$0 != nil}, start: start) else {break} </code></pre> <p>I also tried</p> <pre><code>guard let prime = (start...maxValue).first(where: {index in numbers[index] != nil}) else {break} </code></pre> <p>and that does work but it seems even more awkward. It does have the advantage of starting the search at the index <code>start</code> instead of index zero each time. What's the preferred way to search an array beginning somewhere in the middle of it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:45:02.670", "Id": "408562", "Score": "0", "body": "Welcome to Code Review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:25:31.463", "Id": "408568", "Score": "0", "body": "(One reference site is [Rosetta Code](https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Swift).)" } ]
[ { "body": "<p>To answer your immediate question: You can search in an array <em>slice:</em></p>\n\n<pre><code> guard let prime = numbers[start...].first(where: {$0 != nil}) else {break}\n</code></pre>\n\n<p>That works because array slices share their indices with the originating array.</p>\n\n<hr>\n\n<p>There is a small bug in your program, as one can see here:</p>\n\n<pre><code>let sieve = Sieve(4)\nprint(sieve.primes) // [2, 3, 4]\n</code></pre>\n\n<p>The reason is that the</p>\n\n<pre><code>if lo &lt; maxValue { ... }\n</code></pre>\n\n<p>loop does not include the last value. The test should be <code>lo &lt;= maxValue</code>.</p>\n\n<hr>\n\n<p>There are also some possible improvements: </p>\n\n<pre><code> let lo = 2 * prime!\n</code></pre>\n\n<p>can be replaced by</p>\n\n<pre><code> let lo = prime! * prime!\n</code></pre>\n\n<p>because all lower multiples have been “nilled” before. As a consequence, the outer loop </p>\n\n<pre><code> while start &lt;= maxValue { ... }\n</code></pre>\n\n<p>can be replaced by</p>\n\n<pre><code> while start * start &lt;= maxValue { ... }\n</code></pre>\n\n<p>Now instead of repeatedly searching for the next non-nil entry in the array you might as well <em>iterate</em> over the array. This allows also to get rid of the ugly forced unwrapping <code>prime!</code>:</p>\n\n<pre><code> for i in (2..&lt;numbers.count).prefix(while: { $0 * $0 &lt;= maxValue }) {\n if numbers[i] != nil {\n for x in stride(from: i * i, to: numbers.count, by: i) {\n numbers[x] = nil\n }\n }\n }\n</code></pre>\n\n<p>At this point it becomes apparent that the information in the <code>numbers</code> array is redundant: Each element is equal to its index or <code>nil</code>. Therefore a <em>boolean</em> array is sufficient instead of an array of optional integers, this reduces the required memory considerably.</p>\n\n<p>I suggest that you first try to implement that yourself, otherwise have a look at <code>func eratosthenesSieve()</code> in <a href=\"https://codereview.stackexchange.com/questions/192021/prime-number-generator-efficiency/192042#192042\">Prime Number Generator &amp; Efficiency</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:55:15.870", "Id": "408563", "Score": "0", "body": "Thanks for the welcome, and for pointing out that bug. I had rather hastily inserted that `if` statement when I found that the invocation of `stride` threw an exception when `lo >= numbers.count`. The (now deprecated) older form of the `for` loop, `for x = lo; x < numbers.count; x += prime` simply would have executed zero times in that case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:28:21.523", "Id": "211287", "ParentId": "211282", "Score": "0" } } ]
{ "AcceptedAnswerId": "211287", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:27:38.353", "Id": "211282", "Score": "1", "Tags": [ "swift" ], "Title": "Find index of array item starting at a given location" }
211282
<p>I was hoping that someone could review this code. </p> <p>My main concern is that the contents of main() are difficult to read. I thought about extracting some segments of code into functions (to aid comprehension) but it felt unnecessary because these segments are not completely repeated.</p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include &lt;random&gt; // Maps input in the range [0..1] to an output in the range [0..1]. // Represents the piecewise function: // y(x) = 2*x^2 when x &lt; 0.5 // = -2*x^2 + 4*t - 1 when x &gt;= 0.5 float easeInOutQuad(float normalisedTime) { auto &amp; t = normalisedTime; return t &lt; 0.5 ? 2*t*t : 2*t*(2 - t) - 1; } struct Tween { float begin; float change; float time{0}; float duration; float current() const { return begin + change*easeInOutQuad(time/duration); } }; int main() { sf::RenderWindow window{sf::VideoMode{500, 500}, "Snow"}; auto const inverseFramerate = 1.f/60; window.setFramerateLimit(static_cast&lt;unsigned&gt;(1/inverseFramerate)); auto const numberOfSnowflakes = 200; Tween tweens[numberOfSnowflakes]; float yPositions[numberOfSnowflakes]; auto generator = std::mt19937{}; // Returns a normally distributed random number. auto randomChangeInX = [&amp;generator]() { static auto distribution = std::normal_distribution&lt;float&gt;{0.f, 10.f}; return distribution(generator); }; // Returns a uniformly distributed random number in the range [min..max). auto randomBetween = [&amp;generator](float min, float max) { return std::generate_canonical&lt;float, 10&gt;(generator)*(max - min) + min; }; for (auto i = 0; i &lt; numberOfSnowflakes; ++i) { tweens[i].begin = randomBetween(0, window.getSize().x); tweens[i].change = randomChangeInX(); tweens[i].duration = randomBetween(1, 5); yPositions[i] = randomBetween(-20, window.getSize().y); } auto const defaultRadius = 5.f; auto circle = sf::CircleShape{}; while (window.isOpen()) { auto event = sf::Event{}; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } for (auto i = 0; i &lt; numberOfSnowflakes; ++i) { tweens[i].time += inverseFramerate; if (tweens[i].time &gt; tweens[i].duration) { tweens[i].begin += tweens[i].change; tweens[i].change = randomChangeInX(); tweens[i].time = 0; } yPositions[i] += 1/tweens[i].duration; if (yPositions[i] &gt; window.getSize().y) { yPositions[i] = -defaultRadius*2; tweens[i].begin = randomBetween(0, window.getSize().x); tweens[i].change = randomChangeInX(); tweens[i].time = 0; } } window.clear(); for (auto i = 0; i &lt; numberOfSnowflakes; ++i) { circle.setPosition(tweens[i].current(), yPositions[i]); circle.setRadius(defaultRadius/tweens[i].duration); window.draw(circle); } window.display(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:28:20.677", "Id": "408558", "Score": "0", "body": "This is how it originally looked, except that I had to add 4 spaces to the beginning of each line before I could submit the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:31:05.543", "Id": "408559", "Score": "2", "body": "Okay. In the future it is far more convenient to `ctrl-a` to select all the click on the `{}` on the top of the editor or press `ctrl-k` to have the editor format for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:40:43.807", "Id": "408575", "Score": "1", "body": "Welcome to Code Review! Looking at the code, this is the exact community to turn to." } ]
[ { "body": "<p><code>Tween</code> is not a very good name. How about <code>Snowflake</code>? And why is it a <code>struct</code> and exposing all of its implementation details. I would personally place it in a class, initialize its values via constructor, and give it a public function like <code>fall()</code> or something to update it each frame.</p>\n\n<pre><code>class Snowflake\n{\npublic:\n void fall();\nprivate:\n sf::CircleShape snowflake;\n float begin;\n float change;\n float time{ 0 };\n float duration;\n float current() const\n {\n return begin + change * easeInOutQuad(time / duration);\n }\n};\n</code></pre>\n\n<p>By putting the circle in the class you can update it internally. More on all that later.</p>\n\n<hr>\n\n<pre><code>float easeInOutQuad(float normalisedTime)\n{\n auto &amp; t = normalisedTime;\n return t &lt; 0.5 ? 2*t*t : 2*t*(2 - t) - 1;\n}\n</code></pre>\n\n<p>It seems a little unusual to assign a reference to the argument and then return the reference. I'm actually a little surprised this didn't boom. it's a trivially copied <code>float</code>. Just pass it by value.</p>\n\n<hr>\n\n<pre><code>auto const inverseFramerate = 1.f / 60;\nwindow.setFramerateLimit(static_cast&lt;unsigned&gt;(1 / inverseFramerate));\n</code></pre>\n\n<p>That is an odd way to write</p>\n\n<pre><code>window.setFramerateLimit(60);\n</code></pre>\n\n<p>Now you could replace the magic number 60 that I just passed here with a named constant but I would actually argue that this is one of those rare cases when you shouldn't. This will be the only call to this function and the name won't be more readable here. Most readers are likely to immediately recognize that the 60 is setting 60 fps.</p>\n\n<p>No cast. No equation. easily readable. less lines.</p>\n\n<hr>\n\n<pre><code>auto const numberOfSnowflakes = 200;\nTween tweens[numberOfSnowflakes];\nfloat yPositions[numberOfSnowflakes];\n</code></pre>\n\n<p>This is a much more useful named constant. However. Don't use C <code>array[]</code>s. <code>std::array</code> or <code>std::vector</code> are better C++ containers. <code>std::array</code> is static sized like the C-style <code>array[]</code> and <code>std::vector</code> is dynamically sized. Don't forget to <code>#include</code> whichever you choose to use. You should keep the constant but switch to the more preferred <code>constexpr</code></p>\n\n<pre><code>constexpr int number_of_snowflakes = 200;\n</code></pre>\n\n<hr>\n\n<pre><code>auto generator = std::mt19937{};\n</code></pre>\n\n<p>A lot of your difficult to read code revolves around your use and misuse of this object. Allow me to show you a slightly easier to use way of handling PRNG. I'd wrap it all into its own named function and do away with the two harder to read and use lambdas. Then inside the function you seed the generator and declare it <code>static</code> so it doesn't get destroyed when it goes out of scope.</p>\n\n<pre><code>//we take unsigned and return float in order to work with SFML's window size which is unsigned\nfloat generateRandom(unsigned min, unsigned max)\n{\n float real_min = static_cast&lt;float&gt;(min);\n float real_max = static_cast&lt;float&gt;(max);\n std::random_device rd;\n static const std::mt19937 generator(rd());\n std::uniform_real_distribution&lt;float&gt; distribution(real_min, real_max);\n\n return distribution(generator);\n}\n</code></pre>\n\n<p>Now when you want a value between 0 - width you do</p>\n\n<pre><code>start = generateRandom(0, window.getSize().x)\n</code></pre>\n\n<p>This is a weird reimplementation of <code>uniform_real_distribution</code>. You did it so you could work with negative ranges because you want your snowflakes to start off-screen. But all you need is an offset applied after the fact.</p>\n\n<pre><code>auto randomBetween = [&amp;generator](float min, float max)\n{\n return std::generate_canonical&lt;float, 10&gt;(generator)*(max - min) + min;\n}; \n</code></pre>\n\n<hr>\n\n<p>Now we get to initialization. In the future it is best to declare and initialize variables together. If you need helper functions have them defined beforehand and ready to use rather than defining them in between instantiation and initialization.</p>\n\n<pre><code>for (auto i = 0; i &lt; numberOfSnowflakes; ++i)\n{\n tweens[i].begin = randomBetween(0, window.getSize().x);\n tweens[i].change = randomChangeInX();\n tweens[i].duration = randomBetween(1, 5);\n yPositions[i] = randomBetween(-20, window.getSize().y);\n}\nauto const defaultRadius = 5.f;\nauto circle = sf::CircleShape{};\n</code></pre>\n\n<p>Most of this can be eliminated by doing two things. Move the <code>sf::Circle</code> into our new <code>Snowflake</code> class and we use default initialization within the class. You can also be completely rid of the second <code>yPositions</code> array as the <code>Snowflake</code> class circle can maintain its own position. You will have to pass the starting coordinates to the constructor because the <code>Snowflake</code> class won't have full access to the <code>sf::RenderWindow</code> class. Our class is now starting to look like this:</p>\n\n<pre><code>class Snowflake\n{\npublic:\n explicit Snowflake(sf::Vector2f start_position);\n\n void fall();\nprivate:\n float change{ generateRandom(1, 10) };\n float duration{ generateRandom(1, 5) };\n float time{ 0 };\n sf::Vector2f position;\n sf::CircleShape snowflake{ default_radius / duration };\n float current() const\n {\n return position.x + change * easeInOutQuad(time / duration);\n }\n};\n</code></pre>\n\n<p>You can do the initialization like so:</p>\n\n<pre><code>std::vector&lt;Snowflake&gt; snowflakes;\nsnowflakes.reserve(number_of_snowflakes);\nfor (int i = 0; i &lt; number_of_snowflakes; ++i)\n{\n float x = generate_random(0, window.getSize().x);\n float y = generate_random(-20, window.getSize().y);\n sf::Vector2f start_position(x, y);\n snowflakes.emplace_back(Snow(start_position));\n}\n</code></pre>\n\n<p>This will give you a nice standard container of snowflakes at default initialized</p>\n\n<hr>\n\n<p>So now we get to your animation loop. I see now why you did <code>inverseFramerate</code> now, but it was a complicated way of having your snow fall at varying rates. As you have moved everything into the <code>Snowflake</code> class you can have a much simpler animation loop.</p>\n\n<pre><code>while (window.isOpen())\n{\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n window.close();\n }\n }\n\n for (auto&amp;&amp; snow : snowflakes)\n {\n snow.fall(window.getSize());\n }\n\n window.clear();\n for (auto&amp;&amp; snow : snowflakes)\n {\n snow.draw(window);\n }\n window.display();\n}\n</code></pre>\n\n<p>All that leaves us with is implementing the <code>fall()</code> and <code>draw()</code> methods from above. <code>draw()</code> is simple and would look something like this:</p>\n\n<pre><code>void draw(sf::RenderWindow&amp; window) { window.draw(snowflake); }\n</code></pre>\n\n<p>and the <code>fall()</code> method I just copied over your implementation details using my new class member variables. It looks something like this:</p>\n\n<hr>\n\n<p>Put it all together and it would look like this:</p>\n\n<pre><code>#include &lt;random&gt;\n#include &lt;vector&gt;\n\n#include &lt;SFML/Graphics.hpp&gt;\n\nconstexpr int number_of_snowflakes = 200;\nconstexpr float single_frame = 1.F / 60;\nconstexpr float default_radius = 5.F;\n\n// Maps input in the range [0..1] to an output in the range [0..1].\n// Represents the piecewise function:\n// y(x) = 2*x^2 when x &lt; 0.5\n// = -2*x^2 + 4*t - 1 when x &gt;= 0.5\nfloat ease_in_and_out(float normalised_time)\n{\n float t = normalised_time;\n return t &lt; 0.5 ? 2 * t*t : 2 * t*(2 - t) - 1;\n}\n\n//we take unsigned and return float in order to work with SFML's window size which is unsigned\nfloat generate_random(unsigned min, unsigned max)\n{\n float real_min = static_cast&lt;float&gt;(min);\n float real_max = static_cast&lt;float&gt;(max);\n static std::random_device rd;\n static std::mt19937 generator(rd());\n std::uniform_real_distribution&lt;float&gt; distribution(real_min, real_max);\n\n return distribution(generator);\n}\n\nclass Snowflake\n{\npublic:\n explicit Snowflake(sf::Vector2f start_position) : position{ start_position }\n { \n snowflake.setPosition(position);\n begin = start_position.x;\n }\n\n void fall(sf::Vector2u window_size)\n {\n time += single_frame;\n if (time &gt; duration)\n {\n begin += change;\n change = generate_random(1, 10);\n time = 0.F;\n }\n\n position.y = snowflake.getPosition().y;\n position.y += 1 / duration;\n if (position.y &gt; window_size.y)\n {\n position.y = -10.F;\n begin = generate_random(0, window_size.x);\n change = generate_random(1, 10);\n time = 0;\n snowflake.setRadius(default_radius / duration);\n }\n\n position.x = shift_x();\n snowflake.setPosition(position);\n }\n void draw(sf::RenderWindow&amp; window) { window.draw(snowflake); }\nprivate:\n sf::Vector2f position;\n float begin;\n float change{ generate_random(1, 10) };\n float duration{ generate_random(1, 5) };\n float time{ 0 };\n sf::CircleShape snowflake{ default_radius / duration };\n\n float shift_x() const\n {\n return begin + change * ease_in_and_out(time / duration);\n }\n};\n\nint main()\n{\n sf::RenderWindow window{ sf::VideoMode{500, 500}, \"Snow\" };\n window.setFramerateLimit(60);\n\n std::vector&lt;Snowflake&gt; snowflakes;\n snowflakes.reserve(number_of_snowflakes);\n for (int i = 0; i &lt; number_of_snowflakes; ++i)\n {\n float x = generate_random(0, window.getSize().x);\n float y = generate_random(0, window.getSize().y) - 20.F;\n sf::Vector2f start_position(x, y);\n snowflakes.emplace_back(Snowflake(start_position));\n }\n\n while (window.isOpen())\n {\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n window.close();\n }\n }\n\n for (auto&amp;&amp; snow : snowflakes)\n {\n snow.fall(window.getSize());\n }\n\n window.clear();\n for (auto&amp;&amp; snow : snowflakes)\n {\n snow.draw(window);\n }\n window.display();\n }\n}\n</code></pre>\n\n<p>Could this still be improved? Sure. I left a few magic numbers behind, and we all know those are bad. The names are more descriptive and better describe what is happening but they could probably be improved. SFML allows for classes to inherit from <code>sf::Drawable</code> and you can fix the syntax so it can be called <code>window.draw(Snowflake);</code> instead of passing a reference to the window object to your class. I would also probably extract the <code>fall()</code> method to a couple private helpers. This would</p>\n\n<ul>\n<li>hide the implementation details of the public method that don't need to be exposed.</li>\n<li>allow you to simplify some of the functionality. (There's a lot of resetting values to default.)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T06:48:41.513", "Id": "211303", "ParentId": "211283", "Score": "5" } }, { "body": "<p>I see some things that may help you improve your program.</p>\n\n<h2>Use objects</h2>\n\n<p>The <code>Tween struct</code> is a start, but this code would really benefit from the use of actual objects. Right now, the <em>data</em> for each snowflake is in <code>Tween</code>, but most of the <em>code</em> to manipulate it is in <code>main</code> which makes the code much harder to read and understand than it should be. Even more strangely, each <code>Tween</code> contains its own <code>x</code> coordinate, but a separate array holds the <code>y</code> coordinates! </p>\n\n<h2>Reconsider the use of random numbers</h2>\n\n<p>The usual advice I give is to use a better random number generator, but here, I think the opposite advice is in order. Because <code>std::generate_canonical</code> calls the generator multiple times to assure sufficient entropy (10 bits in your program), it can have the effect of slowing down the program if called frequently. In this case, the simpler <code>std::uniform_real_distribution</code> would probably be a better choice.</p>\n\n<h2>Avoid plain arrays</h2>\n\n<p>In most instances in modern C++, a <code>std::array</code> is better than a plain C-style array. Not only does the size accompany the structure, but it also simplifies the use of standard algorithms on the array.</p>\n\n<h2>Use SFML more fully</h2>\n\n<p>A better use of SFML in this case would be to have a <code>Snowflake</code> class, or even better, a <code>Snowstorm</code> class that contains all of the snowflakes, that that derives from both the <code>sf::Transformable</code> and <code>sf::Drawable</code> classes. Doing so would allow your main loop to be much more readable:</p>\n\n<pre><code>while (window.isOpen()) {\n auto event = sf::Event{};\n while (window.pollEvent(event)) {\n if (event.type == sf::Event::Closed) {\n window.close();\n }\n }\n snowstorm.update(inverseFramerate);\n window.clear();\n window.draw(snowstorm);\n window.display();\n}\n</code></pre>\n\n<p>See the <a href=\"https://www.sfml-dev.org/tutorials/2.5/graphics-vertex-array.php\" rel=\"noreferrer\">SFML tutorial on creating entities</a> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T14:05:42.730", "Id": "211328", "ParentId": "211283", "Score": "5" } } ]
{ "AcceptedAnswerId": "211303", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T19:59:16.783", "Id": "211283", "Score": "7", "Tags": [ "c++", "animation", "sfml" ], "Title": "2D falling snow animation" }
211283
<p>I have written a C# class to perform LZ77 compression ( per RFC 1951 ), to incorporate in my <a href="https://codereview.stackexchange.com/q/210757/130590">RFC 1951 deflate implementation</a> ( posted on Jan 2 ).</p> <p>The usual method (per RFC 1951) is to use a 3-byte hash to get started, then iterate through a chain of earlier 3-byte matches. However this can be slow if the chains become long. ZLib has heuristics (which I don't fully understand!) to shorten the search, RFC 1951 suggests "To avoid a worst-case situation, very long hash chains are arbitrarily truncated at a certain length, determined by a run-time parameter."</p> <p>That all seems a little messy, so I decided to see if a "re-hashing" approach would work : suppose the string ABC is already recorded, and we encounter a new ABC, the new position of ABC will in future be used in preference to the old (position) for coding ABC (as it's "closer") so we re-hash the old position as a 4-byte hash instead. If there is already a matching 4-byte entry, then the lesser position becomes a 5-byte hash, etc.</p> <p>Example: given input string ABCABCDABC, the hash dictionary updates as follows ( each section delimited by ';' corresponds to the input position advancing by one byte ):</p> <p>0(ABC); 1(BCA); 2(CAB); 0(ABCA), 3(ABC); 4(BCD); 5(CDA); 6(DAB); 3(ABCD), 7(ABC);</p> <p>Here's the code:</p> <pre><code>class Matcher { public Matcher ( int n ) { Hash = new Entry[ n * 5 ]; // A larger table reduces the number of hash collisions, but uses more memory. } private const int MinMatch = 3, MaxMatch = 258, MaxDistance = 32768; // RFC 1951 limits. public int Match( byte [] input, int position, uint hash, out int matchDistance, bool look ) // Record the specified input string starting at position for future matching, and (if look=true) // look for the longest prior match. hash is a function of MinMatch bytes of input starting at // position ( can simply be the concatenated bytes ). { int matchPosition = InsertLook( input, position, hash, MinMatch ); matchDistance = position - matchPosition; if ( ! look || matchPosition &lt; 0 || matchDistance &gt; MaxDistance ) return 0; int match = MinMatch; int bestMatch = ExtraMatch( input, position, matchPosition, match ); // Look for a match longer than MinMatch. while ( bestMatch &lt; MaxMatch &amp;&amp; position + bestMatch &lt; input.Length ) { hash += hash * 4 + input[position+match]; match += 1; matchPosition = Look( input, position, hash, match ); if ( matchPosition &lt; 0 || position - matchPosition &gt; MaxDistance ) break; int newMatch = ExtraMatch( input, position, matchPosition, match ); if ( newMatch &gt; bestMatch ) { matchDistance = position - matchPosition; bestMatch = newMatch; } } return bestMatch; } private Entry [] Hash; // The Hash table used to find a matching string. private class Entry // Alternatively make Hash an array of positions and also store Length and Next in arrays. { public int Position, Length; // Position and Length of input substring. public Entry Next; // To handle hash collisions. public Entry( int position, int length, Entry next ){ Position = position; Length = length; Next = next; } } private int Look( byte[] input, int position, uint hash, int length ) // Look in the hash table for a match of specified length. { uint hashindex = hash % (uint) Hash.Length; for ( Entry e = Hash[ hashindex ]; e != null; e = e.Next ) { if ( e.Length == length &amp;&amp; Equal( input, position, e.Position, length ) ) return e.Position; } return -1; } private int InsertLook( byte[] input, int position, uint hash, int length ) // Look in the hash table for the specified string, and also insert the specified string into the table. // If there is a match with an existing string, it's position is returned, and the existing string is re-hashed. { uint hashindex = hash % (uint) Hash.Length; for ( Entry e = Hash[ hashindex ]; e != null; e = e.Next ) { if ( e.Length == length &amp;&amp; Equal( input, position, e.Position, length ) ) { int result = e.Position; e.Position = position; hash += hash * 4 + input[ result + length ]; Rehash( input, result, hash, length + 1 ); return result; } } Hash[ hashindex ] = new Entry( position, length, Hash[ hashindex ] ); return -1; } private void Rehash( byte[] input, int position, uint hash, int length ) { while ( true ) { uint hashIndex = hash % (uint) Hash.Length; Entry e = Hash[ hashIndex ]; while ( true ) { if ( e == null ) { Hash[ hashIndex ] = new Entry( position, length, Hash[ hashIndex ] ); return; } else if ( e.Length == length &amp;&amp; Equal( input, position, e.Position, length ) ) { int eposition = e.Position; if ( eposition &lt; position ) // The smaller position is rehashed. { e.Position = position; hash += hash * 4 + input[ eposition + length ]; position = eposition; } else { hash += hash * 4 + input[ position + length ]; } length += 1; break; } e = e.Next; } } } private static int ExtraMatch( byte [] input, int p, int q, int match ) { int limit = input.Length; if ( limit - p &gt; MaxMatch ) limit = p + MaxMatch; while ( p + match &lt; limit &amp;&amp; input[ p + match ] == input[ q + match ] ) match += 1; return match; } private static bool Equal( byte [] input, int p, int q, int length ) { for ( int i = 0; i &lt; length; i+=1 ) if ( input[ p + i ] != input[ q + i ] ) return false; return true; } } </code></pre> <p>ZLib (on default settings) seems to be faster ( although I have not tried to fully optimise my code yet), but at the expense of less compression ( since truncating the search means it doesn't always find the longest LZ77 match ).</p> <p>For example, my code compresses the file FreeSans.ttf from 264,072 bytes to 146,542 bytes, the ZLib compressed length is 148,324 bytes.</p> <p>Questions:</p> <p>(1) What do you think of this approach compared to the 'standard' approach, are there any hidden issues I haven't foreseen?</p> <p>(2) Re-hashing seems a fairly obvious and natural idea, have you seen it before?</p> <p>(3) Would using arrays instead of the Entry record be a good idea?</p> <p>(4) I am thinking of using two hash tables, "sliding" every 16kb of input, to reduce hash collisions when the input is more than 32kb long ( and also reduce memory usage), would that be a good idea?</p> <p>(5) Any other suggestions?</p> <p>(6) The algorithm as is performs poorly on long repeats ( for example 1,000 zeros ). How can I fix that? [ This question added later ]</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T07:28:07.897", "Id": "408607", "Score": "0", "body": "In comparison to your last code I really like this one! The only two names that aren't so clear are the `p` & `q` in `ExtraMatch` and `Equal` ok, and maybe the `n` in `Matcher` ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:49:50.523", "Id": "408679", "Score": "0", "body": "A simple advice with regards to how the is read is adding more blank lines in your code. Currently your code seem a little too dense. Adding a blank line before/after conditional and control statements." } ]
[ { "body": "<blockquote>\n<p>I apologize in advance that this answer does not contribute much to the actual functions of your code; However, I firmly believe that writing code that is easy for others to read/understand is an important element of feedback from any code review.</p>\n</blockquote>\n<p>At first glance, I would note that there can be a little bit more adherence to <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions\" rel=\"nofollow noreferrer\">C# Coding Conventions</a>.</p>\n<p><em>(Aside) I admit it is a bit of a discipline thing (think of setting a table for dinner... The fork and knife shouldn't be upside down with the handles faced away from the diner -- it's not functionally &quot;wrong&quot; but you'll get a weird face from people when they find out you were responsible -- it doesn't conform to conventions).</em></p>\n<p>In particular here are a few bits that standout the most to me:</p>\n<p><strong>Exessive spacing.</strong><br />\nYour &quot;excessive&quot; spacing (really just one too many)<br />\nmakes the code a l i t t l e h a r d e r t o r e a d.</p>\n<p>For example:</p>\n<pre><code>public Matcher ( int n )\npublic int Match( byte [] input, int position, uint hash, out int matchDistance, bool look )\n</code></pre>\n<p>Should look more like this:</p>\n<pre><code>public Matcher(int n)\npublic int Match(byte[] input, int position, uint hash, out int matchDistance, bool look)\n</code></pre>\n<p><strong>Proper case and underscore for your private fields</strong><br />\nHere we have a private field called <code>Hash</code></p>\n<pre><code>private Entry [] Hash;\n</code></pre>\n<p>Which according to naming conventions should be</p>\n<pre><code>private readonly Entry[] _hash; // note the underscore and lower case\n</code></pre>\n<p><em>Note: I have also added a <code>readonly</code> to it which according to your code is what you should do.</em>\nYou could alternatively do a property, such as:</p>\n<pre><code>public Entry[] Hash { get; private set; } // note properties are capitalized\n</code></pre>\n<p><em>Note: Don't do this with your code &quot;as-is&quot;, since your <code>Hash</code> object is currently a private one -- you will have an accessibility problem. I just added this as an example of a property declaration since I noticed you had none.</em></p>\n<p><strong>Validating arguments.</strong><br />\nThis is something that you may or may not require in every method as sometimes this can get a little out of hand. However, for the case of a constructor and key (usually every publicly exposed) methods, I will state that you MUST do it.</p>\n<pre><code>public Matcher(int n)\n{\n // throw an error if passed zero or negative values\n if (n &lt; 0) throw new ArgumentException(&quot;must be greater than zero&quot;, nameof(n));\n\n _hash = new Entry[n*5];\n}\n</code></pre>\n<hr />\n<h2>Hmmmm... smelly code.</h2>\n<p>I am not familiar with RFC 1951, so I hesitate to dive into the efficiencies or accuracy of your code. But asides from some of the coding convention related issues I noted earlier, there are a few sections that look like bad / smelly code (again, I cannot be certain about the results due to my lack of knowledge with RFC 1951).</p>\n<p><strong>Two infinite while loops.</strong><br />\nLet's start here...</p>\n<pre><code>private void Rehash( byte[] input, int position, uint hash, int length )\n{\n while ( true ) // &lt;----!?\n {\n uint hashIndex = hash % (uint) Hash.Length;\n Entry e = Hash[ hashIndex ]; \n\n while ( true ) // &lt;----!?\n {\n ...\n</code></pre>\n<p>I'm sure others will tend to agree that this doesn't sit right. It's quite unusual to see a <code>while(true)</code> at all. To be blunt, it feels like a lazy design attempt, but the reason it stands out to me is because it is inside a method which name suggests a singular task / operation (<code>Rehash</code>). If the method name was something like <code>RehashForeverAndEver</code> then I would probably have glossed over this and just assumed the infinite loop was intended.</p>\n<p><strong>Use of public fields.</strong><br />\nI'm looking at this private nested class <code>Entry</code>, that you have...</p>\n<pre><code>private class Entry\n{ \n public int Position, Length;\n public Entry Next;\n public Entry( int position, int length, Entry next )\n {\n Position = position;\n Length = length;\n Next = next;\n }\n}\n</code></pre>\n<p>I generally hesitate when I see the use of public fields. Due to the -- let's call it -- stigma behind the use of them. It throws off some heavy code smell. I would carefully reconsider the design of this class.</p>\n<blockquote>\n<p>I was about to note areas of possible optimizations with how you are handling the <code>byte[]</code> operations, but I'm going to hold off, as I think that this post is plenty long now. I encourage you to break down your code into small concise methods and re-post just the methods that you feel need code review (it would very likely yield you a more focused review and profitable feedback).</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T11:57:36.623", "Id": "408631", "Score": "0", "body": "Underscore-prefixing isn't mentioned anywhere in the naming guidelines. Nevertheless +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:07:30.393", "Id": "408635", "Score": "1", "body": "@Heslacher -- You're right. I am so used to seeing private fields being prefixed with an underscore in C# that I incorrectly made it appear like it was part of the official naming guideline. I hope these comments will serve as a footnote to my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T13:44:38.840", "Id": "408647", "Score": "0", "body": "I would suggest `Hash` still be readonly with `public Entry[] Hash { get; }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:46:41.040", "Id": "408677", "Score": "2", "body": "I would advice against omitting curly brackets in conditional statements. I guess it's personal preferences in the end, but I have seen subtle bugs being introduced (fortunately caught in code review) due to a developer adding line before e.g. an exception. As said, it's not a rule, but it does help keep consistency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:54:12.223", "Id": "408680", "Score": "0", "body": "@RickDavin - Technically, given his current code the `Entry` type is a private class nested within, so creating a property would not work. I would also argue that exposing the `Entry` class (take a look at it) has a bit of code smell and I wouldn't advise putting that out there in the wild. --- I did attempt to note this in my answer, but maybe I should have just not put anything about property declarations in my answer at all?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T11:43:38.067", "Id": "211323", "ParentId": "211284", "Score": "3" } }, { "body": "<p>To partially answer question (6), the Rehash function can be modified to start:</p>\n\n<pre><code>private void Rehash( byte[] input, int position, uint hash, int length )\n{\n while ( true )\n {\n if ( length &gt; MaxMatch ) return;\n</code></pre>\n\n<p>The logic is that since the limit on a match is MaxMatch (=258), there is no point hashing a string longer than that. This means it is now possible, albeit rather slow, to compress long repeat sequences ( which are quite common when compressing PDF images ). </p>\n\n<p>I'm not very satisfied with this solution yet though, I think the algorithm could be modified to process long repeats efficiently and elegantly, but I haven't figured out how. Even with this fix, long repeats cause the processing to go much slower than normal - the outer loop of Rehash is executed nearly 258 times for each byte of input processed, when processing a long repeat.</p>\n\n<p>Edit: I think skipping to the last MaxMatch bytes of a repeat sequence might work, as earlier potential matches will never be used ( again due to the MaxMatch limit ). I have not yet tried to code this.</p>\n\n<p>Further Edit: After more investigation, my conclusion is that the re-hashing is not an effective approach. The cost appears to exceed any benefit, at least in the context of RFC 1951. </p>\n\n<p>What seems to be more interesting is trying different block sizes, which seems to produce improved compression for relatively mimimal cost ( for example, for each block, starting with a small block size, and testing whether doubling the block size results in smaller output ).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T10:02:12.153", "Id": "211369", "ParentId": "211284", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:14:32.843", "Id": "211284", "Score": "8", "Tags": [ "c#", "compression" ], "Title": "RFC 1951 compression LZ77 re-hashing approach" }
211284
<p>I have a "working sheet" that contains 15000+ rows. In column A is an identifier for that row. There are over 20 different identifiers i.e 9W, AM, AV, BG, CY, HJ etc. etc.</p> <p>My current code looks for each row on "Working Sheet" that has 9W in column A, cuts and pastes that row into a sheet called 9W. Once finished it moves to AM, finds am in Column A, cuts and pastes each row into a sheet called AM. Process repeats until all Identifiers have been done.</p> <p>Here is a sample of the current code that I have created with my limited knowledge:</p> <pre><code>Sub Test() 'Do 9W Dim sht1 As Worksheet, sht2 As Worksheet Dim i As Long Set sht1 = ThisWorkbook.Worksheets("Working Sheet") Set sht2 = ThisWorkbook.Worksheets("9W") For i = 2 To sht1.Cells(sht1.Rows.Count, "A").End(xlUp).Row If sht1.Range("A" &amp; i).Value = "9W" Then sht1.Range("A" &amp; i).EntireRow.Cut sht2.Range("A" &amp; sht2.Cells(sht2.Rows.Count, "A").End(xlUp).Row + 1) End If Next i 'Do AM Dim sht3 As Worksheet, sht4 As Worksheet Dim i1 As Long Set sht3 = ThisWorkbook.Worksheets("Working Sheet") Set sht4 = ThisWorkbook.Worksheets("AM") For i1 = 2 To sht3.Cells(sht3.Rows.Count, "A").End(xlUp).Row If sht3.Range("A" &amp; i1).Value = "AM" Then sht3.Range("A" &amp; i1).EntireRow.Cut sht4.Range("A" &amp; sht4.Cells(sht4.Rows.Count, "A").End(xlUp).Row + 1) End If Next i1 'DO AV Dim sht5 As Worksheet, sht6 As Worksheet Dim i2 As Long Set sht5 = ThisWorkbook.Worksheets("Working Sheet") Set sht6 = ThisWorkbook.Worksheets("AV") For i2 = 2 To sht5.Cells(sht5.Rows.Count, "A").End(xlUp).Row If sht5.Range("A" &amp; i2).Value = "AV" Then sht5.Range("A" &amp; i2).EntireRow.Cut sht6.Range("A" &amp; sht6.Cells(sht6.Rows.Count, "A").End(xlUp).Row + 1) End If Next i2 'DO BG Dim sht7 As Worksheet, sht8 As Worksheet Dim i3 As Long Set sht7 = ThisWorkbook.Worksheets("Working Sheet") Set sht8 = ThisWorkbook.Worksheets("BG") For i3 = 2 To sht7.Cells(sht7.Rows.Count, "A").End(xlUp).Row If sht7.Range("A" &amp; i3).Value = "BG" Then sht7.Range("A" &amp; i3).EntireRow.Cut sht8.Range("A" &amp; sht8.Cells(sht8.Rows.Count, "A").End(xlUp).Row + 1) End If Next i3 End Sub </code></pre>
[]
[ { "body": "<p>As long as all the rows in your working sheet have a valid identifier, you can simplify this process a <strong>lot</strong> by looking at each row and looking up the Sheet you're supposed to copy the row to.</p>\n\n<p>This allows you to write a <strong>single</strong> loop instead of a loop for each ID there is:</p>\n\n<pre><code>Dim source As Worksheet\nDim target As Worksheet\nDim targetRow As Long\n\nSet source = ThisWorkbook.Worksheets(\"Working Sheet\")\n' As long as there is a row to cut and paste\nDo While source.Cells(\"A2\").Value &lt;&gt; vbNullString\n ' select where the row is supposed to go\n Set target = ThisWorkbook.Worksheets(source.Cells(\"A2\").Value)\n targetRow = target.Cells(target.Rows.Count, \"A\").End(xlUp).Row + 1\n ' and transfer it using copy &amp; delete\n With source.Range(\"A2\").EntireRow\n .Copy target.Range(\"A\" &amp; targetRow)\n .Delete xlShiftUp\n End With\nLoop\n</code></pre>\n\n<p>Of course if that's not the case, this simplification still applies: Iterate the rows of the worksheet <strong>once</strong> and only Copy&amp;Delete the rows where the identifier matches one of the allowed identifiers.</p>\n\n<p>If deleting the rows from the working sheet is not correct, or you don't want to move every row, you will need to iterate using a For Loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:56:41.637", "Id": "408564", "Score": "0", "body": "`While...Wend` should be `Do While...Loop`, and not involving the clipboard (assuming only the values are needed) would be even faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:00:11.950", "Id": "408565", "Score": "0", "body": "thanks for the syntax fix. I have no idea how to fix that clipboard issue, though...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T07:19:15.403", "Id": "408606", "Score": "0", "body": "Thanks , however the Code stops at the Do While line.\nI changed the \"A2\" to 1,2 (Row, Column) and it cut / pasted the 1st row once correctly, then stopped.. any ideas" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:51:43.367", "Id": "408644", "Score": "1", "body": "I don't think this code shifts cells up after cutting. So the first iteration would work, but then it will *always* be blank." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T13:28:29.843", "Id": "408646", "Score": "0", "body": "@RyanWildry I think I fixed that now :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:52:38.373", "Id": "211291", "ParentId": "211285", "Score": "2" } }, { "body": "<p>If you are only concerned with moving values (e.g. formats aren't important) from the Working Sheet to all other sheets, this approach should be significantly faster than copy and pasting the cells.</p>\n\n<p>This method starts by sorting the cells first so like cells are grouped together. The method will build up a range as it iterates, and when it encounters a new value it will dump the built up Range to the corresponding sheet. In my brief testing, this was able to complete moving 20,000 cells to three different sheets in less than 1 second.</p>\n\n<pre><code>Public Sub MoveData()\n On Error GoTo ErrorHandler:\n\n Dim LastRow As Long\n Dim Cell As Range\n Dim SearchRange As Range\n Dim FilterRange As Range\n Dim PreviousValue As String\n Dim JoinedRange As Range\n Dim FirstIteration As Boolean\n Dim RangeToJoin As Range\n Dim SourceSheet As Worksheet\n Dim MyTimer As Long\n\n Application.ScreenUpdating = False\n Application.Calculation = xlCalculationManual\n\n MyTimer = Timer\n Set SourceSheet = ThisWorkbook.Worksheets(\"Sheet1\")\n\n 'Sort the data together so it is grouped\n With SourceSheet\n LastRow = .Cells(.Rows.Count, \"A\").End(xlUp).Row + 1\n LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1\n Set SearchRange = .Range(.Cells(1, 1), .Cells(LastRow, 1)) 'Search only in column A, where sheet names are\n Set FilterRange = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn)) 'Area to sort\n .Sort.SortFields.Add Key:=SearchRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal\n End With\n\n FirstIteration = True\n For Each Cell In SearchRange\n\n 'Don't process changes for the first row\n If Not FirstIteration Then\n If PreviousValue = Cell.Value2 And Len(Cell.Value2) &gt; 0 Then\n Set RangeToJoin = SourceSheet.Range(SourceSheet.Cells(Cell.Row, 1), SourceSheet.Cells(Cell.Row, LastColumn))\n\n If JoinedRange Is Nothing Then\n Set JoinedRange = RangeToJoin\n Else\n Set JoinedRange = Union(JoinedRange, RangeToJoin)\n End If\n ElseIf Len(PreviousValue) &gt; 0 Then\n With ThisWorkbook.Sheets(PreviousValue)\n LastRow = .Cells(.Rows.Count, \"A\").End(xlUp).Row + 1\n .Range(.Cells(LastRow, 1), .Cells(JoinedRange.Rows.Count + LastRow - 1, JoinedRange.Columns.Count)).Value = JoinedRange.Value\n Set JoinedRange = Nothing\n End With\n End If\n End If\n\n FirstIteration = False\n PreviousValue = Cell.Value2\n Next\n\n 'Clear the values on the sheet\n SourceSheet.Cells.ClearContents\n\n Application.ScreenUpdating = True\n Application.Calculation = xlCalculationAutomatic\n Debug.Print \"Process took : \" &amp; Timer - MyTimer\n Exit Sub\n\nErrorHandler:\n 'Restore state if there was an issue\n Application.ScreenUpdating = True\n Application.Calculation = xlCalculationAutomatic\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:50:03.483", "Id": "211346", "ParentId": "211285", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:26:34.383", "Id": "211285", "Score": "3", "Tags": [ "vba" ], "Title": "Cut and paste rows to new sheet based on different criteria in Column A" }
211285
<p>I made a Flask app that consists of 3 pages. </p> <ul> <li>Index: Indexes to the 2 pages</li> <li>SubnetOverview: SSH's into the server and executes <code>ifconfig</code>, then returns the output to a webpage.</li> <li>AddSubnet: Has a HTML form where the administrator can fill in the desired VLAN id and subnet. This gets added to the <code>netplan</code> file and <code>netplan apply</code> gets executed to apply the changes.</li> </ul> <p><pre> #Flask app that interacts with a router running on a virtual machine, enbales administrator to list current network interfaces and make a new subinterface via SSH.</p> <code>from flask import Flask, render_template, request, redirect import paramiko import ssl app = Flask(__name__) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.load_cert_chain('certificates/cert.pem', 'certificates/key.pem') SERVER_IP = "192.168.0.80" SERVER_USERNAME = "root" SERVER_PASSWORD = "secret123" SERVER_PORT = 22 SERVER_IFCONFIG = "/sbin/ifconfig" @app.route('/') def index(): return render_template('index.html') @app.route('/SubnetOverview') def SubnetOverview(): #Try to SSH into the server and execute the command client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD) stdin, stdout, stderr = client.exec_command(SERVER_IFCONFIG, get_pty=True) output = stdout.readlines() output = ''.join(output) output = output.replace("\r\n", "&lt;br /&gt;") client.close() return render_template('SubnetOverview.html', ssh_output=output) @app.route('/AddSubnet', methods = ['POST', 'GET']) def AddSubnet(): if request.method == 'POST': #Getting the data from the HTML form formdata = request.form.to_dict() vlanid = formdata.get('vlanid') address = formdata.get('address') command = " vlan" + vlanid + ":\n id: " + vlanid + "\n link: eth0\n addresses: [ \"" + address + "\" ]\n" #Opening an SFTP connection transport = paramiko.Transport((SERVER_IP, SERVER_PORT)) transport.connect(username=SERVER_USERNAME, password=SERVER_PASSWORD) sftp = paramiko.SFTPClient.from_transport(transport) file=sftp.file('/etc/netplan/01-network-manager-all.yaml', "a", -1) file.write(command) file.flush() SERVER_COMMAND = "sudo netplan apply" sftp.close() transport.close() #Opening SSH connection to send a command that apply's the config client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD) stdin, stdout, stderr = client.exec_command(SERVER_COMMAND, get_pty=True) client.close() return redirect("/SubnetOverview") return render_template('AddSubnet.html') if __name__ == "__main__": app.run(host='0.0.0.0', port=443, ssl_context=context) </code></pre> <p></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:26:39.107", "Id": "211286", "Score": "2", "Tags": [ "python", "linux", "flask" ], "Title": "Flask app to administrate network interfaces" }
211286
<p>I was recently asked this question in an interview. Here is the solution I came up with. Please let know if I could have done this differently or in a more efficient manner.</p> <p>The question is as follows:</p> <blockquote> <p>Determine The Top Two Clothes Sizes In The Following Array</p> <pre><code>["XS","S","S","M","L","XL","XLL","XL","XL","M","M","M","XS","XS","XS","XS"] </code></pre> <p>The solution should be <code>[ 'XS', 'M' ]</code> since XS occurs 5 times and M occurs 4 times.</p> </blockquote> <pre><code>function determineTopTwo(arr){ let map = {}; let resultArr = []; let result = []; for(let i = 0; i &lt; arr.length; i++){ if(!map[arr[i]]){ map[arr[i]]=1; }else{ map[arr[i]]++; } } for(key in map){ resultArr.push([map[key],key]); } let newArr = resultArr.sort((a,b)=&gt;{ return a[0]-b[0]; }); result.push(newArr[newArr.length-1][1], newArr[newArr.length-2][1]); return result; } </code></pre>
[]
[ { "body": "<p>You didn't specify if you were allowed to use <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> features or not but presumably you were, since you used <code>let</code> and arrow functions. As an interviewer, I would note that you used those features, yet you iterated over the array using a regular <code>for</code> loop instead of using <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"noreferrer\"><code>for...of</code></a>. That isn't necessarily a bad thing since it demonstrates that you know how to increment a counter in a standard loop and then use that for indexing into the array, but you don't have to if you use a <code>for...of</code> loop.</p>\n\n<p>The technique for sorting the array is good, though because <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"noreferrer\"><code>Array.prototype.sort()</code></a> \"<em>sorts the elements of an array <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" rel=\"noreferrer\">in place</a> and returns the array</em>\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"noreferrer\">1</a></sup> there isn't really a need to store the value in <code>newArr</code> because <code>resultArr</code> is sorted.</p>\n\n<blockquote>\n<pre><code>let newArr = resultArr.sort((a,b)=&gt;{\n return a[0]-b[0];\n});\n</code></pre>\n</blockquote>\n\n<p>You could have just returned the first two elements of <code>resultArr</code>.</p>\n\n<p>Also, <code>const</code> could have been used for any variable that is never re-assigned - including arrays that merely have elements pushed into them - to avoid accidental re-assignment. </p>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort</a></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T22:30:00.583", "Id": "408579", "Score": "0", "body": "Thank you very much. I'm a bit unfamiliar with the for...of operator but i'll definitely have a look. You are absolutely right about the array as well, i will make the changes accordingly. thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:25:57.420", "Id": "211293", "ParentId": "211290", "Score": "6" } }, { "body": "<h2>Two bugs</h2>\n\n<p>There is a bug when you have only less than two unique sizes. Trying to access an undefined array <code>newArr[newArr.length-1][1], newArr[newArr.length-2][1]</code> throws if <code>newArray.length &lt; 2</code></p>\n\n<p>Bug in hiding waiting to pounce. The variable <code>key</code> has not been declared and thus has been created in the global scope. This is bad mistake and can result in very hard to find bugs in totally unrelated code. You should use \"use strict\" to catch such errors early.</p>\n\n<h2>General review notes</h2>\n\n<ul>\n<li>Spaces between operators , spaces after <code>for</code>, <code>if</code>, <code>else</code>, <code>,</code>, and <code>=&gt;</code> and befor <code>else</code> and <code>=&gt;</code></li>\n<li>There is no need to create the array <code>result</code>, you can create it as you return it. EG <code>return [newArr[newArr.length-1][1], newArr[newArr.length-2][1]];</code> or <code>return [newArr.pop()[1], newArr.pop()[1]];</code></li>\n<li>The arrays and <code>map</code> should be constants as they do not change.</li>\n<li>Try to avoid using <code>for in</code> loops they have some problems that make them next to useless. Rather use <code>for of</code></li>\n<li>Converting the map to an array and then sorting, just to find the top to is overkill. Sorts are complex, and you have already passed over each item, and thus know what the max values are.</li>\n<li>Naming <code>map</code>is not a great name. It is a map that holds counts, so <code>counts</code> is the better name</li>\n<li>For simple <code>if else</code> statements use the simplest form you can. eg you have <code>if (!foo) {/* do not foo */} else {...}</code> the not <code>!</code> is redundant if you reverse the order to <code>if (foo) {... } else {/* do not foo */}</code></li>\n<li>Use the shorter form of arrow function if you are just returning a value. <code>.sort((a, b) =&gt; { return a[0] - b[0] });</code> can be <code>.sort((a, b) =&gt; a[0] - b[0]);</code></li>\n<li>Sort sorts in place, you don't need to passing it to another array.</li>\n</ul>\n\n<h2>Rewrite using your approach</h2>\n\n<p>If there are no items to produce any of the top two then returns <code>undefined</code> in its place. Needs to check the sorted array size to see if it can return any values.</p>\n\n<p>Note that because it pushes the entries directly to the <code>sorted</code> array the count and items have switched places in the arrays.</p>\n\n<pre><code>function findTopTwo(arr) {\n \"use strict\";\n const counts = {}, sorted = [];\n for (const item of arr) {\n counts[item] = counts[item] ? counts[item] + 1 : 1;\n }\n\n sorted.push(...Object.entries(counts));\n if (sorted.length === 0) { return [] }\n if (sorted.length === 1) { return [sorted[0][0]] }\n\n sorted.sort((a, b) =&gt; a[1] - b[1]); \n return [sorted.pop()[0], sorted.pop()[0]];\n}\n</code></pre>\n\n<h2>Avoiding the sort</h2>\n\n<p>This looks for the top two as you count them. It avoids the sort so is less complex and uses less memory.</p>\n\n<pre><code>function findTopTwo(arr) {\n var maxA = 0, maxB = 0, itemA, itemB;\n const counts = {};\n for (const item of arr) {\n const count = (counts[item] = counts[item] ? counts[item] + 1 : 1);\n if (count &gt; maxA &amp;&amp; item !== itemB) {\n if (item !== itemA &amp;&amp; maxA &gt; maxB) { [maxB, itemB] = [maxA, itemA] }\n [maxA, itemA] = [count, item];\n } else if (count &gt; maxB &amp;&amp; item !== itemA) { [maxB, itemB] = [count, item] }\n }\n return maxA &gt; maxB ? [itemA, itemB] : [itemB, itemA];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:30:58.187", "Id": "408666", "Score": "0", "body": "Thank you very much for this. There is a lot of good information here that i will try and apply for future problems as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T06:51:30.360", "Id": "211304", "ParentId": "211290", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:50:55.933", "Id": "211290", "Score": "6", "Tags": [ "javascript", "algorithm", "interview-questions", "ecmascript-6" ], "Title": "Find top two clothing sizes in the array" }
211290
<p>The <a href="https://en.wikipedia.org/wiki/The_Hardest_Logic_Puzzle_Ever" rel="noreferrer">The Hardest Logic Puzzle Ever</a> recently came to my attention:</p> <blockquote> <blockquote> <p>Three gods A, B, and C are called, in no particular order, True, False, and Random. True always speaks truly, False always speaks falsely, but whether Random speaks truly or falsely is a completely random matter. Your task is to determine the identities of A, B, and C by asking three yes-no questions; each question must be put to exactly one god. The gods understand English, but will answer all questions in their own language, in which the words for yes and no are da and ja, in some order. You do not know which word means which.</p> </blockquote> <p>Furthermore, a single god may be asked more than one question, questions are permitted to depend on the answers to earlier questions, and the nature of Random's response should be thought of as depending on the flip of a fair coin hidden in his brain: if the coin comes down heads, he speaks truly; if tails, falsely.</p> </blockquote> <p>I quickly wrote a Python solution. The code is meant to be mostly PEP8 compliant but was not intended to be very formal — just a straight port from word problem to program. If there is a problem, the program should immediately crash to prevent undiscovered bugs.</p> <p>Given that the code shown below was meant to simply test the ideas provided in the solution for the puzzle, would it be best to rewrite the program and clean it up if code quality is to be improved without having regards for how the problem and its solution reads?</p> <pre><code>#! /usr/bin/env python3 # Reference: https://en.wikipedia.org/wiki/The_Hardest_Logic_Puzzle_Ever from random import choice, sample def question_1(god): if god == 'Random': return choice((yes, no)) truth = a == 'Random' # part 1 if god == 'True': answer = yes if truth else no elif god == 'False': answer = no if truth else yes truth = answer == 'ja' # part 2 if god == 'True': return yes if truth else no elif god == 'False': return no if truth else yes def question_2(god): if god == 'Random': return choice((yes, no)) truth = god == 'False' # part 1 if god == 'True': answer = yes if truth else no elif god == 'False': answer = no if truth else yes truth = answer == 'ja' # part 2 if god == 'True': return yes if truth else no elif god == 'False': return no if truth else yes def question_3(god): if god == 'Random': return choice((yes, no)) truth = b == 'Random' # part 1 if god == 'True': answer = yes if truth else no elif god == 'False': answer = no if truth else yes truth = answer == 'ja' # part 2 if god == 'True': return yes if truth else no elif god == 'False': return no if truth else yes for _ in range(10000): # setup a, b, c = sample(('True', 'False', 'Random'), 3) da, ja = sample(('yes', 'no'), 2) temp = {y: x for x, y in globals().items() if isinstance(y, str)} yes, no = temp['yes'], temp['no'] del temp # question answer = question_1(b) if answer == 'ja': not_random = 'c' elif answer == 'da': not_random = 'a' answer = question_2(globals()[not_random]) if answer == 'da': not_random_id = 'True' elif answer == 'ja': not_random_id = 'False' answer = question_3(globals()[not_random]) if answer == 'ja': b_id = 'Random' elif answer == 'da': if not_random != 'a': a_id = 'Random' elif not_random != 'c': c_id = 'Random' # decide if not_random == 'a': a_id = not_random_id elif not_random == 'c': c_id = not_random_id try: a_id except NameError: a_id = ({'True', 'False', 'Random'} - {b_id, c_id}).pop() else: try: b_id except NameError: b_id = ({'True', 'False', 'Random'} - {a_id, c_id}).pop() else: try: c_id except NameError: c_id = ({'True', 'False', 'Random'} - {a_id, b_id}).pop() # verify try: assert (a, b, c) == (a_id, b_id, c_id) except AssertionError: print(f'a, b, c = {a!r}, {b!r}, {c!r}') print(f'a_id, b_id, c_id = {a_id!r}, {b_id!r}, {c_id!r}') raise else: del a, b, c, da, ja, yes, no, \ answer, not_random, not_random_id, \ a_id, b_id, c_id </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:29:11.357", "Id": "408569", "Score": "0", "body": "@Carcigenicate The mapping between \"yes\" and \"no\" with \"da\" and \"ja\" is meant to be unknown. This is reflected in the code as you found it to be unclear which is on purpose. In the questions, `yes` and `no` are used to make the code readable while leaving the meaning of \"da\" and \"ja\" as ambiguous." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T22:34:59.800", "Id": "408580", "Score": "0", "body": "In case there are any questions about the assignment to `not_random` on lines 61 and 63: the purpose of not assigning `c` or `a` directly is to avoid gaining any knowledge that has not been earned yet. By using an indirect reference and then having to pull the value out of `globals()`, the true identity of god A or god C is not stolen and cannot be used accidently without merit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T22:44:16.107", "Id": "408581", "Score": "0", "body": "Is there any difference between `question_1`, `question_2`, and `question_3`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T22:46:57.140", "Id": "408582", "Score": "0", "body": "@vnp `# part 1` of the question is always different. Each question function is meant to evaluate the related question as defined in the riddle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T01:56:47.190", "Id": "408592", "Score": "0", "body": "Oh I see now. Consider it a first phase of the review: the reviewer is stumbled. An immediate recommendation is to factor out everything after `# part 1` into a function." } ]
[ { "body": "<ol>\n<li><p>The code needs a lot more comments to say <em>why</em>. Why is each <code>question_x</code> written as it is written? Why is there a loop over 10000? My best guess is that the questions hard-code a strategy and you test it with 10000 random configurations, but (a) that should be made explicit (and so should the strategy itself); and (b) you should explain why you test 10000 random configurations when there are only 12 possible configurations.</p></li>\n<li><p>The use of globals is very confusing. I strongly suggest passing around an explicit state.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T09:25:53.240", "Id": "211313", "ParentId": "211292", "Score": "4" } }, { "body": "<p>The code is not well organized. The 3 questions are very similar and does not explain <em>what</em> is being asked, and the top-level code mix together the setup logic, the solving logic and the testing logic.</p>\n\n<p>Besides, the whole logic is convoluted: using strings to store state is error-prone; and relying so much on the global state (and even the name of some variables) is even more.</p>\n\n<p>You should:</p>\n\n<ol>\n<li><p>Define some constant using enums:</p>\n\n<pre><code>import enum\n\n\nclass Answer(enum.Enum):\n JA = 'ja'\n DA = 'da'\n\n\nclass God(enum.Enum):\n TRUE = True\n FALSE = False\n RANDOM = None\n</code></pre></li>\n<li><p>Extract out the question structure so it is easier to understand what is being asked:</p>\n\n<pre><code>def answer_truthy(question):\n return yes if question else no\n\n\ndef answer_falsey(question):\n return no if question else yes\n\n\ndef would_you_say_ja_if_asked(question, god):\n if god is God.RANDOM:\n return choice((yes, no))\n\n god_answer = answer_truthy if god is God.TRUE else answer_falsey\n answer = god_answer(question)\n return god_answer(answer is Answer.JA)\n</code></pre>\n\n<p>So you can <code>would_you_say_ja_if_asked(a is God.RANDOM, b)</code> for instance, which is clearer what is being asked.</p>\n\n<p>To make it read even better, you can define this last function as a method on the <code>God</code> class:</p>\n\n<pre><code>class God(enum.Enum):\n TRUE = True\n FALSE = False\n RANDOM = None\n\n def would_you_say_ja_if_asked(self, question):\n if self is God.RANDOM:\n return choice((yes, no))\n\n god_answer = answer_truthy if self is God.TRUE else answer_falsey\n answer = god_answer(question)\n return god_answer(answer is Answer.JA)\n</code></pre>\n\n<p>Which is used as <code>b.would_you_say_ja_if_asked(a is God.RANDOM)</code> and reads very well.</p></li>\n<li><p>Extract out your solving logic out of the setup + test one:</p>\n\n<pre><code>def solve():\n \"\"\"Solve the puzzle by asking three questions\"\"\"\n a = b = c = None\n\n # Determine which of A or C is not the Random god\n answer = B.would_you_say_ja_if_asked(A is God.RANDOM)\n non_random_god = C if answer is Answer.JA else A\n\n # Determine the identity of previously selected god\n answer = non_random_god.would_you_say_ja_if_asked(non_random_god is God.FALSE)\n if non_random_god is C:\n c = God.FALSE if answer is Answer.JA else God.TRUE\n else:\n a = God.FALSE if answer is Answer.JA else God.TRUE\n\n # Determine which god is Random\n answer = non_random_god.would_you_say_ja_if_asked(B is God.RANDOM)\n if answer is Answer.JA:\n b = God.RANDOM\n elif non_random_god is C:\n a = God.RANDOM\n else:\n c = God.RANDOM\n\n # Deduct the identity of the third god\n last_one = (set(God) - {a, b, c}).pop()\n if a is None:\n a = last_one\n elif b is None:\n b = last_one\n else:\n c = last_one\n\n return a, b, c\n</code></pre></li>\n<li><p>Stop relying on global variables and pass state explicitly around:</p>\n\n<pre><code>#! /usr/bin/env python3\n\n\"\"\"Setup and find an answer to the hardest puzzle ever.\n\nThe puzzle statement is as follows:\n\n Three gods A, B, and C are called, in no particular\n order, True, False, and Random. True always speaks\n truly, False always speaks falsely, but whether Random\n speaks truly or falsely is a completely random matter.\n Your task is to determine the identities of A, B, and\n C by asking three yes-no questions; each question must\n be put to exactly one god. The gods understand English,\n but will answer all questions in their own language, in\n which the words for yes and no are da and ja, in some\n order. You do not know which word means which.\n\n Furthermore, a single god may be asked more than one\n question, questions are permitted to depend on the\n answers to earlier questions, and the nature of Random's\n response should be thought of as depending on the flip\n of a fair coin hidden in his brain: if the coin comes\n down heads, he speaks truly; if tails, falsely.\n\nReference: https://en.wikipedia.org/wiki/The_Hardest_Logic_Puzzle_Ever\n\nThe solution is found as follows:\n\n * ask B if they would say ja if asked 'is A Random?';\n depending on the answer either A or C is not Random.\n * ask the non-Random god if they would say ja if asked\n 'are you False?'; the answer will tell who they are.\n * ask the same god if they would say ja if asked\n 'is B Random?'; the answer will tell who Random is.\n * the third god can be deduced without further questions.\n\"\"\"\n\nimport sys\nimport enum\nfrom random import choice, sample\n\n\nclass Answer(enum.Enum):\n JA = 'ja'\n DA = 'da'\n\n\nclass God(enum.Enum):\n TRUE = True\n FALSE = False\n RANDOM = None\n\n def would_you_say_ja_if_asked(self, question, yes_no_meaning):\n if self is God.RANDOM:\n return choice(yes_no_meaning)\n\n god_answer = answer_truthy if self is God.TRUE else answer_falsey\n answer = god_answer(question, yes_no_meaning)\n return god_answer(answer is Answer.JA, yes_no_meaning)\n\n\ndef answer_truthy(question, yes_no_meaning):\n yes, no = yes_no_meaning\n return yes if question else no\n\n\ndef answer_falsey(question, yes_no_meaning):\n yes, no = yes_no_meaning\n return no if question else yes\n\n\ndef solve(A, B, C, yes_no_meaning):\n \"\"\"Solve the puzzle by asking three questions\"\"\"\n a = b = c = None\n\n # Determine which of A or C is not the Random god\n answer = B.would_you_say_ja_if_asked(A is God.RANDOM, yes_no_meaning)\n non_random_god = C if answer is Answer.JA else A\n\n # Determine the identity of previously selected god\n answer = non_random_god.would_you_say_ja_if_asked(non_random_god is God.FALSE, yes_no_meaning)\n if non_random_god is C:\n c = God.FALSE if answer is Answer.JA else God.TRUE\n else:\n a = God.FALSE if answer is Answer.JA else God.TRUE\n\n # Determine which god is Random\n answer = non_random_god.would_you_say_ja_if_asked(B is God.RANDOM, yes_no_meaning)\n if answer is Answer.JA:\n b = God.RANDOM\n elif non_random_god is C:\n a = God.RANDOM\n else:\n c = God.RANDOM\n\n # Deduct the identity of the third god\n last_one = (set(God) - {a, b, c}).pop()\n if a is None:\n a = last_one\n elif b is None:\n b = last_one\n else:\n c = last_one\n\n return a, b, c\n\n\ndef setup_puzzle():\n yes, no = sample(list(Answer), 2)\n a, b, c = sample(list(God), 3)\n return yes, no, a, b, c\n\n\ndef test(test_cases=10_000):\n for _ in range(test_cases):\n yes, no, A, B, C = setup_puzzle()\n a, b, c = solve(A, B, C, (yes, no))\n\n if (a, b, c) != (A, B, C):\n print(f'a, b, c = {a}, {b}, {c}', file=sys.stderr)\n print(f'A, B, C = {A}, {B}, {C}', file=sys.stderr)\n sys.exit('Found a failing case')\n\n print('All tests passed')\n\n\nif __name__ == '__main__':\n test()\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T10:08:50.613", "Id": "211318", "ParentId": "211292", "Score": "5" } }, { "body": "<h2>Best general answer</h2>\n<p><a href=\"https://codereview.stackexchange.com/a/211318/140921\">@Mathias Ettinger's answer</a> is very comprehensive for the big picture design changes, so I would probably follow that one for my general design (though your question has piqued my interest in programming this question, so I may come back with my own variant at some point). However, I do have some useful tidbits to offer in my answer, and they can hopefully help you improve your knowledge, even if they aren't the big picture for this problem.</p>\n<h2>Answering the meta question</h2>\n<blockquote>\n<p>In what cases would this implementation of THLPE require more formality?</p>\n<p>...</p>\n<p>Given that the code shown below was meant to simply test the ideas provided in the solution for the puzzle, it what case(s) would it be best to rewrite the program and clean it up if code quality is to be improved without having regards for how the problem and its solution reads?</p>\n</blockquote>\n<p>Code Review is a place for general review of code quality as described in <strong>Do I want the code to be good code?</strong> in our <a href=\"https://codereview.stackexchange.com/help/on-topic\">on-topic page</a>. I will be reviewing just as described there. I am not approaching the problem in this way <em>just</em> because of how our rules are phrased. In my experience in general coding, I've found that following best practices in general helps to achieve better reliability, and I think most would agree with me on this. There is really not any conflict between best practices and reliability; they go hand in hand.</p>\n<p>On the other hand, best practices and <em>performance</em> can sometimes come into conflict. However, for many (most?) problems, optimizing performance beyond best practices is not a real issue, hence the common programming aphorism of <a href=\"https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize\" rel=\"nofollow noreferrer\">premature optimization</a>. And when this becomes a common enough issue in an active programming language (like Python), the language can be revised to address it, or alternate solutions can be developed by the community (like <a href=\"https://en.wikipedia.org/wiki/Cython\" rel=\"nofollow noreferrer\">Cython</a> for C-optimized Python code).</p>\n<h1>Review</h1>\n<h2><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't repeat yourself</a>!</h2>\n<p>There's one extremely noticeable bad practice in your program. <code>question_1</code>, <code>question_2</code>, and <code>question_3</code> are all verbatim identical aside from their names. Instead of having repeated code, there should be a single <code>question</code> function, which I would probably renamed to <code>ask_question</code> for more clarity. If the number of the question was important, then it should be a parameter to that <em>one</em> function (probably named <code>num</code>, unless it has a more specific designation). However, the number does not matter in this problem. The only information that matters for this puzzle is the</p>\n<p>Repeating code is a bad practice because there's more code to keep track of when revising the code, so it's easier to introduce a continuity error. It is also generally easier to read shorter code.</p>\n<h2>Don't abuse <code>globals()</code></h2>\n<p>You should be wary of using <code>globals()</code> because it introduces another layer of complexity into a program. Unless you're sure that you need it, you should try to find another way to accomplish your goal. In your case, you could have a dict or even an iterable to store the gods, so there's no reason to haphazardly query globals.</p>\n<h2>Use the right function for the situation</h2>\n<p>The following two lines come to my attention:</p>\n<pre><code> a, b, c = sample(('True', 'False', 'Random'), 3)\n da, ja = sample(('yes', 'no'), 2)\n</code></pre>\n<p>Here, you're using <code>random.sample</code> to randomly order a tuple. However, there is some implicit repetition here: you're entering the length of each tuple (3 and 2 respectively), when that information could be retrieved from the tuple itself through the <code>len</code> built-in function. This repetition occurs because <code>sample</code> is the <strong>wrong</strong> function for this situation: you actually want <a href=\"https://docs.python.org/library/random.html#random.shuffle\" rel=\"nofollow noreferrer\"><code>random.shuffle</code></a> if you're trying to reorder an iterable (though it modifies its argument in-place, so it would need a list instead of a tuple).</p>\n<p>However, for the big picture, I wouldn't even use a randomly generated list like this; I would probably use enums in a way similar to <a href=\"https://codereview.stackexchange.com/a/211318/140921\">@Mathias Ettinger's answer</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T12:01:54.703", "Id": "211324", "ParentId": "211292", "Score": "4" } }, { "body": "<p>A minor comment for efficiency, for example, you may want to change </p>\n\n<pre><code>def question_1(creature):\n if creature == 'Random':\n return choice((yes, no))\n truth = a == 'Random' # part 1\n if creature == 'True':\n answer = yes if truth else no\n elif creature == 'False':\n answer = no if truth else yes\n truth = answer == 'ja' # part 2\n if creature == 'True':\n return yes if truth else no\n elif creature == 'False':\n return no if truth else yes\n</code></pre>\n\n<p>to</p>\n\n<pre><code>def question_1(creature):\n if creature == 'Random':\n return choice((yes, no))\n\n truth = a == 'Random' # part 1\n\n if creature == 'True':\n answer = yes if truth else no\n truth = answer == 'ja' # part 2\n return yes if truth else no\n else:\n answer = no if truth else yes\n truth = answer == 'ja' # part 2\n return no if truth else yes\n</code></pre>\n\n<ul>\n<li><p>Since there are only 3 possibilities for <code>creature</code>: <code>'Random'</code>, <code>'False'</code>, or <code>'True'</code>. So after <code>if creature == 'True'</code>, <code>else</code> is for when <code>creature == False</code>. </p></li>\n<li><p>The previous one has two <code>if creature == 'True':...</code>, but you can make it into just one to be more compact.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T09:40:00.310", "Id": "211530", "ParentId": "211292", "Score": "2" } } ]
{ "AcceptedAnswerId": "211318", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T21:06:08.220", "Id": "211292", "Score": "5", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Python solution to The Hardest Logic Puzzle Ever" }
211292
<p>I have the following code that I managed to make thread-safe but I am not sure if I am using C++ technology optimally.</p> <pre><code>#include &lt;iostream&gt; #include &lt;omp.h&gt; //#include &lt;memory&gt; class GenNo { public: int num; explicit GenNo(int num_) { num = num_; }; void create(int incr) { num += incr; } }; class HelpCrunch{ public: HelpCrunch() { } void helper(int number) { std::cout &lt;&lt; "Seed is " &lt;&lt; number &lt;&lt; " for thread number: " &lt;&lt; omp_get_thread_num() &lt;&lt; std::endl; } }; class calculate : public HelpCrunch { public: int specific_seed; bool first_run; void CrunchManyNos() { HelpCrunch solver; thread_local static GenNo RanNo(specific_seed); //std::unique_ptr&lt;GenNo&gt; GenNo_ptr(nullptr); /* if(first_run == true) { GenNo_ptr.reset(new GenNo(specific_seed)); first_run = false; } solver.helper(GenNo_ptr-&gt;num); */ RanNo.create(1); solver.helper(RanNo.num); //do actual things that I hope are useful. }; }; int main() { calculate MyLargeProb; MyLargeProb.first_run = true; #pragma omp parallel firstprivate(MyLargeProb) { int thread_specific_seed = omp_get_thread_num(); MyLargeProb.specific_seed = thread_specific_seed; #pragma omp for for(int i = 0; i &lt; 10; i++) { MyLargeProb.CrunchManyNos(); std::cout &lt;&lt; "Current iteration is " &lt;&lt; i &lt;&lt; std::endl; } } return 0; } </code></pre> <p>The code that is commented out can be used as an alternative but the pointer gets destroyed after the method finishes which crashes the programme. Moreover, it was pointed out to me that I could use <code>threadprivate</code> for the static instance of <code>GenNo.</code> The use case equivalent of <code>GenNo</code> is a random number generator that gets seeded once per thread with a known seed and then is left alone, i.e. not reinitialised, but called upon to generate fresh random numbers in each iteration.</p> <p>I know the whole structure seems a bit contrived but my hands are tied somewhat: the classes and their dependence are dictated to me by the tools I would like to use and I think this scenario is common in the scientific computing community. It compiles fine and upon manual testing appears to be thread-safe and working but again, I don't think this is particularly good style and a bit cobbled together, so I would love to hear everyone's comments. Important note: I am using gcc as my compiler and gcc for over ten years now doesn't support threadprivate class instances. Intel's compiler which can be obtained for academics and students on a trial license, does.</p> <p>The following is an example of code that would not compile in GCC (even the most recent version).</p> <pre><code>#include "myclass.h" #include &lt;omp.h&gt; int main { myclass myinstance; #pragma omp parallel threadprivate(my_instance) { // do parallel things } return 0; } </code></pre> <p>The error message would be <code>my_instance declared threadprivate after first use</code> which is a long-standing bug or rather not a bug but a missing feature, see <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=27557" rel="nofollow noreferrer">here</a>, for example.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T09:28:51.267", "Id": "408787", "Score": "0", "body": "There's so much skipped in the code that it's impossible to review. I see statements of which I doubt they could possibly work and there's no context. Please take a look at the [help/on-topic]. Currently, it's impossible to say you're doing it right, since there's next-to-nothing shown and what's show looks dubious at best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T09:36:10.473", "Id": "408788", "Score": "0", "body": "@Mast I erred on the side of giving a minimal reproducible example which is why I threw out most of it and made a model of my code rather than posting 600 lines here. But okay I shall see how I can produce a slightly more functional example. However, the code in the big implementation works fine and I am getting my numbers crunched, I just don't think I did it very well and hence was looking for someone to take a look at it. I shall have a read through the guidelines on the help center." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T10:00:05.963", "Id": "408791", "Score": "0", "body": "Minimum Complete Verifiable Examples are something for Stack Overflow. On Code Review, they are not acceptable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T10:02:44.460", "Id": "408792", "Score": "0", "body": "@aha ok that would explain it, I will have a look at the help center because it seems a bit rich of me to ask people to look at pretty extensive code. I was referred from stackoverflow to here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T14:23:28.280", "Id": "408799", "Score": "0", "body": "@Mast Excluding the two header-only libraries I use, I have about 1500 lines of code. Do you not think this is too much? It is a class that inherits from an optimiser class and contains the value function as well as methods that help along the way. Then a main that uses an instance of the class to carry out the task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T14:37:13.570", "Id": "408801", "Score": "0", "body": "It's possible your project is too big to be reviewable, yes. That doesn't change the rules." } ]
[ { "body": "<p>what is the problem with just creating a range of random number generators from <code>&lt;random&gt;</code> and assign each to a thread? </p>\n\n<p>Mind that using <code>thread_local</code> might not be a good way, as initialization of random number generators is costly. Also i do not know, how therngs would be seeded in a <code>thread_local</code> environement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:16:10.570", "Id": "408675", "Score": "0", "body": "random number generator I use is based on the Mersenne Twister and is a custom-built one that delivers multivariate normal with given covariance matrix and vector of means. Assuming I were to go with your suggestion, how would I do that? Also, I am seeding manually as is the case in the model code above." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T18:55:59.203", "Id": "211341", "ParentId": "211296", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T22:43:31.720", "Id": "211296", "Score": "0", "Tags": [ "c++", "multithreading", "openmp" ], "Title": "Generating parallel random numbers in a thread-safe way and using them in computations implemented by class method" }
211296
<p>I'm using the flutter_simple_permissions plugin to request permission to read contacts on my flutter application. I want the app to quit when a user denies the permission, and need to show them a custom Dialog.</p> <pre><code> Future&lt;bool&gt; getContactsPermission() async{ bool hasPermission = await SimplePermissions.checkPermission(Permission.ReadContacts); if(!hasPermission){ await showDialog(context: context, builder: (context) { return new AlertDialog( title: Text('Requires Contacts Permission'), content: SingleChildScrollView( child: ListBody( children: &lt;Widget&gt;[ Text('This application requires access to your contacts'), Text('Please allow access'), ], ), ), actions: &lt;Widget&gt;[ FlatButton( child: Text('Allow'), onPressed:() async { final response = await SimplePermissions.requestPermission(Permission.ReadContacts); if(response != PermissionStatus.authorized){ return false; } Navigator.of(context).pop(); }, ), FlatButton( child: Text('Exit App'), onPressed: () { exit(0); }, ), ], ); }); } return true; } refreshContacts() async { bool hasPermission = false; while(!hasPermission){ hasPermission = await getContactsPermission(); } var contacts = await ContactsService.getContacts(); print("GOT CONTACTS!"); setState(() { _contacts = contacts; }); } </code></pre> <p>Whenever I call refreshContacts() the popup shows up if the user had no permission.</p> <p>The code is working great, but I feel it could have been much simpler using FutureBuilder maybe?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T08:05:48.477", "Id": "211309", "Score": "3", "Tags": [ "gui", "dart", "flutter" ], "Title": "Custom permission Dialog in Dart" }
211309
<p>I am using PHP, and I am getting the value back from the form. Since I am working with time, I have an array by (1 x 4) x 7, and I feel like I could do a better job at it. I just don't know exactly how should I approach the problem</p> <pre><code>$schedule = array( round(abs(strtotime($_POST['mon'][1]) - strtotime($_POST['mon'][0])) / 3600, 2), round(abs(strtotime($_POST['mon'][3]) - strtotime($_POST['mon'][2])) / 3600, 2), round(abs(strtotime($_POST['tue'][1]) - strtotime($_POST['tue'][0])) / 3600, 2), round(abs(strtotime($_POST['tue'][3]) - strtotime($_POST['tue'][2])) / 3600, 2), round(abs(strtotime($_POST['wed'][1]) - strtotime($_POST['wed'][0])) / 3600, 2), round(abs(strtotime($_POST['wed'][3]) - strtotime($_POST['wed'][2])) / 3600, 2), round(abs(strtotime($_POST['thu'][1]) - strtotime($_POST['thu'][0])) / 3600, 2), round(abs(strtotime($_POST['thu'][3]) - strtotime($_POST['thu'][2])) / 3600, 2), round(abs(strtotime($_POST['fri'][1]) - strtotime($_POST['fri'][0])) / 3600, 2), round(abs(strtotime($_POST['fri'][3]) - strtotime($_POST['fri'][2])) / 3600, 2), round(abs(strtotime($_POST['sat'][1]) - strtotime($_POST['sat'][0])) / 3600, 2), round(abs(strtotime($_POST['sat'][3]) - strtotime($_POST['sat'][2])) / 3600, 2), round(abs(strtotime($_POST['sun'][1]) - strtotime($_POST['sun'][0])) / 3600, 2), round(abs(strtotime($_POST['sun'][3]) - strtotime($_POST['sun'][2])) / 3600, 2), ); </code></pre>
[]
[ { "body": "<p>Well, every time you see a repeated code, you could think of a loop. </p>\n\n<p>if I am not mistaken, only a weekday is changed, so it could be used to form the loop:</p>\n\n<pre><code>$schedule = [];\n$weekdays = ['mon','tue','wed','thu','fri','sat','sun'];\nforeach ($weekdays as $day)\n{\n $schedule[] = round(abs(strtotime($_POST[$day][1]) - strtotime($_POST[$day][0])) / 3600, 2),\n $schedule[] = round(abs(strtotime($_POST[$day][3]) - strtotime($_POST[$day][2])) / 3600, 2),\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-16T18:12:43.657", "Id": "409256", "Score": "0", "body": "Thank you. Managed to remove a lot of code that were similar by at least 40%!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T08:36:49.657", "Id": "211311", "ParentId": "211310", "Score": "2" } } ]
{ "AcceptedAnswerId": "211311", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T08:23:29.040", "Id": "211310", "Score": "1", "Tags": [ "php", "form" ], "Title": "Processing form values for each day of week" }
211310
<p>I'm writing a script that's changing the background color depending on hour of day, if it is a weekend or if it is a Swedish holiday. I have a functional script and as I want to improve my programming skills I want to see if there's anything I can do differently or more efficiently.</p> <p>I wanted to work with separate functions to (hopefully) improve readability and make the script more adaptable by passing parameters. The script also runs a function on an interval to update the background color if the allowed time span has been passed. My concern is that this will affect performance as far as I know it will not be too CPU intensive.</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> closedDates(); function closedDates() { //Create new date object var d = new Date(); var year = d.getFullYear(); var closedDates = (calculateClosedDates(year)); var closedDates = [ new Date(year, 0, 1), // Fixed date: New Years day new Date(year, 0, 5), // Fixed date: Twelfth Night new Date(year, 0, 6), // Fixed date: Epiphany new Date(closedDates[0]), // Thursday new Date(closedDates[1]), // Good Friday new Date(closedDates[2]), // Easter Day new Date(closedDates[3]), // Easter Monday new Date(year, 3, 30), // Fixed date: Walpurgis Night new Date(year, 4, 1), // Fixed date: International Workers' Day new Date(closedDates[4]), // Feast of the Ascension new Date(closedDates[5]), // Pingstafton new Date(closedDates[6]), // Pingstdagen new Date(year, 5, 6), // Fixed date: Swedish National Day new Date(closedDates[7]), // Saint John's Eve new Date(closedDates[8]), // Midsummer day new Date(closedDates[9]), // All Saints' Eve new Date(closedDates[10]), // All Saints' Day new Date(year, 11, 24), // Fixed date: Christmas Eve new Date(year, 11, 25), // Fixed date: Christmas Day new Date(year, 11, 26), // Fixed date: Christmas Eve new Date(year, 11, 31) // Fixed date: New Years Eve ]; // Pass current date and date array to function checkDate(d, closedDates); } function checkDate(d, closedDates) { var openingHour = 10, closingHour = 18, weekend = [0, 6]; // Run check time once to see if it is open checkTime(); // Check if time falls in between time span and is not a weekend // Change background color if/else function checkTime() { d = new Date() console.log(d); if (d.getHours() &lt; openingHour || d.getHours() &gt;= closingHour || d.getDay() === weekend[0] || d.getDay() === weekend[1]) { document.body.style.backgroundColor = "red"; } else { document.body.style.backgroundColor = "green"; } } // Check if current date is equal to a date in the date array // Converting to time to be able to compare // Change background colour accordingly for (i = 0; i &lt; closedDates.length; i++) { if (d.getTime() === closedDates[i].getTime()) { document.body.style.backgroundColor = "red"; return } else { // Run script in 30 second intervals to update background reguraly setInterval(checkTime, 30000); return } } } function calculateClosedDates(year) { /* This function calculates and returns an array with date objects of Swedish public holidays Many days are based on when easterDay occurs and therefore I use Gauss Easter Algorithm to calculate when easter day occurs for the current year. It uses constanst M &amp; N that needs to be updated 2099 but this is a non issue. I could include a function that checks which year it is and updates the constants accordingly but I feel it's over ambitious for this script. Some days are fixed dates and some holidays shift and therefore need to be calculated */ // Start Gauss Easter Algorithm // https://en.wikipedia.org/wiki/Computus#Gauss's_Easter_algorithm // Constants, update year 2099 ;) var M = 24, N = 5, a = year % 19, b = year % 4, c = year % 7, d = ((19*a) + M) % 30, e = ((2*b) + (4*c) + (6*d) + N) % 7, easterDay = 22 + d + e, // Easter Month as default March easterMonth = 2; // If easterDay is greater than 31, take value minus 31 // Set month to April if (easterDay &gt; 31) { easterDay = easterDay - 31; easterMonth = 3; } // Exceptions to formula // If easterDay is 26 and easterMonth is April // set date a week earlier if (easterDay == 26 &amp;&amp; easterMonth == 4) { easterDay = easterDay - 7; } // If easterDay is 25, easterMonth is April, d is 28, e is 6 and a is greater than 10 // set date a week earlier if (easterDay == 25 &amp;&amp; easterMonth == 4 &amp;&amp; d == 28 &amp;&amp; e == 6 &amp;&amp; a &gt; 10) { easterDay = easterDay - 7; } // End Gauss Easter Formula var maundyThursday = new Date(year, easterMonth, easterDay-3), // Will always occur on the first thursday before easter day goodFriday = new Date(year, easterMonth, easterDay-2), // Will always occur on the first friday before easter day easter = new Date(year, easterMonth, easterDay), // Value from Gauss easterMonday = new Date(year, easterMonth, easterDay+1), // Will always occur on the first monday after easter day ascension = new Date(year, easterMonth, ((easterDay+4) + 35)), // Get the next thursday from easter day + 35 days (5 weeks) pingstAfton = new Date(year, easterMonth, easterDay+48), // 7 Weeks - 1 day after easter day pingstDagen = new Date(year, easterMonth, easterDay+49), // 7 Weeks after easter day midsommarAfton = getSpecificDay(5, new Date(year, 5, 20)), // From start date, find first friday midsommarDagen = getSpecificDay(6, new Date(year, 5, 20)), // From start date, find first saturday allSaintsEve = getSpecificDay(5, new Date(year, 9, 30)), // From start date, find first friday allSaintsDay = getSpecificDay(6, new Date(year, 9, 31)); // From start date, find first saturday function getSpecificDay(holiday, startDate) { // Get which specific day that the holiday (friday, saturday) is and then get the start date of the period var calculatedDate = startDate; calculatedDate.setDate(startDate.getDate() + (holiday - startDate.getDay() % 7)); return calculatedDate; } return [maundyThursday, goodFriday, easter, easterMonday, ascension, pingstAfton, pingstDagen, midsommarAfton, midsommarDagen, allSaintsEve, allSaintsDay]; }</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Here are a few suggestions..</p>\n\n<ul>\n<li>The Easter day calculation should <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">be in its own function</a>.</li>\n<li>I would probably put this as a single one liner arrow function (and move it up a few lines) <code>const getSpecificDay = (h, s) =&gt; s.setDate(s.getDate() + (h - s.getDay() % 7));</code>. That just looks cleaner IMO.</li>\n<li>You should combine <code>closedDates()</code> and <code>calculateClosedDates()</code> since they're basically both doing the same thing.</li>\n</ul>\n\n<p>Instead of checking the hour every 30 seconds, you're better off calculating the number of milliseconds until the next hour and start checking at that time every hour.</p>\n\n<pre><code>var d = new Date()\nd.setHours(d.getHours()+1, 0, 0, 0)\nvar nextHour = d.getTime() - new Date().getTime();\n\nsetTimeout(()=&gt;{\n checkTime();\n setInterval(checkTime, 60*60*1000);\n}, nextHour);\n</code></pre>\n\n<p>Aside from a few formatting things it looks pretty good man.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:24:26.563", "Id": "211343", "ParentId": "211317", "Score": "1" } }, { "body": "<p><strong>Remove UI code</strong></p>\n\n<pre><code>if (d.getHours() &lt; openingHour || d.getHours() &gt;= closingHour || d.getDay() === weekend[0] || d.getDay() === weekend[1]) {\n document.body.style.backgroundColor = \"red\";\n }\n else {\n document.body.style.backgroundColor = \"green\";\n }\n</code></pre>\n\n<p>Mixing UI code with what should be pure holiday calculation code is the worse thing I see for the long term health of your application. Instead client code (the UI) should call an object method or property but shall not return a color because that's UI business.</p>\n\n<p>Think about it - why would my calculator assume anything about why I'm doing a calculation or how I will use it. When the calculation output is \"green\" instead of true or false (is what I suspect you want) then that calculator is now useless for anything except that exact, lone thing. The code is not reusable.</p>\n\n<hr>\n\n<p><strong>The comments</strong> read the literal code. You should assume the reader knows how to read code and then have comments that tell \"why\" or \"what.\" Kudos for referencing the algorithm source.</p>\n\n<p>Bad comments:</p>\n\n<pre><code>//Create new date object\nvar d = new Date();\n. . .\n// If easterDay is greater than 31, take value minus 31\n// Set month to April\nif (easterDay &gt; 31) {\n easterDay = easterDay - 31;\n easterMonth = 3;\n}\n. . .\n// Pass current date and date array to function\ncheckDate(d, closedDates);\n</code></pre>\n\n<p>OK comments:</p>\n\n<pre><code>// Exceptions to formula\n. . .\n// Run check time once to see if it is open\n checkTime();\n</code></pre>\n\n<hr>\n\n<p>Should be unnecessary comments:</p>\n\n<pre><code>// Easter Month as default March\n easterMonth = 2;\n</code></pre>\n\n<p>Define constants for the months</p>\n\n<hr>\n\n<p>Make <code>closedDates</code> an object then you don't have to memorize the order in the array and induce coding errors.</p>\n\n<pre><code>var closedDates = [\n new Date(year, 0, 1), // Fixed date: New Years day\n new Date(year, 0, 5), // Fixed date: Twelfth Night\n new Date(year, 0, 6), // Fixed date: Epiphany\n new Date(closedDates[0]), // Thursday\n\nvar closedDates = {\n \"NewYears\" : new Date(year, 0, 1),\n \"TwelfthNight\" : new Date(year, 0, 5),\n \"Epiphany\" : new Date(year, 0, 6),\n \"Thursday\" : new Date(closedDates[0]), \n</code></pre>\n\n<p>A weekday should not be in the holidays structure. Make a 'weekdays' structure instead. If you meant 'maundyThursday' I suspect that making an object in the first place would have avoided the commenting error.</p>\n\n<hr>\n\n<p><strong>Naming</strong></p>\n\n<p>Name things to reflect the subject domain not the code implementation details. Sometimes (often?) unnecessary comments - see above - can suggest appropriate names.</p>\n\n<p><code>closedDates</code> are not dates, they are holidays. And does it really matter to the <code>closedDates</code> user if they are closed or not? Anyway <code>closedDates</code> also includes open dates and so the name is more wrong. What does open and closed mean anyway?</p>\n\n<p>Making day &amp; month constants will make the whole thing far more understandable, significantly prevent errors, and otherwise unnecessary comments.</p>\n\n<p>Rethink all the function names. For example <code>checkDate</code> is meaningless. I know how hard that is; 30 character names is no so good either so sometimes you just have to settle for good function comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T01:26:31.403", "Id": "408699", "Score": "0", "body": "-1 I can not agree with your advice on naming dates. All the code needs do is change the background color depending on the current time and date. Introducing named dates adds a completely unrelated abstraction to the code. . The time and dates do not need to be ordered, the OP's error was to index directly rather than add easter holidays using `...` operator eg `const closedDates = [ ...calculateClosedDates(year), new Date(year, 0, 1), ` and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T06:57:52.037", "Id": "408704", "Score": "0", "body": "*All the code needs do is change the background color depending on the current time and date* But it does two things, calculate the holidays and updates the UI. There is a separation of concerns here - a single responsibility principle problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T06:59:28.853", "Id": "408705", "Score": "0", "body": "*Introducing named dates adds a completely unrelated abstraction* How can naming dates as the holidays they are be unrelated to dates that are these holidays?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T07:07:59.670", "Id": "408706", "Score": "0", "body": "*the OP's error was to index directly rather than add easter holidays using ... operator ...* The spread operator may be concise, etc. but not using it is not \"an error.\" More to the point, this all utterly misses the point. Client code can reference the holidays by their names rather than an index position in an array. As written these positions cannot change - holidays cannot be added or removed without breaking this code and any client code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T07:26:44.857", "Id": "408707", "Score": "0", "body": "\"...but not using it is not \"an error.\"\" I was referring to the comment error you used to justify naming the dates \"...would have avoided the commenting error.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T23:14:48.027", "Id": "408842", "Score": "0", "body": "Down votes should be explained. It helps everyone. **down vote criteria**: *Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect.*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T23:29:45.727", "Id": "408844", "Score": "0", "body": "Downvotes do not require explanation. Why would they be anonymous if they required explanation? But the point is mute as I have given you the reason for the down vote." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:00:39.400", "Id": "211347", "ParentId": "211317", "Score": "-1" } }, { "body": "<h1>Never mix information and code</h1>\n\n<p>I have a fundamental problem with your code.</p>\n\n<h2>Existing data</h2>\n\n<p>The calculations for Easter dates looks complex, too complex to trust there are not typos or errors in the code. It would be dangerous to release this service without first testing it over the period you expect this application to provide its service. Hence you should already have a list of Easter holiday dates available to do the test.</p>\n\n<p>Why complicate when you have that data at hand already?</p>\n\n<h2>Changing information should not mean changing code</h2>\n\n<p>As nothing is set in stone and thus it is highly likely that you will need to make changes to things like open and close times, add exceptions to weekends, amend public holiday times. As you have hard coded all possible information that is subject to possible change changes will require a programmer, and a full test cycle. </p>\n\n<p>Changes cost time and money, and if you don't have a good contract, that cost may be yours to bear, or worse that time may come when you have none to spare.</p>\n\n<h2>Deligate responsibility</h2>\n\n<ul>\n<li>You are a coder, you write code.</li>\n<li>The trader runs a trade, manages opening times and does not write code.</li>\n<li>Many people set holidays, they provide services regarding this information</li>\n</ul>\n\n<p>I would highly stress that this type of service (calculating trading hours) be up to the client (the trader) and that you (the coder) provide an interface (server based) for the client to make changes as needed.</p>\n\n<p>That you outsource the calculation of holidays to an API (Example. Randomly selected <a href=\"https://holidayapi.com/\" rel=\"nofollow noreferrer\">Holiday API</a> from a google search) </p>\n\n<p>You do not get involved in changing holidays, and trading hours, you provide the means for those that do to provide the information that your code needs to change the background color.</p>\n\n<h2>Rewriting your app</h2>\n\n<p>The rewrite is an example only, untested, and data copied and unverified.\nHolidays, trading times and days are as separate data objects that could be delivered as JSON. They are required for the code to load.</p>\n\n<p>To simplify holiday checks, dates are converted to days of the year.</p>\n\n<p>Now your timed function need only do the following.</p>\n\n<pre><code>document.body.classList[tradingInfo.isClosed ? \"add\" : \"remove\"](\"bg-color--trading-closed\");\n</code></pre>\n\n<h3>The code</h3>\n\n<pre><code>//=============================================\n// Helpers and conversion code\nconst msInHour = 100 * 60 * 60; \nconst msInDay = msInHour * 24;\nconst tradingTimeZone = 8 * msInHour;\nconst weekDays = {sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6}\nconst dayOfYearFromDate = date =&gt; (date.valueOf() + tradingTimeZone) / msInDay | 0;\nconst dayOfYear = (year, month, day) =&gt; dayOfYearFromDate(new Date(year, month, day));\nconst dayOfYearOfWeekDayNear = (year, weekDayNameShort, month, date) =&gt; {\n const dt = new Date(year, month, date);\n return dayOfYearFromDate(\n dt.setDate(dt.getDate() + (weekDays[weekDayNameShort] - dt.getDay() % 7))\n );\n}\nconst holidaysDayOfYear = (year) =&gt; holidays.map(monthDay =&gt; dayOfYear(year,...monthDay));\nconst easterHolidays = (year) =&gt; {\n const day = dayOfYear(year, ...easterInfo[year]);\n return [\n ...easterInfo.offsetDays.map(offset =&gt; day + offset),\n ...easterInfo.weekDayNear.map(dayNear =&gt; dayOfYearOfWeekDayNear(year,...dayNear)),\n ];\n}\n\n/* Requires holiday info and trading data before this can be run and used */\n\n// the object that converts data to isClosed \nconst tradingInfo = {\n closed {\n hours: weeklyTradingClosed.hours, // 24hr ranges [from, to]\n days: weeklyTradingClosed.daysOfWeek, // index from 0 sun to 6 sat\n holidays : [ // array of days of the year\n ...easterHolidays(new Date().getFullYear()), \n ...holidaysDayOfYear(new Date().getFullYear())\n ], \n },\n get isClosed() {\n const date = new Date();\n const hour = date.getHour();\n const dayOfWeek = date.getDay();\n const dayOfYear = dayOfYearFromDate(date);\n return tradingInfo.closed.hour.some(hours =&gt; hour &gt;= hours[0] &amp;&amp; hour &lt;= hours[1]) ||\n tradingInfo.closed.days.some(day =&gt; day = dayOfWeek) || \n tradingInfo.closed.holidays.includes(dayOfYear);\n }, \n};\n</code></pre>\n\n<h3>Information required</h3>\n\n<pre><code>// sources\n// https://codereview.stackexchange.com/q/211317/120556\nconst weeklyTradingClosed = {hours : [[0, 10], [18, 24]], daysOfWeek : [0,6]}\nconst holidays = [\n [0, 1], // New Years day\n [0, 5], // Twelfth Night\n [0, 6], // Epiphany\n [3, 30], // Walpurgis Night\n [4, 1], // International Workers' Day\n [5, 6], // Swedish National Day\n [11, 24], // Christmas Eve\n [11, 25], // Christmas Day\n [11, 26], // Christmas Eve\n [11, 31], // New Years Eve\n}; \n</code></pre>\n\n<h3>Easter info for next 20 years</h3>\n\n<p>You don't need a complicated formula, we know the dates already, use that information.</p>\n\n<pre><code>// sources\n// https://codereview.stackexchange.com/q/211317/120556\n// https://en.wikipedia.org/wiki/List_of_dates_for_Easter Using western dates.\nconst easterInfo = { \n offsetDays : [-3, -2, 0, 1, 39, 48, 49], \n weekdayNear : [[\"fri\", 5, 20], [\"sat\", 5, 20], [\"fri\", 9, 30], [\"sat\", 9, 31]],\n \"2019\": [3, 21],\n \"2020\": [3, 12],\n \"2021\": [3, 4],\n \"2022\": [3, 17],\n \"2023\": [3, 9],\n \"2024\": [2, 31],\n \"2025\": [3, 20],\n \"2026\": [3, 5,],\n \"2027\": [2, 28],\n \"2028\": [3, 16],\n \"2029\": [3, 1],\n \"2030\": [3, 21],\n \"2031\": [3, 13],\n \"2032\": [2, 28],\n \"2033\": [3, 17],\n \"2034\": [3, 9],\n \"2035\": [2, 25],\n \"2036\": [3, 13],\n \"2037\": [3, 5],\n \"2038\": [3, 2],\n \"2039\": [3, 1],\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T01:11:35.347", "Id": "211358", "ParentId": "211317", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T10:01:23.157", "Id": "211317", "Score": "1", "Tags": [ "javascript", "datetime" ], "Title": "Change state depending on holidays, weekends or hour of day" }
211317
<p>The code below is for a slideshow that shows a slide with class <em>active</em>, pre-loads a slide with class <em>next</em>, and holds the slide with class <em>last</em> in the background.</p> <p>My biggest issue with this is there seems to be lots of duplication and probably very inefficient code here that I would like to improve upon, but do not yet have that complete knowledge.</p> <p>I am not looking for the code rewritten, but would like to hear of ideas that can improve not only my knowledge of jQuery but also the efficiency of the code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('.slide:eq(-1)').addClass('last'); $('.dot:first').addClass('active'); $('.slide:first').addClass('active').delay($duration).queue(function() { $(this).addClass('show-text'); }); $('.slide:eq(1)').addClass('next'); }); // Globals var $classes = 'last active show-text next'; var $duration = 1250; // Function for the pagination operation $('.dot').on('click', function() { // the dot click var $This = $(this); // Match the index to the slide numbers var GetIndex = $This.closest('li').index() + 1; $('.dot').removeClass('active').filter($This).addClass('active'); $('.slide').dequeue(); $('.slide').removeClass($classes); // Show new active slide $('#slide' + GetIndex).addClass('active').delay($duration).queue(function() { $(this).addClass('show-text'); }); // Add class to previous slide $('.slide').eq(($('.slide.active').index() - 1) % $('.slide').length).addClass('last'); // Add class to next slide $('.slide').eq(($('.slide.active').index() + 1) % $('.slide').length).addClass('next'); }); $('.button').click(function moveSlide() { // Variables for moving slide var $active = $('.slide.active'); var $prevSlide = $('.slide').eq(($active.index() - 1) % $('.slide').length); var $afterPrevSlide = $('.slide').eq(($active.index() - 2) % $('.slide').length); var $nextSlide = $('.slide').eq(($active.index() + 1) % $('.slide').length); var $slideAfterNext = $('.slide').eq(($active.index() + 2) % $('.slide').length); // Variables for pagination var $tagNextDot = $('#' + $prevSlide.attr('id') + 'Dot'); var $tagPrevDot = $('#' + $nextSlide.attr('id') + 'Dot'); $active.dequeue(); $('.slide').removeClass($classes) $('.dot').removeClass('active'); if ($(this).is("#prev")) { $active.addClass('next'); $tagNextDot.addClass('active'); $prevSlide.addClass('active').delay($duration).queue(function() { $(this).addClass('show-text'); }); $afterPrevSlide.addClass('last'); } else { $active.addClass('last'); $tagPrevDot.addClass('active'); $nextSlide.addClass('active').delay($duration).queue(function() { $(this).addClass('show-text'); }); $slideAfterNext.addClass('next'); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-size: 16px; font-family: 'Heebo', sans-serif; text-transform: uppercase; font-weight: 900; } /* Slides */ .slide-wrapper { position: absolute; top: 0; left: 0; bottom: 0; right: 0; display: flex; overflow: hidden; } .slide { position: absolute; display: flex; justify-content: center; align-items: center; height: 100vh; width: 70%; left: 140%; z-index: 0; transition: 1.25s; box-shadow: -10px 0px 21px -5px rgba(0, 0, 0, 0.5); } .slide h2 { display: none; color: #fff; text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.5); letter-spacing: -2px; font-size: 3rem; } .slide.active.show-text h2 { display: block; animation: reveal-text 1.5s forwards; } @keyframes reveal-text { 0% { opacity: 0; } 100% { opacity: 1; } } #slide1 { background: linear-gradient(to right, #ff416c, #ff4b2b); } #slide2 { background: linear-gradient(to right, #00b4db, #0083b0); } #slide3 { background: linear-gradient(to right, #59c173, #a17fe0, #5d26c1); } #slide4 { background: linear-gradient(to right, #ad5389, #3c1053); } .slide.last { left: 0; z-index: 0; } .slide.active { left: 0; z-index: 1; } .slide.next { left: 70%; z-index: 2; } .dots-wrapper { z-index: 10; list-style: none; padding-left: 0; position: absolute; bottom: 0; padding: 10px; } .dots-wrapper li { display: inline; } .dot { display: inline-block; width: 8px; height: 8px; border: 2px solid #fff; border-radius: 6px; } .dot.active { background-color: red; border-color: red; } /* Buttons */ .button-wrapper { display: flex; z-index: 10; width: 100%; justify-content: space-between; align-items: center; } .button { background-color: rgba(0, 0, 0, 0.45); color: #ddd; height: 40px; border: none; font-weight: bold; padding: 10px 20px; transition: 0.3s; } .button:hover { cursor: pointer; background: rgba(0, 0, 0, 0.85); color: #fff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="slide-wrapper"&gt; &lt;div id="slide1" class="slide"&gt; &lt;h2&gt;Slide One.&lt;/h2&gt; &lt;/div&gt; &lt;div id="slide2" class="slide"&gt; &lt;h2&gt;Slide Two.&lt;/h2&gt; &lt;/div&gt; &lt;div id="slide3" class="slide"&gt; &lt;h2&gt;Slide Three.&lt;/h2&gt; &lt;/div&gt; &lt;div id="slide4" class="slide"&gt; &lt;h2&gt;Slide Four.&lt;/h2&gt; &lt;/div&gt; &lt;div class="button-wrapper"&gt; &lt;button id="prev" class="button"&gt;Prev.&lt;/button&gt; &lt;button id="next" class="button"&gt;Next.&lt;/button&gt; &lt;/div&gt; &lt;ul class="dots-wrapper"&gt; &lt;li&gt; &lt;span id="slide1Dot" class="dot"&gt;&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span id="slide2Dot" class="dot"&gt;&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span id="slide3Dot" class="dot"&gt;&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span id="slide4Dot" class="dot"&gt;&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Overall, I would say that the code is okay but the biggest thing that stands out is that it has <strong>A LOT</strong> of DOM queries, and while that may not slow things down much for a small DOM, it isn't very efficient. There are also some redundant callback functions that can be abstracted to a named function - e.g. the function that adds the class <code>show-text</code> to an element.</p>\n\n<hr>\n\n<p>As of the latest version of jQuery, the recommended syntax for the DOM ready callback has been simplified to just <code>$(function() {...})</code><sup><a href=\"https://api.jquery.com/ready\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n\n<hr>\n\n<p>Last year I read <a href=\"https://ilikekillnerds.com/2015/02/stop-writing-slow-javascript/\" rel=\"nofollow noreferrer\">this article about optimizing JavaScript</a> code and suggest that you take a look at it if you haven't already. I know it has a negative tone towards jQuery so ignore that if you plan to keep going with jQuery. The third sub-heading of that article is <strong>Cache DOM Lookups</strong>. You could store <code>$('.slide')</code> in a variable in the DOM-ready callback, as well as <code>$('.dot')</code> and <code>$('.button')</code> and use those when manipulating the DOM later. </p>\n\n<hr>\n\n<p>If you cache those jQuery collections then you can utilize jQuery methods like <a href=\"https://api.jquery.com/first\" rel=\"nofollow noreferrer\"><code>.first()</code></a>, <a href=\"https://api.jquery.com/last\" rel=\"nofollow noreferrer\"><code>.last()</code></a>, <a href=\"https://api.jquery.com/eq\" rel=\"nofollow noreferrer\"><code>.eq()</code></a> to filter the existing collections to particular nodes instead of running new DOM queries.</p>\n\n<p>That means that these lines:</p>\n\n<blockquote>\n<pre><code>$(document).ready(function() {\n\n $('.slide:eq(-1)').addClass('last');\n $('.dot:first').addClass('active');\n $('.slide:first').addClass('active').delay($duration).queue(function() {\n $(this).addClass('show-text');\n });\n $('.slide:eq(1)').addClass('next');\n</code></pre>\n</blockquote>\n\n<p>Could be transformed like this:</p>\n\n<pre><code>var slides, dots, buttons;\n$(function() { //DOM ready callback \n slides = $('.slide');\n dots = $('.dot');\n buttons = $('.button');\n\n slides.last().addClass('last'); \n dots.first().addClass('active'); \n slides.first().addClass('active').delay($duration).queue(function() {\n $(this).addClass('show-text');\n }); \n slides.eq(1).addClass('next'); \n</code></pre>\n\n<p>Those cached collections can also be used when adding the clock handlers to the elements with class names <em>dot</em> and <em>button</em>, which should also happen after the DOM is ready. </p>\n\n<pre><code> buttons.click(function moveSlide() {...});\n dots.click(function() {...});\n</code></pre>\n\n<hr>\n\n<p>As far as associating a dot with a slide, you could utilize <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"nofollow noreferrer\">data attributes</a> and then take advantage of the jQuery method <a href=\"http://api.jquery.com/data/\" rel=\"nofollow noreferrer\"><code>.data()</code></a> to get/set such values, but utilizing <a href=\"https://api.jquery.com/index\" rel=\"nofollow noreferrer\"><code>.index()</code></a> should be sufficient.</p>\n\n<hr>\n\n<p>As was mentioned above, the function to add class <code>show-text</code> to an element can be abstracted to a named function:</p>\n\n<pre><code>function addShowTextClass() {\n $(this).addClass('show-text');\n}\n</code></pre>\n\n<p>Then that can be used in places where that function appears - e.g. instead of </p>\n\n<blockquote>\n<pre><code>$('.slide:first').addClass('active').delay($duration).queue(function() {\n $(this).addClass('show-text');\n});\n</code></pre>\n</blockquote>\n\n<p>That can be updated to the following:</p>\n\n<pre><code>$('.slide:first').addClass('active').delay($duration).queue(addShowTextClass);\n</code></pre>\n\n<p>As well as for this line in the dot click handler:</p>\n\n<blockquote>\n<pre><code>$('#slide' + GetIndex).addClass('active').delay($duration).queue(function() {\n $(this).addClass('show-text');\n});\n</code></pre>\n</blockquote>\n\n<p>And two more occurrences in the <code>moveSlide()</code> function can be updated as well.</p>\n\n<hr>\n\n<p>The constants could be declared using the <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> keyword <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a>, unless you need to support browsers that don't support that keyword. A common convention in JavaScript and many other languages is to use all uppercase letters for constants. While there isn't anything wrong with starting variables with a dollar sign, that is typically only found with jQuery source code and plugins, but not required. If you prefer to keep those then go ahead.</p>\n\n<hr>\n\n<p>The click handlers are added in two forms - </p>\n\n<blockquote>\n<pre><code>$('.dot').on('click', function() { // the dot click\n</code></pre>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n<pre><code>$('.button').click(function moveSlide() {\n</code></pre>\n</blockquote>\n\n<p>There isn't anything wrong with using the shortcut in one place but not the other, though it is inconsistent. Why not use the same format in both places? Also, why name one but not the other?</p>\n\n<p>I would suggest moving the functions out and then after assigning the DOM collections to variables in the DOM ready callback, add the click handlers using named functions:</p>\n\n<pre><code>var dots, slides, buttons;\n\n$(function() { //DOM ready callback - see next section for explanation\n slides = $('.slide');\n dots = $('.dot');\n buttons = $('.button');\n\n dots.click(dotClickHandler);\n buttons.click(moveSlide);\n\n});\n\nfunction dotClickHandler() { ...}\nfunction moveSlide() {...}\n</code></pre>\n\n<hr>\n\n<p>This line can be eliminated:</p>\n\n<blockquote>\n<pre><code>var $This = $(this);\n</code></pre>\n</blockquote>\n\n<p>while that variable is used twice, it doesn't hurt anything to replace the two instances with <code>$(this)</code>...</p>\n\n<hr>\n\n<p>Lastly, there are quite <a href=\"https://codereview.stackexchange.com/search?q=jquery+slideshow\">a few posts on this site involving jquery slideshows</a>. It may help you to look at some of those as well.</p>\n\n<h3>Rewrite</h3>\n\n<p>The code below uses the advice above. The id attributes were removed from the dots and the same could likely be done to the slide elements if desired.</p>\n\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>// Globals\nconst CLASSES = 'last active show-text next';\nconst DELAY_DURATION = 1250;\n\nfunction addShowTextClass() {\n $(this).addClass('show-text');\n}\nvar dots, slides, buttons;\n\n$(function() { //DOM ready callback - simplified format which is recommended in jQuery documentation\n slides = $('.slide');\n dots = $('.dot');\n buttons = $('.button');\n\n slides.last().addClass('last');\n dots.first().addClass('active');\n slides.first().addClass('active').delay(DELAY_DURATION).queue(addShowTextClass); \n slides.eq(1).addClass('next');\n\n dots.click(dotClickHandler);\n buttons.click(moveSlide);\n});\n\n\n// Function for the pagination operation\nfunction dotClickHandler() { // the dot click\n\n //var $This = $(this);\n // Match the index to the slide numbers\n var listIndex = $(this).closest('li').index();\n\n dots.removeClass('active').filter($(this)).addClass('active');\n\n slides.dequeue();\n slides.removeClass(CLASSES);\n\n // Show new active slide\n slides.eq( listIndex).addClass('active').delay(DELAY_DURATION).queue(addShowTextClass);\n // Add class to previous slide\n slides.eq((slides.filter('.active').index() - 1) % slides.length).addClass('last');\n // Add class to next slide\n slides.eq(( slides.filter('.active').index() + 1) % slides.length).addClass('next');\n\n}\n\nfunction moveSlide() {\n\n // Variables for moving slide\n var $active = slides.filter('.active');\n var $prevSlide = slides.eq(($active.index() - 1) % slides.length);\n var $afterPrevSlide = slides.eq(($active.index() - 2) % slides.length);\n var $nextSlide = slides.eq(($active.index() + 1) % slides.length);\n var $slideAfterNext = slides.eq(($active.index() + 2) % slides.length);\n\n // Variables for pagination\n var $tagNextDot = dots.eq($prevSlide.index()); \n var $tagPrevDot = dots.eq($nextSlide.index()); \n\n $active.dequeue();\n slides.removeClass(CLASSES)\n dots.removeClass('active');\n\n if ($(this).is(\"#prev\")) {\n\n $active.addClass('next');\n $tagNextDot.addClass('active');\n $prevSlide.addClass('active').delay(DELAY_DURATION).queue(addShowTextClass);\n $afterPrevSlide.addClass('last');\n\n } else {\n $active.addClass('last');\n $tagPrevDot.addClass('active');\n $nextSlide.addClass('active').delay(DELAY_DURATION).queue(addShowTextClass);\n $slideAfterNext.addClass('next');\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-size: 16px;\n font-family: 'Heebo', sans-serif;\n text-transform: uppercase;\n font-weight: 900;\n}\n\n\n/* Slides */\n\n.slide-wrapper {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n display: flex;\n overflow: hidden;\n}\n\n.slide {\n position: absolute;\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n width: 70%;\n left: 140%;\n z-index: 0;\n transition: 1.25s;\n box-shadow: -10px 0px 21px -5px rgba(0, 0, 0, 0.5);\n}\n\n.slide h2 {\n display: none;\n color: #fff;\n text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.5);\n letter-spacing: -2px;\n font-size: 3rem;\n}\n\n.slide.active.show-text h2 {\n display: block;\n animation: reveal-text 1.5s forwards;\n}\n\n@keyframes reveal-text {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n#slide1 {\n background: linear-gradient(to right, #ff416c, #ff4b2b);\n}\n\n#slide2 {\n background: linear-gradient(to right, #00b4db, #0083b0);\n}\n\n#slide3 {\n background: linear-gradient(to right, #59c173, #a17fe0, #5d26c1);\n}\n\n#slide4 {\n background: linear-gradient(to right, #ad5389, #3c1053);\n}\n\n.slide.last {\n left: 0;\n z-index: 0;\n}\n\n.slide.active {\n left: 0;\n z-index: 1;\n}\n\n.slide.next {\n left: 70%;\n z-index: 2;\n}\n\n.dots-wrapper {\n z-index: 10;\n list-style: none;\n padding-left: 0;\n position: absolute;\n bottom: 0;\n padding: 10px;\n}\n\n.dots-wrapper li {\n display: inline;\n}\n\n.dot {\n display: inline-block;\n width: 8px;\n height: 8px;\n border: 2px solid #fff;\n border-radius: 6px;\n}\n\n.dot.active {\n background-color: red;\n border-color: red;\n}\n\n\n/* Buttons */\n\n.button-wrapper {\n display: flex;\n z-index: 10;\n width: 100%;\n justify-content: space-between;\n align-items: center;\n}\n\n.button {\n background-color: rgba(0, 0, 0, 0.45);\n color: #ddd;\n height: 40px;\n border: none;\n font-weight: bold;\n padding: 10px 20px;\n transition: 0.3s;\n}\n\n.button:hover {\n cursor: pointer;\n background: rgba(0, 0, 0, 0.85);\n color: #fff;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;div class=\"slide-wrapper\"&gt;\n &lt;div id=\"slide1\" class=\"slide\"&gt;\n &lt;h2&gt;Slide One.&lt;/h2&gt;\n &lt;/div&gt;\n &lt;div id=\"slide2\" class=\"slide\"&gt;\n &lt;h2&gt;Slide Two.&lt;/h2&gt;\n &lt;/div&gt;\n &lt;div id=\"slide3\" class=\"slide\"&gt;\n &lt;h2&gt;Slide Three.&lt;/h2&gt;\n &lt;/div&gt;\n &lt;div id=\"slide4\" class=\"slide\"&gt;\n &lt;h2&gt;Slide Four.&lt;/h2&gt;\n &lt;/div&gt;\n &lt;div class=\"button-wrapper\"&gt;\n &lt;button id=\"prev\" class=\"button\"&gt;Prev.&lt;/button&gt;\n &lt;button id=\"next\" class=\"button\"&gt;Next.&lt;/button&gt;\n &lt;/div&gt;\n &lt;ul class=\"dots-wrapper\"&gt;\n &lt;li&gt;\n &lt;span class=\"dot\"&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;span class=\"dot\"&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;span class=\"dot\"&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;span class=\"dot\"&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sup>1</sup><sub><a href=\"https://api.jquery.com/ready\" rel=\"nofollow noreferrer\">https://api.jquery.com/ready</a></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:10:06.520", "Id": "410830", "Score": "1", "body": "This is excellent. Thank you. This was the type of explanation I was looking for. I am yet to implement it fully but this has given me the extra bit of knowledge I was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T00:58:00.353", "Id": "211793", "ParentId": "211319", "Score": "3" } } ]
{ "AcceptedAnswerId": "211793", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T10:28:56.613", "Id": "211319", "Score": "1", "Tags": [ "javascript", "jquery", "html", "css", "animation" ], "Title": "jQuery Slideshow with pagination" }
211319
<p>I'm writing a server for an MMO game using boost::asio. I would like to know, are there any design or other issues in my code? And what should I improve in it? Thanks in advance.</p> <p><strong>BaseServer.h:</strong></p> <pre><code>#ifndef BASE_SERVER_H #define BASE_SERVER_H #include &lt;asio.hpp&gt; #include "MessageProcessor.h" class BaseServer { public: BaseServer(asio::io_context&amp; ioContext, unsigned short port) : socket(ioContext, asio::ip::udp::endpoint(asio::ip::udp::v4(), port)) { receivePacket(); } protected: asio::ip::udp::socket socket; virtual void handlePacket() = 0; private: void receivePacket() { socket.async_receive(asio::null_buffers(), [this](std::error_code ec, std::size_t bytes_recvd) { if (ec == asio::error::operation_aborted) return; handlePacket(); receivePacket(); }); } }; #endif </code></pre> <p><strong>GameServer.h:</strong></p> <pre><code>#ifndef GAME_SERVER_H #define GAME_SERVER_H #include &lt;Net/BaseServer.h&gt; #include &lt;Net/MessageProcessor.h&gt; #include &lt;Utils/BitStream.h&gt; class GameServer : public BaseServer { public: GameServer(asio::io_context&amp; ioContext, unsigned short port); protected: MessageProcessor&lt;BitStream&amp;, asio::ip::udp::endpoint&gt; messageProcessor; void asyncParsePacket(unsigned char* buffer, unsigned short packetSize, asio::ip::udp::endpoint senderEndpoint); virtual void handlePacket() override; }; #endif </code></pre> <p><strong>GameServer.cpp:</strong></p> <pre><code>#include "GameServer.h" #include &lt;iostream&gt; #include "Messages/Client/TestMessage.h" GameServer::GameServer(asio::io_context&amp; ioContext, unsigned short port) : BaseServer(ioContext, port) { messageProcessor.registerHandler(0x01, [](BitStream&amp; stream, asio::ip::udp::endpoint endpoint) { TestMessage mes; mes.deserialize(stream); std::cout &lt;&lt; "Test message received! A = " &lt;&lt; mes.a &lt;&lt; ", B = " &lt;&lt; mes.b &lt;&lt; std::endl; }); } void GameServer::asyncParsePacket(unsigned char* buffer, unsigned short packetSize, asio::ip::udp::endpoint senderEndpoint) { BitStream stream(buffer, packetSize); delete[] buffer; unsigned char messageId; stream &gt;&gt; messageId; auto handler = messageProcessor.getHandler(messageId); if (handler) handler(stream, senderEndpoint); } void GameServer::handlePacket() { unsigned int available = socket.available(); unsigned char* buffer = new unsigned char[available]; asio::ip::udp::endpoint senderEndpoint; std::error_code ec; unsigned short packetSize = socket.receive_from(asio::buffer(buffer, available), senderEndpoint, 0, ec); socket.get_io_service().post(std::bind(&amp;AuthServer::asyncParsePacket, this, buffer, packetSize, senderEndpoint)); } </code></pre> <p><strong>BaseMessage.h:</strong></p> <pre><code>#ifndef BASE_MESSAGE_H #define BASE_MESSAGE_H #include "../Utils/BitStream.h" class BaseMessage { protected: unsigned short id; public: BaseMessage(unsigned short messageId) : id(messageId) {} virtual ~BaseMessage() = default; unsigned short getId() const { return this-&gt;id; } virtual void serialize(BitStream&amp; stream) const = 0; virtual void deserialize(BitStream&amp; stream) = 0; }; #endif </code></pre> <p><strong>MessageProcessor.h</strong></p> <pre><code>#ifndef MESSAGE_PROCESSOR_H #define MESSAGE_PROCESSOR_H #include &lt;vector&gt; #include &lt;functional&gt; class BitStream; template &lt;typename ... HandlerArgs&gt; class MessageProcessor { protected: using MessageHandler = std::function&lt;void (HandlerArgs ...)&gt;; std::vector&lt;MessageHandler&gt; messageHandlers; public: void registerHandler(unsigned short id, MessageHandler handler) { if (messageHandlers.size() &lt;= id) messageHandlers.resize(id); messageHandlers.insert(messageHandlers.begin() + id, handler); } MessageHandler getHandler(unsigned short id) const { return id &lt; messageHandlers.size() ? messageHandlers[id] : 0; } }; #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:08:40.613", "Id": "408660", "Score": "0", "body": "Can you tell us more about the current functionality and why you're doing what you're doing? For example, what's the purpose of \n`handlePacket()` and why is `receivePacket()` called recursively?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:22:46.097", "Id": "408664", "Score": "0", "body": "@Mast `receivePacket()` is needed to encapsulate `async_read` function and avoid boilerplate code in derived classes. `handlePacket()` is like an `onMessageReceived()` callback. `receivePacket()` is called recursively because I need the server to receive messages in a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:27:17.123", "Id": "408665", "Score": "0", "body": "Are you aware there's such a thing as recursion depth and exceeding the maximum depth will result in a stack overflow? What is your maximum stack size and how long have you tried running your server? It *should* crash eventually if I read this right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:33:30.920", "Id": "408667", "Score": "0", "body": "@Mast This is not a recursion. `async_receive` is an asynchronous function, so it just adds new async request to the I/O queue and exits immediately." } ]
[ { "body": "<p>You can make the call to recieve_from async by creating a temp struct with the variables you need to keep alive and the buffer. Then you can put it in a shared_ptr (to account for the potential copies and capture that shared_ptr in the lambda:</p>\n\n<pre><code>void GameServer::handlePacket()\n{\n unsigned int available = socket.available();\n struct rec_data{\n std::vector&lt;unsigned char&gt; buffer;\n asio::ip::udp::endpoint senderEndpoint;\n }\n\n std::shared_ptr&lt;rec_data&gt; data = std::make_shared&lt;rec_data&gt;();\n data-&gt;buffer.resize(available);\n\n socket.receive_from(asio::buffer(data -&gt;buffer.data(), available), \n data -&gt;senderEndpoint, 0, \n [data](const std::error_code&amp; error, \n std::size_t bytes_transferred)\n {\n if(!error)\n asyncParsePacket(data-&gt;buffer.data(), bytes_transferred, data-&gt;senderEndpoint);\n });\n}\n</code></pre>\n\n<p>The int you use for <code>registerHandler</code> is a magic number. Make it an enum and give each message type a name. Make sure to share the header between the sender and receiver.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T17:05:16.553", "Id": "211335", "ParentId": "211330", "Score": "1" } } ]
{ "AcceptedAnswerId": "211335", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T15:50:34.807", "Id": "211330", "Score": "1", "Tags": [ "c++", "game", "networking", "server", "boost" ], "Title": "C++ game server" }
211330
<p>I need to calculate the BLACKLOG_M value corresponding to the Snapdate of the first of the month. It becomes a constant value repeated for each line of the month</p> <p>As it is explained in the picture:</p> <p><a href="https://i.stack.imgur.com/7llEQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7llEQ.png" alt="enter image description here"></a></p> <pre><code>SELECT T1.SNAP, T1.PERI, T1.ANNEE, T1.MOIS, T1.[BCKL], T2.[BCKL] AS BCK2,[NBR1] ,[NBR2] FROM stg.FACTSALES AS T1 LEFT OUTER JOIN (SELECT YEAR(SNAP) AS ANNEE, MONTH(SNAP) AS MOIS, [BCKL] FROM stg.FACTSALES WHERE (DAY(SNAP) = 1)) AS T2 ON T2.ANNEE = T1.ANNEE AND T2.MOIS = T1.MOIS </code></pre> <p>The script returns the correct values, but is there any another best idea or improvement?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T16:37:45.063", "Id": "211334", "Score": "1", "Tags": [ "sql", "sql-server" ], "Title": "Calculate BACKLOG_M_1" }
211334
<p>I want to search for a pattern in a time-series while either ignoring the mean/shift/bias or the scale/standard deviation.</p> <p>Consequently, I've written two functions.</p> <p>The first function searches passes through the time-series, incrementally calculating the mean for each search-space sub-sequence and using this mean to normalize the sub-sequence before comparing it to a normalized query.</p> <pre><code>function euc_dist(data::Vector{Float64}, query::Vector{Float64}, current_best::Float64)::Float64 sum = 0 for (dd, qq) in zip(data, query) sum += (dd - qq) ^ 2 if sum &gt;= current_best break end end return sum end function run_ignore_bias(data::Vector{Float64}, query::Vector{Float64})::Tuple{Float64, Int} m = length(query) # normalize query in same manner data sub-sequence will be normalized query = query .- (sum(query) / m) current_best = Inf loc = -1 # Keep current data in a double-size array to avoid using modulo # Basically, the data is stored twice and weird indexing arithmetic is used to avoid # using a LIFO queue and negative indexing. # Computational efficiency benefit unclear. t = zeros(Float64, 2*m) tz = zeros(Float64, m) run_sum = 0. for (d_i, dat) in enumerate(data) run_sum += dat t_idx = ((d_i - 1) % m) + 1 t[t_idx] = dat t[t_idx + m] = dat if d_i &gt;= m run_mean = run_sum / m # offset for search-space data s_off = (d_i % m) + 1 # offset for search-space bound data s_bound_off = (d_i - 1) - (m - 1) + 1 tz = t[s_off:s_off + m - 1] .- run_mean dist = euc_dist(tz, query, current_best) if dist &lt; current_best current_best = dist loc = s_bound_off end run_sum -= t[s_off] end end return sqrt(current_best), loc end </code></pre> <p>The second function does the same, except it normalizes according to the standard deviation.</p> <pre><code>function run_ignore_scale(data::Vector{Float64}, query::Vector{Float64})::Tuple{Float64, Int} m = length(query) # normalize scale query q_mean = sum(query) / m query = query / sqrt(sum(query.^2)/m - q_mean^2) current_best = Inf loc = -1 # Keep current data in a double-size array to avoid using modulo # Basically, the data is stored twice and weird indexing arithmetic is used to avoid # using a LIFO queue and negative indexing. # Computational efficiency benefit unclear. t = zeros(Float64, 2*m) tz = zeros(Float64, m) run_sum = 0. run_sum2 = 0. for (d_i, dat) in enumerate(data) run_sum += dat run_sum2 += dat ^ 2 t_idx = ((d_i - 1) % m) + 1 t[t_idx] = dat t[t_idx + m] = dat if d_i &gt;= m run_mean = run_sum / m # occasionally, a floating point error can cause this value to be negative, thus take the absolute value before sqrt run_std = sqrt(abs((run_sum2 / m) - (run_mean^2))) # offset for search-space data s_off = (d_i % m) + 1 # offset for search-space bound data s_bound_off = (d_i - 1) - (m - 1) + 1 tz = t[s_off:s_off + m - 1] / run_std dist = euc_dist(tz, query, current_best) @assert dist &gt; 0 if dist &lt; current_best current_best = dist loc = s_bound_off end run_sum -= t[s_off] run_sum2 -= t[s_off] ^ 2 end end return sqrt(current_best), loc end </code></pre> <p>Here are the tests for both functions.</p> <pre><code>using Test @testset "ignore bias" begin sig = [.2, .3, .5, -.4, .2, .3] data = vcat(zeros(2), sig .+ 1., zeros(8), 2*sig, zeros(4)) val, idx = run_ignore_bias(data, sig) # should find shifted signal, but not scaled signal @test idx == 3 @test isapprox(val, 0., atol=0.001) end @testset "ignore scale" begin sig = [.2, .3, .5, -.4, .2, .3] data = vcat(zeros(2), sig .+ 1., zeros(8), 2*sig, zeros(4)) val, idx = run_ignore_scale(data, sig) # should find scaled signal, but not shifted @test idx == 17 @test isapprox(val, 0., atol=0.001) end @testset "dist calc" begin dist = euc_dist([1., 2., 3.], [4., 5., 6.], Inf) @test isapprox(dist, 27.0, atol=0.001) dist = euc_dist([1., 2., 3.], [4., 5., 6.], 8.) @test isapprox(dist, 9.0, atol=0.001) end </code></pre> <p>How do I reduce the code duplication between these two functions?</p>
[]
[ { "body": "<p>I created an iterator in Julia to remove the duplicated work of array viewing.</p>\n\n<pre><code>\"\"\"\nDuplicate data and indexing arithmetic to avoid\nusing a LIFO queue or negative indexing.\n\"\"\"\nmutable struct t_iter\n data::Vector{Float64}\n t::Vector{Float64}\n length::Int\n q_len::Int\n\n function t_iter(data::Vector{Float64}, q_len::Int)\n return new(data, zeros(Float64, 2*length(data)), length(data), q_len)\n end\nend\n\n\nfunction Base.iterate(data::t_iter, d_i=1)\n if d_i &gt;= data.length\n return nothing\n end\n\n dat = data.data[d_i]\n\n t_idx = ((d_i - 1) % data.q_len) + 1\n data.t[t_idx] = dat\n data.t[t_idx + data.q_len] = dat\n\n return ((d_i, dat, data.t), d_i+1)\nend\n</code></pre>\n\n<p>The new functions and tests are as follows:</p>\n\n<pre><code>function run_ignore_bias(data::Vector{Float64}, query::Vector{Float64})::Tuple{Float64, Int}\n m = length(query)\n\n # normalize query in same manner data sub-sequence will be normalized\n query = query .- (sum(query) / m)\n\n current_best = Inf\n loc = -1\n\n tz = zeros(Float64, m)\n\n run_sum = 0.\n\n for (d_i, dat, t) in t_iter(data, m)\n run_sum += dat\n\n if d_i &gt;= m\n run_mean = run_sum / m\n\n # offset for search-space data\n s_off = (d_i % m) + 1\n\n tz = t[s_off:s_off + m - 1] .- run_mean\n dist = euc_dist(tz, query, current_best)\n\n if dist &lt; current_best\n current_best = dist\n loc = d_i - m + 1\n end\n\n run_sum -= t[s_off]\n end\n end\n\n return sqrt(current_best), loc\nend\n\n\nfunction run_ignore_scale(data::Vector{Float64}, query::Vector{Float64})::Tuple{Float64, Int}\n m = length(query)\n\n # normalize scale query\n q_mean = sum(query) / m\n query = query / sqrt(sum(query.^2)/m - q_mean^2)\n current_best = Inf\n loc = -1\n\n tz = zeros(Float64, m)\n\n run_sum = 0.\n run_sum2 = 0.\n\n for (d_i, dat, t) in t_iter(data, m)\n run_sum += dat\n run_sum2 += dat ^ 2\n\n if d_i &gt;= m\n run_mean = run_sum / m\n # occasionally, a floating point error can cause this value to be negative, thus take the absolute value before sqrt\n run_std = sqrt(abs((run_sum2 / m) - (run_mean^2)))\n\n # offset for search-space data\n s_off = (d_i % m) + 1\n\n tz = t[s_off:s_off + m - 1] / run_std\n dist = euc_dist(tz, query, current_best)\n @assert dist &gt; 0\n\n if dist &lt; current_best\n current_best = dist\n loc = d_i - m + 1\n end\n\n run_sum -= t[s_off]\n run_sum2 -= t[s_off] ^ 2\n end\n end\n\n return sqrt(current_best), loc\nend\n\n\nsig = [.2, .3, .5, -.4, .2, .3]\ndata = vcat(zeros(2), sig .+ 1., zeros(8), 2*sig, zeros(4))\nval, idx = run_ignore_bias(data, sig)\n# should find shifted signal, but not scaled signal\n@assert idx == 3\n@assert isapprox(val, 0., atol=0.001)\n\n\nsig = [.2, .3, .5, -.4, .2, .3]\ndata = vcat(zeros(2), sig .+ 1., zeros(8), 2*sig, zeros(4))\nval, idx = run_ignore_scale(data, sig)\n# should find scaled signal, but not shifted\n@assert idx == 17\n@assert isapprox(val, 0., atol=0.001)\n\n\ndist = euc_dist([1., 2., 3.], [4., 5., 6.], Inf)\n@assert isapprox(dist, 27.0, atol=0.001)\n\ndist = euc_dist([1., 2., 3.], [4., 5., 6.], 8.)\n@assert isapprox(dist, 9.0, atol=0.001)\n```\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T22:27:54.217", "Id": "212031", "ParentId": "211336", "Score": "0" } } ]
{ "AcceptedAnswerId": "212031", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T17:13:47.923", "Id": "211336", "Score": "2", "Tags": [ "julia" ], "Title": "Time-series search with early stopping" }
211336
<p>This <a href="https://stackoverflow.com/q/54132043/7347631">question</a> is the real question asked on StackOverflow. I'm here to review my <a href="https://stackoverflow.com/a/54133230/7347631">answer</a> and see how can I optimize it.</p> <hr> <h3>Here is the answer text:</h3> <p>This is a basic approach, but it proposes a proof of concept of what might be done. I do it using Bash along with the usage of the <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options" rel="nofollow noreferrer">GCC <code>-fsyntax-only</code> option</a>.</p> <p>Here is the bash script:</p> <pre><code>#!/bin/bash while IFS='' read -r line || [[ -n "$line" ]]; do LINE=`echo $line | grep -oP "(?&lt;=//).*"` if [[ -n "$LINE" ]]; then echo $LINE | gcc -fsyntax-only -xc - if [[ $? -eq 0 ]]; then sed -i "/$LINE/d" ./$1 fi fi done &lt; "$1" </code></pre> <p>The approach I followed here was reading each line from the code file. Then, <code>grep</code>ing the text after the <code>//</code> delimiter <em>(if exists)</em> with the regex <code>(?&lt;=//).*</code> and passing that to the <code>gcc -fsyntax-only</code> command <strong>to check whether it's a correct C/C++ statement or not</strong>. Notice that I've used the argument <code>-xc -</code> to pass the input to GCC from stdin <em>(<a href="https://stackoverflow.com/a/47999843/7347631">see my answer here</a> to understand more)</em>. An <strong>important</strong> note, the <code>c</code> in <code>-xc -</code> specifies the language, which is C in this case, if you want it to be C++ you shall change it to <code>-xc++</code>.</p> <p>Then, if GCC was able to successfully parse the statement (i.e., it's a legitimate C/C++ statement), I directly remove it using <code>sed -i</code> from the file passed.</p> <hr> <p>Running it on your example (<em>but after removing <code>&lt;- commented code</code> from the third line to make it a legitimate statement</em>): </p> <pre><code>// Those parameters control foo and bar... &lt;- valid comment int t = 5; // int t = 10; int k = 2*t; </code></pre> <p>Output (in the same file):</p> <pre><code>// Those parameters control foo and bar... &lt;- valid comment int t = 5; int k = 2*t; </code></pre> <p><em>(if you want to add your modifications in a different file, just remove the <code>-i</code> from <code>sed -i</code>)</em></p> <p>The script can be called just like: <code>./script.sh file.cpp</code>, it may show several GCC errors while these are the correct </p>
[]
[ { "body": "<ul>\n<li><p><code>echo | grep</code> is unwarranted. <code>bash</code> understands regular expressions (<code>\"$line\" =~ regex</code>), and can do simple substitutions: <code>line=${line#[[:space:]]*\\/\\/}</code> removes leading whitespaces , followed by the comment, just what we are after. </p></li>\n<li><p>Replacing the file while reading it looks suspiciously. I recommend to have a destination file, and copy valid lines (and don't copy undesired ones). A perk benefit is that forking <code>sed</code> is not needed anymore.</p></li>\n</ul>\n\n<p>A side note: the script makes a false positive in cases like</p>\n\n<pre><code> // Notice that\n // some_valid_c_code;\n // doesn't work, because etc\n</code></pre>\n\n<p>The part of the comment would be recognized as a dead code, and the output will be</p>\n\n<pre><code> // Notice that\n // doesn't work, because etc\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:40:34.860", "Id": "408682", "Score": "0", "body": "Your side note, you mean the code is going to remove all of the comments?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:41:57.890", "Id": "408683", "Score": "0", "body": "@AndrewNaguib No. See edit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:42:37.037", "Id": "408684", "Score": "0", "body": "Yeah, true. But, who would write a comment in such a way (i.e., \"some_valid_c_code;\"? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:45:21.453", "Id": "408685", "Score": "0", "body": "I mean, that is the question actually. The OP wants to remove dead code? What am I missing here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:47:01.513", "Id": "408686", "Score": "1", "body": "@AndrewNaguib Me, for starters. And I've seen it in the wild. That is quite a good way to explain some not-so-obvious design decisions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:59:58.887", "Id": "408690", "Score": "0", "body": "How can I use the [`=~ `](https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs) (side note: you have them reversed in the answer) if it's a binary operator? I actually `grep` to get the line following the `//` delimiter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T21:12:39.783", "Id": "408691", "Score": "1", "body": "@AndrewNaguib Thanks for pointing the typo; fixed. The operator returns 0 or 1 depending on match success or failure. Use it in `if [[ \"$line\" =~ regex]]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T16:17:30.567", "Id": "408730", "Score": "0", "body": "Indeed, it is not possible to know 100% of the time for sure if a line is code or not. As such, after applying such script, one should validate each changes before committing them to source control. And even if a line is code, it might be a part of a comment and should not be deleted (for. example a line after `// Uncomment next line to enable logging`). If next line is removed, then the comment won't make sense anymore." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:38:57.340", "Id": "211350", "ParentId": "211344", "Score": "3" } }, { "body": "<h3>Look for corner cases</h3>\n\n<p>This command is fragile, there are several ways in which it can malfunction:</p>\n\n<blockquote>\n<pre><code>sed -i \"/$LINE/d\" ./$1\n</code></pre>\n</blockquote>\n\n<p>For example:</p>\n\n<ul>\n<li><p>If the dead code contains <code>/</code>, it will break the <code>sed</code> command, because <code>/</code> within <code>/.../d</code> must be escaped.</p></li>\n<li><p>It doesn't target accurately the line to remove. It removes all lines that match <code>$LINE</code>. If there are lines in the file that are similar enough to a dead code that appears somewhere else, it will be removed too.</p></li>\n</ul>\n\n<p>Both of these problems can be fixed by tracking the line numbers that should be deleted, and then using those with the <code>d</code> command of <code>sed</code>, instead of pattern matching.</p>\n\n<hr>\n\n<p>The pattern <code>\"(?&lt;=//).*\"</code> used by the <code>grep</code> is not strict enough,\nand may incorrectly match lines that are not dead code, for example:</p>\n\n<blockquote>\n<pre><code>int x = 1; // some comment\nchar * s = \"foo // bar\";\n</code></pre>\n</blockquote>\n\n<h3>Double-quote variables used in command line arguments</h3>\n\n<p>How many bugs can you spot here?</p>\n\n<blockquote>\n<pre><code>while IFS='' read -r line || [[ -n \"$line\" ]]; do\n somecmd ./$1\ndone &lt; \"$1\"\n</code></pre>\n</blockquote>\n\n<p>I see at least:</p>\n\n<ul>\n<li><p>It doesn't handle absolute paths correctly. When <code>$1</code> is an absolute path, then <code>./$1</code> and <code>\"$1\"</code> are likely different files, except in the lucky case when the working directory is <code>/</code>.</p></li>\n<li><p><code>./$1</code> is not properly quoted, so if <code>$1</code> contains spaces or shell meta-characters, the command will fail.</p></li>\n</ul>\n\n<p>The solution is simple: quote properly and use the same path consistently <code>somecmd \"$1\"</code>.</p>\n\n<p>In addition, it's usually a good idea to assign command line arguments to variables with descriptive names at the top of a script, and then refer to it by that name, instead of have <code>$1</code> scattered at multiple places in the script.</p>\n\n<h3>Use the exit code of commands directly in conditional statements</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>somecmd\nif [[ $? -eq 0 ]]; then\n ...\nfi\n</code></pre>\n</blockquote>\n\n<p>You can write:</p>\n\n<pre><code>if somecmd; then\n ...\nfi\n</code></pre>\n\n<p>Simpler and quite natural!</p>\n\n<h3>Avoid <code>sed -i ... somefile</code> in a loop</h3>\n\n<p>Repeatedly rewriting the content of a file in a loop,\nlooks dangerous.</p>\n\n<h3>Use here-strings</h3>\n\n<p>Usually <code>echo \"...\" | somecommand</code> can be rewritten as <code>somecommand &lt;&lt;&lt; \"...\"</code>,\nusing here-strings, and saving an <code>echo</code> and a pipe.</p>\n\n<p>Then depending on <code>somecommand</code>, better options may be available,\nsuch as using <code>[[ ... =~ ... ]]</code> for pattern matching instead of <code>grep</code> (as @vnp mentioned),\nor running <code>grep</code> on a larger outer scope (as demonstrated in the previous point).</p>\n\n<h3>Alternative implementation</h3>\n\n<p>Consider this alternative implementation that fixes the above issues and bad practices.</p>\n\n<pre><code>#!/usr/bin/env bash\n\ninput=$1\n\nsed_commands=()\nline_num=1\nwhile IFS= read -r line || [[ \"$line\" ]]; do\n if [[ \"$line\" =~ ^[[:space:]]+// ]]; then\n if gcc -fsyntax-only -xc - &lt;&lt;&lt; \"$line\"; then\n sed_commands+=(-e \"${line_num}d\")\n fi\n fi\n ((line_num++))\ndone &lt; \"$input\"\n\nsed \"${sed_commands[@]}\" -i \"$input\"\n</code></pre>\n\n<p>The weakness of this alternative is that if there are enough dead code lines in the input, then the maximum argument count limit of the shell may be reached in the final <code>sed</code> command. When that becomes a realistic issue, it can be optimized to handle that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T07:13:44.013", "Id": "213130", "ParentId": "211344", "Score": "3" } } ]
{ "AcceptedAnswerId": "211350", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:38:11.387", "Id": "211344", "Score": "3", "Tags": [ "c++", "c", "regex", "bash", "grammar" ], "Title": "Removing commented dead code without removing the legitimate comments" }
211344
<p>I've been working on <a href="https://leetcode.com/problems/longest-mountain-in-array/" rel="noreferrer">longest mountain in array on Leetcode</a>:</p> <blockquote> <p>Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:</p> <ul> <li><code>B.length &gt;= 3</code></li> <li>There exists some <code>0 &lt; i &lt; B.length - 1</code> such that <code>B[0] &lt; B[1] &lt; ... B[i-1] &lt; B[i] &gt; B[i+1] &gt; ... &gt; B[B.length - 1]</code></li> </ul> <p>(Note that B could be any subarray of A, including the entire array A.)</p> <p>Given an array A of integers, return the length of the longest <em>mountain</em>. </p> <p>Return <code>0</code> if there is no mountain.</p> <h3>Example:</h3> <p>Input: [2,1,4,7,3,2,5]<br> Output: 5<br> Explanation: The largest mountain is [1,4,7,3,2] which has length 5.</p> </blockquote> <p>I've come up with a solution that passes the test but only beats 17% of javascript submissions. I just want to know if there's anything I can do with my code to optimize it's performance. Also please let me know if the code could be written better. </p> <p>The idea is as followed. In a mountain array we have a start, peak, and an end. I keep track of when a mountain starts, when a mountain peaks and when a mountain ends. When the mountain ends i pop off my start value from the start stack and use the spread operator to add it to a result array which contains the peak and the end of a mountain. </p> <p>For example the array [1,3,8]... the mountain starts at index 1, peaks at index 3 and ends at index 8. In order to find the length of the array I then subtract the end from the start. </p> <p>A mountain can have multiple peaks and thus an array such as [[1,3,8],[8,13,18]] is possible. I'm handling this situation by having a maxDifference variable to store the maximum differences if a mountain is complete [start, peak, end]. </p> <pre><code>var longestMountain = function(A) { let maxDifference = 0; let startPeakEnd = []; const start = []; const innerLoop = []; if(A[1]&gt;A[0])start.push(0) else start.push(1); for(let i = 0; i &lt; A.length; i++){ if(A[i-1]&lt;A[i] &amp;&amp; A[i+1]&lt;A[i]){ startPeakEnd.push(i); }else if(A[i-1]&gt;=A[i] &amp;&amp; A[i+1]&gt;=A[i]){ startPeakEnd.push(i); innerLoop.push([start.pop(),...startPeakEnd]); start.push(i) startPeakEnd = []; }else if(A[i+1]===undefined){ startPeakEnd.push(i); innerLoop.push([start.pop(),...startPeakEnd]); } } for(let item of innerLoop){ if(item.length===3){ if(item[2]-item[0]+1&gt;maxDifference){ maxDifference=item[2]-item[0]+1; } } } return maxDifference; }; </code></pre>
[]
[ { "body": "<p>It would be better to try and use built in functions for iterating over arrays. It appears that you are trying to generate and store all possible mountains. This would not be necessary. This would be my approach.</p>\n\n<pre><code>var longestMountain = function(arr) {\n //get nodes that may be the peaks of mountains\n var candidates = arr.map(function(currentValue, index) {\n if (index == 0 || index === arr.length - 1) {\n return false;\n } else {\n return arr[index - 1] &lt; currentValue &amp;&amp; arr[index + 1] &gt; currentValue;\n }\n });\n\n //for each index, calculate the height of the slope where arr[i - 1] &lt; arr[i]\n var increasingMountainCounts = arr.map(function(currentValue, index) {\n if (index == 0 || arr[index - 1] &gt;= currentValue) {\n return 0;\n } else {\n return arr[index - 1] + 1;\n }\n });\n\n //for each index, calculate the height of the slope where arr[i - 1] &gt; arr[i]\n var decreasingMountainCounts = arr.reverse().map(function(currentValue, index) {\n if (index == 0 || arr[index - 1] &gt;= currentValue) {\n return 0;\n } else {\n return arr[index - 1] + 1;\n }\n });\n\n //for each candidate peak, get the height of the mountain with that peak\n var maxMountainHeight = 0;\n\n candidates.forEach(function(currentValue, index) {\n if (currentValue !== true) {} else {\n maxMountainHeight = Math.max(maxMountainHeight, increasingMountainCounts[index - 1] + decreasingMountainCounts[index + 1] + 1);\n }\n });\n\n return maxMountainHeight;\n\n};\n</code></pre>\n\n<p>An alternative approach which uses more javascript array iterators but in my opinion makes the code a bit less readable.</p>\n\n<pre><code>var longestMountain = function(arr) {\n var candidates = arr.map(function(currentValue, index) {\n if (index == 0 || index === arr.length - 1) {\n return false;\n } else {\n return arr[index - 1] &lt; currentValue &amp;&amp; arr[index + 1] &gt; currentValue;\n }\n });\n\n var increasingMountainCounts = arr.map(function(currentValue, index) {\n if (index == 0 || arr[index - 1] &gt;= currentValue) {\n return 0;\n } else {\n return arr[index - 1] + 1;\n }\n });\n\n var decreasingMountainCounts = arr.reverse().map(function(currentValue, index) {\n if (index == 0 || arr[index - 1] &gt;= currentValue) {\n return 0;\n } else {\n return arr[index - 1] + 1;\n }\n });\n\n var maxMountainHeightAccumulator = (maxMountainHeight, currentValue, index) =&gt; {\n if (currentValue !== true) {\n return maxMountainHeight;\n } else {\n return Math.max(maxMountainHeight, increasingMountainCounts[index - 1] + decreasingMountainCounts[index + 1] + 1);\n }\n };\n\n return candidates.reduce(maxMountainHeightAccumulator, 0);\n\n};\n</code></pre>\n\n<p>In terms of improving performance, this reminds me of the problem of finding the (contigious) subsequence with the maximum sum/product. That solution would probably require completely rewriting your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T22:07:13.953", "Id": "211393", "ParentId": "211349", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:37:49.010", "Id": "211349", "Score": "6", "Tags": [ "javascript", "performance", "algorithm", "programming-challenge" ], "Title": "Leetcode Mountain Array" }
211349
<p>I am trying to sort the <code>option</code>s within a <code>SELECT</code> element. I wonder if I am doing it stupidly or not, so perhaps someone can look at it and provide suggestions.</p> <pre><code>// Function Name = sortSelect(jsID, tagAttr) // Function Purpose = Sort elements within a select element by supplying the ID of the select element. Sorting parameter is based on the order of the tags passed in through tagAttr as an array with decreasing importance. CSS styles can be use as a sort parameters as well with syntax css: // Example Call = sortSelect("element", ["css: display", "id"]); function sortSelect(jsID, tagAttr) { var jqID = "#"+jsID; var arrHold = []; var arrTemp = []; var arrObjs = []; var ct; var comp; if ($(jqID).prop("tagName").toUpperCase() == "SELECT") { $(jqID + " option").each(function() { arrHold = []; arrHold.push($(this)); for (var j in tagAttr) { if (tagAttr[j].replace(/\s+/g, '').substring(0, 4) !== "css:") { arrHold.push($(this).attr(tagAttr[j])); } else { arrHold.push($(this).css(tagAttr[j].replace(/\s+/g, '').substring(4, tagAttr[j].length).trim())); } j+=1; } arrTemp.push(arrHold); ct+=1; }); if (ct &lt; $("#"+jsID).childElementCount) { var message = "Nodes other than 'option' has been detected, and may have been lost!" console.warn(message); } arrTemp = arrTemp.sort(function(a,b) { for (i=1; i&lt;=tagAttr.length; i++) { comp = (''+a[i]).localeCompare(b[i]); if (comp != 0) { return comp; } } return 0; }); for (i=0; i &lt; arrTemp.length; i++) { arrObjs.push(arrTemp[i][0]); } $(jqID).empty(); $(jqID).append(arrObjs); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T00:22:53.680", "Id": "211356", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Sorting options within a select element" }
211356
<p>I've created a system to generate tokens that could potentially be used in some sort of program:</p> <pre><code># _gen.py is simply to generate the tokens, not to check them. import string, secrets, random # String is for getting all ascii letters and digits. # Secrets is for a cryptographically secure function to choose chars. # Random is providing a random number generator. # Base functions used to generate a token def _tknFrag(length: int=32): """Generates a tknFrag, or Token Fragment.""" return ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length)) def _tknFragLen(): """Returns the tknFrag's tknFragLen, or Token Fragment Length, an int in between 30 and 34""" return int(random.randint(30, 34)) def _insDot(tknFrag: str): """Inserts a dot in the tknFrag at the end""" tknFrag += "." return tknFrag def _insDash(tknFrag: str): """Inserts a dash in the tknFrag at the end""" tknFrag += "-" return tknFrag def _ins(tknFrag: str): """Inserts a dash or a dot inside of the tknFrag""" return { "0" : lambda frag: _insDot(tknFrag=frag), "1" : lambda frag: _insDash(tknFrag=frag) }[str(random.randint(0, 1))](tknFrag) # Now on to actually generating the tokens # This is one last helper function, completely generating a fragment def tokenFragment(repetition): """Generates a fragment with the random length, and the dot/dash. The repetition is to determine wether or not to actually put the dot/dash at the end of the token.""" return _ins(_tknFrag(length=_tknFragLen())) if repetition != 2 else _tknFrag(length=_tknFragLen()) def token(): """Generates a three-fragment-long token""" return "".join([tokenFragment(repetition) for repetition in range(3)]) # Gotta test it somehow if __name__ == '__main__': print(token()) </code></pre> <p>Here are five results from running the code:</p> <pre class="lang-none prettyprint-override"><code>2dD0ZYjV4AOGMzZ2lIg6wVPzwpB82Z.BsX34AaWpvJ7i6jtWzYI1zNRjz2pI0.GRW9Uhfl9P8Xu7pYzoSYutEwuhqjhQnN </code></pre> <p></p> <pre class="lang-none prettyprint-override"><code>AghhjknBMqgKLpD6rR90iXKj2yuT44B.CAyXZJtAE62L97SZUbadGBmXTTSflC9th.RbuKtUDWxQ9ROgwo2OkKYEozHc1ToRz8Q </code></pre> <p></p> <pre class="lang-none prettyprint-override"><code>5sFE1npNyEA7JCz9hHEJFwmP2aX4CY3p.RMiKkilzUp7kmJCigrB6HfOVPkWmsczJ-4DF3qLuQSgdwmRxiOMBLUw1ZLj1Al7n </code></pre> <p></p> <pre class="lang-none prettyprint-override"><code>6FCXlDGWjAKylt5rZFYxOfLecxyyL4Pj-0MGu0B2knedbR8HnFI16gHChWZ8uldQ.chCVuFycHPJXF2tj9wR3mi4W4yuRp3o </code></pre> <p></p> <pre class="lang-none prettyprint-override"><code>rEAi9Rn1lXNkMett8wHXLF0iJLQHbc6lI.ksViH35sOlIwFfvOjVHlyXfMS0Ye58diZB-jEX93wyHTRznkYUJvbADmOrdZZF2D0R0 </code></pre> <p><strong>Note that the dots and dashes are for looks only and serve no purpose.</strong></p>
[]
[ { "body": "<p>Well, in the first place I have a question as to why you would need this specific pattern of tokens; it seems for a very specific use case.</p>\n\n<p>Secondly, you use a pretty consistent naming convention in your code (which is very good), but the shortened names and abbreviations make it difficult for a person to understand your code quickly (in my opinion).</p>\n\n<hr>\n\n<p>Lastly, if you are looking for less code and more speed with the same functionality, I can propose this:</p>\n\n<pre><code>import random\nimport secrets\nimport string\n\nFRAGMENT_ALPHABET = string.ascii_letters + string.digits\nFRAGMENT_SEPARATOR_OPTIONS = ('.', '-')\nFRAGMENT_MIN_LENGTH = 30\nFRAGMENT_MAX_LENGTH = 34\n\ndef _generate_fragment(length: int, prepend_separator: bool):\n prefix = ''\n if prepend_separator:\n prefix = secrets.choice(FRAGMENT_SEPARATOR_OPTIONS)\n\n s = ''.join(\n secrets.choice(FRAGMENT_ALPHABET)\n for _ in range(length))\n\n return prefix + s\n\ndef token(num_parts: int = 3):\n return ''.join(\n _generate_fragment(\n length=random.randint(FRAGMENT_MIN_LENGTH, FRAGMENT_MAX_LENGTH),\n prepend_separator=i &gt; 0) # only False for the first fragment\n for i in range(num_parts))\n</code></pre>\n\n<p>In this code:</p>\n\n<ul>\n<li>In my opinion (opinions can be very subjective) the code is still readable, but has less functions and those have explicit long names, which helps users to understand it faster.</li>\n<li>I also put some general parameters as uppercase module variables at the top of the file; this makes it easier to modify and (in my opinion) also easier to read/understand in the code.</li>\n<li><p>The execution time is less. Comparing the two versions using <code>timeit</code> like this for both versions (with <code>Ubuntu</code> and <code>Python3.6</code>):</p>\n\n<pre><code>&gt;&gt;&gt; timeit.timeit('token()', 'from __main__ import token', number=10000)\n</code></pre>\n\n<p>I get these results, showing my version as faster using about 8 % less time:</p>\n\n<pre><code>Version Time Time comparisson\nyours 2.222258 100.0 %\nmine 2.060732 92.7 %\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T19:51:04.163", "Id": "408746", "Score": "0", "body": "Thank you! Although, the shortened names were not designed to be used by the user. They were designed to be used by the `_ins` and `token` functions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T14:27:12.163", "Id": "211373", "ParentId": "211359", "Score": "3" } } ]
{ "AcceptedAnswerId": "211373", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T02:03:53.270", "Id": "211359", "Score": "3", "Tags": [ "python", "python-3.x", "random" ], "Title": "Token generation system in py3.7" }
211359
<p>I have been recently trying my hands on Euler's Project through HackerRank and got stuck with project #3 where you have to find the <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler003" rel="nofollow noreferrer">Largest Prime Factor.</a></p> <p><strong>Question:</strong> <em>The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of a given number N?</em></p> <p>I have written two different codes which both work for the first four problems in HackerRank but timeout on the last two. Please let me know how I can optimize my code further so that the timeout doesn't occur.</p> <p><strong>Code #1</strong></p> <pre><code>for a in range(int(input())): n = int(input()) b = n//2 i=1 if b%2==1: i+=1 max=1 while b &gt; 2: if n%b==0: isprime = True for c in range(2,int(b**0.5)+1): if b%c==0: isprime = False break; if isprime: max = b break; b-=i if max==1: max=n print(max) </code></pre> <p>This one tries to find the first largest numbers which can divide a particular number and then tries to find whether it is a prime. </p> <p><strong>Code #2</strong></p> <pre><code>for a in range(int(input())): n = int(input()) num = n b = 2 max=1 while n &gt; 1 and b &lt; (num//2)+1: if n%b==0: n//=b max=b b+=1 if max==1: max=n print(max) </code></pre> <p>This basically tries to find the last largest factor by multiple division.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T06:27:49.003", "Id": "408703", "Score": "2", "body": "Please fix your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T11:38:35.813", "Id": "408795", "Score": "0", "body": "Who are `a` and `b` and why haven't you used more sensible names instead? Can you tell us more about your approach?" } ]
[ { "body": "<p>It seems to me your second code example is wrong. You divide out only one prime factor and moving on testing for divisibility. If you enter, say: <code>8</code>, it finds 2, divides it out, which gives 4, and will find 4 as largest prime that divides 8.</p>\n\n<p>You have a lot of redundant tests, stepping <code>b</code> by one. </p>\n\n<p>Consider this:<br>\nWrite any positive number <code>n</code> as <code>n = m + 6*q</code> (<code>q</code> may be 0). Except for the prime numbers 2 and 3: If <code>m</code> is divisible by 2, then so is <code>n</code> (because 6 is divisible by 2). If <code>m</code> is divisible by 3, then so is <code>n</code> (again, because 6 is divisible by 3). The only chances for <code>n</code> to be prime is, if <code>m</code> is 1 or 5. Not all of those numbers are prime, but if it is prime, it will be 1 or 5 modulo 6.</p>\n\n<p>That will add a few lines of code, to explicitly test for primes 2 and 3. But after that, it should speed up your algorithm. Just remember to divide out <em>all</em> powers of a prime before moving on. A single test could look like this:</p>\n\n<pre><code>n = int(input())\nnum = n\nmax = 1\n\nif n % 2 == 0:\n max = 2\n while n % 2 == 0:\n n //= 2\n\nif n % 3 == 0:\n max = 3\n while n % 3 == 0: \n n //= 3\n\nb = 5\ninc = 2\n\nwhile n != 1:\n if n % b==0:\n max = b\n while n % b == 0: \n n //= b\n\n b += inc\n if inc == 2:\n inc = 4\n else:\n inc = 2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T08:46:37.430", "Id": "408708", "Score": "0", "body": "Welcome to Code Review. Please don't answer off-topic questions. As long as the indentation in the original question is off (and thus the code broken), the question is considered off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T10:05:33.413", "Id": "408715", "Score": "0", "body": "@Zeta Understood. Thanks for the heads up!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T07:09:18.200", "Id": "211364", "ParentId": "211361", "Score": "1" } }, { "body": "<p>It may be more optimal to use the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> because it may reuse calculations better than the given approaches. This would be a bottom-up approach rather than a top-down approach but it is a very efficient bottom-up approach.</p>\n\n<p>You just need to take the extra step where for each entry you find to be prime, you check if it is a factor of the given number. You also have a early stopping condition - the prime factor must be &lt;=sqrt(N). So you need a sieve for 1 ... sqrt(N)</p>\n\n<p>Note that there are ways to work with a segmented sieve, to minimise the amount of memory used at once.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T17:33:29.077", "Id": "211381", "ParentId": "211361", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T03:29:24.887", "Id": "211361", "Score": "0", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "primes" ], "Title": "Euler Project #3 Largest prime factor timeout" }
211361
<p>I'm trying to expand on the implementation of static_vector on the <code>std::aligned_storage</code> <a href="https://en.cppreference.com/w/cpp/types/aligned_storage" rel="nofollow noreferrer">reference page</a>, but would like to split it into two parts. First, an <code>aligned_storage_array</code> that supports perfect forwarding (so that I can emplace into it) and doesn't require a default constructor, and then the actual <code>static_vector</code> infrastructure that builds upon it. This will let me use the <code>aligned_storage_array</code> for some other static data structures I plan to make in the future.</p> <p><strong>aligned_storage_array.h</strong></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; namespace nonstd { template&lt;class T, std::size_t N&gt; class aligned_storage_array { public: aligned_storage_array() = default; ~aligned_storage_array() = default; // Move and copy must be manually implemented per-element by the user aligned_storage_array(aligned_storage_array&amp;&amp; rhs) = delete; aligned_storage_array&amp; operator=(aligned_storage_array&amp;&amp; rhs) = delete; aligned_storage_array(const aligned_storage_array&amp; rhs) = delete; aligned_storage_array&amp; operator=(const aligned_storage_array&amp; rhs) = delete; // Size constexpr std::size_t size() const noexcept { return N; } constexpr std::size_t max_size() const noexcept { return N; } // Access inline T&amp; operator[](std::size_t pos) { return *std::launder( reinterpret_cast&lt;T*&gt;( std::addressof(m_data[pos]))); } inline const T&amp; operator[](std::size_t pos) const { return *std::launder( reinterpret_cast&lt;const T*&gt;( std::addressof(m_data[pos]))); } inline T&amp; at(std::size_t pos) { return *std::launder( reinterpret_cast&lt;T*&gt;( std::addressof(m_data.at(pos)))); } inline const T&amp; at(std::size_t pos) const { return *std::launder( reinterpret_cast&lt;const T*&gt;( std::addressof(m_data.at(pos)))); } // Operations template&lt;typename ...Args&gt; inline T&amp; emplace(size_t pos, Args&amp;&amp;... args) { return *::new(std::addressof(m_data[pos])) T(std::forward&lt;Args&gt;(args)...); } template&lt;typename ...Args&gt; inline T&amp; bounded_emplace(size_t pos, Args&amp;&amp;... args) { return *::new(std::addressof(m_data.at(pos))) T(std::forward&lt;Args&gt;(args)...); } inline void destroy(std::size_t pos) { std::destroy_at( std::launder( reinterpret_cast&lt;const T*&gt;( std::addressof(m_data[pos])))); } inline void bounded_destroy(std::size_t pos) { std::destroy_at( std::launder( reinterpret_cast&lt;const T*&gt;( std::addressof(m_data.at(pos))))); } private: std::array&lt;std::aligned_storage_t&lt;sizeof(T), alignof(T)&gt;, N&gt; m_data; }; } </code></pre> <p><strong>static_vector.h</strong></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;stdexcept&gt; #include "aligned_storage_array.h" namespace nonstd { template&lt;class T, std::size_t N&gt; class static_vector { public: using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = value_type&amp;; using const_reference = const value_type&amp;; using iterator = value_type*; using const_iterator = const value_type*; using size_type = std::size_t; static_vector() = default; ~static_vector() { clear(); } static_vector(const static_vector&amp; rhs) { clear(); // Sets m_size to zero for safety for (std::size_t pos = 0; pos &lt; rhs.m_size; ++pos) m_data[pos] = rhs.m_data[pos]; m_size = rhs.m_size; } static_vector&amp; operator=(const static_vector&amp; rhs) { if (this != std::addressof(rhs)) { clear(); // Sets m_size to zero for safety for (std::size_t pos = 0; pos &lt; rhs.m_size; ++pos) m_data[pos] = rhs.m_data[pos]; m_size = rhs.m_size; } return *this; } static_vector(static_vector&amp;&amp; rhs) { // Start by clearing sizes to avoid bad data // access in the case of an exception std::size_t count_self = m_size; std::size_t count_rhs = rhs.m_size; m_size = 0; rhs.m_size = 0; // Can't swap because the destination may be uninitialized destroy_n(count_self); for (std::size_t pos = 0; pos &lt; count_rhs; ++pos) m_data[pos] = std::move(rhs.m_data[pos]); m_size = count_rhs; } static_vector&amp; operator=(static_vector&amp;&amp; rhs) { // Start by clearing sizes to avoid bad data // access in the case of an exception std::size_t count_self = m_size; std::size_t count_rhs = rhs.m_size; m_size = 0; rhs.m_size = 0; // Can't swap because the destination may be uninitialized destroy_n(count_self); for (std::size_t pos = 0; pos &lt; count_rhs; ++pos) m_data[pos] = std::move(rhs.m_data[pos]); m_size = count_rhs; return *this; } // Size and capacity constexpr std::size_t size() const { return m_size; } constexpr std::size_t max_size() const { return N; } constexpr bool empty() const { return m_size == 0; } // Iterators inline iterator begin() { return &amp;m_data[0]; } inline const_iterator begin() const { return &amp;m_data[0]; } inline iterator end() { return &amp;m_data[m_size]; } inline const_iterator end() const { return &amp;m_data[m_size]; } // Access inline T&amp; operator[](std::size_t pos) { return m_data[pos]; } inline const T&amp; operator[](std::size_t pos) const { return m_data[pos]; } inline T&amp; at(std::size_t pos) { if ((pos &lt; 0) || (pos &gt;= m_size)) throw std::out_of_range("static_vector subscript out of range"); return m_data[pos]; } inline const T&amp; at(std::size_t pos) const { if ((pos &lt; 0) || (pos &gt;= m_size)) throw std::out_of_range("static_vector subscript out of range"); return m_data[pos]; } // Operations template&lt;typename ...Args&gt; inline T&amp; emplace_back(Args&amp;&amp;... args) { T&amp; result = m_data.bounded_emplace(m_size, args...); ++m_size; return result; } inline void clear() { std::size_t count = m_size; m_size = 0; // In case of exception destroy_n(count); } private: void destroy_n(std::size_t count) { for (std::size_t pos = 0; pos &lt; count; ++pos) m_data.destroy(pos); } aligned_storage_array&lt;T, N&gt; m_data; std::size_t m_size = 0; }; } </code></pre> <p>A full testing apparatus is available <a href="https://wandbox.org/permlink/bvq4dcHHL3vQK95m" rel="nofollow noreferrer">here</a> (wandbox). Mostly I'd like some extra eyes to help determine:</p> <ol> <li>Is this <em>actually</em> safe for placement new with respect to alignment?</li> <li>Is the use of <code>std::launder</code> correct?</li> <li>Is the use of <code>reinterpret_cast</code> correct (or should it be two <code>static_cast</code>s instead?)</li> <li>Are there any hidden pitfalls I should watch out for here (aside from the maximum capacity)?</li> <li>Am I being sufficiently paranoid (<code>::new</code>, <code>std::address_of</code>, <code>std::destroy_at</code>)? Any other safety features I can put in to handle risky operator overloads?</li> <li>Is this approach to copy/move correct? I feel as though I need to be hands-on because the underlying array may have unknown uninitialized fields. Am I doing the right thing about exception safety? I decided I'd rather have the vector appear empty than have it appear full with malformed entries.</li> <li>What should I do, if anything, about an <code>std::swap</code> on either data structure?</li> </ol> <p>I'm told this is similar to something like <code>boost::small_vector</code>, but I want the <code>aligned_storage_array</code> generalized because I want to use it for a number of different static structures later. Also, I would like to learn more about alignment/placement new, forwarding, and launder.</p>
[]
[ { "body": "<pre><code>static_vector(const static_vector&amp; rhs)\n{\n clear(); // Sets m_size to zero for safety\n for (std::size_t pos = 0; pos &lt; rhs.m_size; ++pos)\n m_data[pos] = rhs.m_data[pos];\n m_size = rhs.m_size;\n}\n</code></pre>\n\n<p><code>clear()</code> is not needed (<code>m_size</code> is already zero because of the default member initializer). </p>\n\n<p><strong>bug:</strong> We are assigning to elements that haven't been constructed yet! We need to use placement new (either through the <code>emplace</code> function, or <code>std::uninitialized_copy_n</code>) to construct each element in place. The move constructor has the same issue.</p>\n\n<hr>\n\n<pre><code>static_vector(static_vector&amp;&amp; rhs)\n{\n // Start by clearing sizes to avoid bad data\n // access in the case of an exception\n std::size_t count_self = m_size;\n std::size_t count_rhs = rhs.m_size;\n m_size = 0;\n rhs.m_size = 0;\n\n // Can't swap because the destination may be uninitialized\n destroy_n(count_self);\n for (std::size_t pos = 0; pos &lt; count_rhs; ++pos)\n m_data[pos] = std::move(rhs.m_data[pos]);\n m_size = count_rhs;\n}\n</code></pre>\n\n<p>Same issue as above (assignment to non-constructed elements).</p>\n\n<p>We could call <code>clear()</code> to set the size to zero and destroy the elements in <code>this</code>.</p>\n\n<p><strong>bug:</strong> It's incorrect to alter the size of <code>rhs</code> like this. Although we have moved from the <code>rhs</code> elements, they still \"exist\", and we need to call their destructors. (Note that unlike <code>std::vector</code>, <code>std::array</code> isn't empty after a \"move\").</p>\n\n<p>If we want <code>rhs</code> to be empty afterwards, we can call <code>rhs.clear()</code> after moving the elements.</p>\n\n<hr>\n\n<p>The copy / move construction / assignment can be simplified quite a bit:</p>\n\n<pre><code>static_vector(const static_vector&amp; rhs)\n{\n std::uninitialized_copy(rhs.begin(), rhs.end(), begin());\n m_size = rhs.m_size;\n}\n\nstatic_vector&amp; operator=(const static_vector&amp; rhs)\n{\n clear();\n std::uninitialized_copy(rhs.begin(), rhs.end(), begin());\n m_size = rhs.m_size;\n return *this;\n}\n\nstatic_vector(static_vector&amp;&amp; rhs)\n{\n std::uninitialized_move(rhs.begin(), rhs.end(), begin());\n m_size = rhs.m_size;\n}\n\nstatic_vector&amp; operator=(static_vector&amp;&amp; rhs)\n{\n clear();\n std::uninitialized_move(rhs.begin(), rhs.end(), begin());\n m_size = rhs.m_size;\n return *this;\n}\n</code></pre>\n\n<hr>\n\n<p>Swapping is never going to be fast because we're storing the elements on the stack, and have to swap them all in turn. We could write something with <code>std::swap_ranges</code>, and then <code>std::uninitialized_move</code> any extra elements if there's a size mismatch, but I'd probably just do this:</p>\n\n<pre><code> // member function\n void swap(static_vector&amp; rhs)\n {\n auto temp = std::move(*this);\n *this = std::move(rhs);\n rhs = std::move(temp);\n }\n\n...\n\n// free function in the nonstd namespace\ntemplate&lt;class T, std::size_t N&gt;\nvoid swap(static_vector&lt;T, N&gt;&amp; a, static_vector&lt;T, N&gt;&amp; b)\n{\n a.swap(b);\n}\n</code></pre>\n\n<hr>\n\n<p>I think preventing copy and move (and not defining swap) on <code>aligned_storage_array</code> is fine.</p>\n\n<hr>\n\n<pre><code>inline T&amp; at(std::size_t pos)\n{\n if ((pos &lt; 0) || (pos &gt;= m_size))\n ...\n}\n</code></pre>\n\n<p><code>pos</code> is (correctly) unsigned, so <code>(pos &lt; 0)</code> isn't needed.</p>\n\n<p>Use the <code>size_type</code> typedef for the function argument (same with the other element access functions).</p>\n\n<p>There's no need to use the <code>inline</code> keyword for functions defined in a class body.</p>\n\n<hr>\n\n<pre><code> inline iterator begin() { return &amp;m_data[0]; }\n inline const_iterator begin() const { return &amp;m_data[0]; }\n inline iterator end() { return &amp;m_data[m_size]; }\n inline const_iterator end() const { return &amp;m_data[m_size]; }\n</code></pre>\n\n<p><strong>bug:</strong> This is undefined behaviour. The array elements at <code>[m_size]</code> or even <code>[0]</code> may not exist. (So the <code>std::array</code> implementation may sensibly throw or crash if we try to access them).</p>\n\n<p>We can fix this with:</p>\n\n<pre><code> // in aligned_storage_array:\n T* data()\n {\n return std::launder(\n reinterpret_cast&lt;T*&gt;(m_data.data()));\n }\n\n T const* data() const\n {\n return std::launder(\n reinterpret_cast&lt;T const*&gt;(m_data.data()));\n }\n\n ...\n\n // in static_vector:\n iterator begin() { return m_data.data(); }\n const_iterator begin() const { return m_data.data(); }\n iterator end() { return m_data.data() + m_size; }\n const_iterator end() const { return m_data.data() + m_size; }\n</code></pre>\n\n<p>This gives us pointer access, which is what we need for iterators. As long as we only dereference pointers to valid elements, we avoid undefined behaviour (i.e. don't dereference <code>end()</code>, and only use <code>begin()</code> if <code>size()</code> isn't zero).</p>\n\n<hr>\n\n<pre><code> template&lt;typename ...Args&gt;\n inline T&amp; emplace_back(Args&amp;&amp;... args)\n {\n T&amp; result = m_data.bounded_emplace(m_size, args...);\n ...\n }\n</code></pre>\n\n<p>We should use <code>std::forward</code> here (it's correctly used in the <code>aligned_storage_array::emplace</code> functions).</p>\n\n<hr>\n\n<p>I'm really not very familiar with <code>std::launder</code>, so hopefully someone else can comment on that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T01:16:26.563", "Id": "408849", "Score": "0", "body": "These are great. I have two follow-up questions.\n\n\n(1) Should I retain the `if (this != std::addressof(rhs))` check in `static_vector`'s copy? I noticed you removed it in your simplication.\n\n(2) Would `std::destroy_n` be a safe/viable alternative to use in the `static_vector` `destroy_n()` function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T01:30:17.520", "Id": "408850", "Score": "0", "body": "One additional note, after testing. The new move constructor and assignment of the `static_vector` doesn't set the `rhs` structure's `m_size` to zero, which means that that that `rhs` `static_vector` will destruct its (now potentially unknown) contents when going out of scope. Should I add a line to set it to zero in this case and avoid that behavior?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T07:52:01.820", "Id": "408870", "Score": "1", "body": "(1) It's not needed. Copy / swap works for self-assignment too. Note that checking would add overhead for the non-self-assignment cases, which are the ones we want to be faster! (2) Yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T08:01:26.807", "Id": "408871", "Score": "1", "body": "Yes. We still need to call destructors on moved-from objects, so directly setting `m_size` to zero is wrong. But if we want the `static_vector` to be empty after move (probably a good design choice), we can call `clear()` on `rhs` just before returning from the constructor / operator." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T09:39:55.863", "Id": "211367", "ParentId": "211362", "Score": "3" } } ]
{ "AcceptedAnswerId": "211367", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T03:29:28.340", "Id": "211362", "Score": "3", "Tags": [ "c++", "memory-management", "template", "c++17", "sfinae" ], "Title": "Implementation of static_vector using an array of std::aligned_storage, with std::launder and forwarding" }
211362
<p>I made a simple password cracker using Python. But it's <strong>extremely</strong> slow. Here is my code:</p> <pre><code>import itertools import string import sys import socket def connection(ip, user, passw, port): s = socket.socket() s.connect((ip, int(port))) data = s.recv(1024) s.send(('USER ' + user + '\r\n').encode()) data = s.recv(1024) s.send(('PASS ' + passw + '\r\n').encode()) data = s.recv(1024) s.send(('quit\r\n').encode()) s.close() return data def crack(ip, user, port): chars = string.digits + string.ascii_letters for password_length in range(1, 9): for guess in itertools.product(chars, repeat = password_length): guess = ''.join(guess) p = connection(ip, user, guess, port) if '230'.encode() in p: print('Username : ' + user + '\nPassword : ' + guess) sys.exit(1) if len(sys.argv) != 4: print('Usage: ./passcracker.py &lt;IP&gt; &lt;Username&gt; &lt;Port&gt;') sys.exit(1) crack(sys.argv[1], sys.argv[2], sys.argv[3]) </code></pre> <p>I want to make it faster. Also if there is any wrong part in code, please tell me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T09:15:48.763", "Id": "408709", "Score": "2", "body": "The slowness is very likely caused primarily by needing to connect to some server, sending data over the network, the server taking some time for the password check (and maybe explicitly slowing down on multiple attempts) etc. All these things are out of control of your program, i.e. caused by infrastructure you don't control. At most you can try to run multiple of such programs in parallel, each with a different sets of passwords to try." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T10:05:46.323", "Id": "408716", "Score": "1", "body": "@Graipher yeah it's a copy-paste error thanks" } ]
[ { "body": "<p>As has been noted in the comments, you should try to figure out what part of the code is slow. Is it the connection to the server or does your program just have to try many passwords and that takes so long?</p>\n\n<hr>\n\n<p>The former can be measured by decorating <code>connection</code> with a decorator that records the time it took to run the function:</p>\n\n<pre><code>import time\nfrom functools import wraps\n\ndef timeit(func):\n func.mean_time = [0]\n func.k = [0]\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.perf_counter()\n ret = func(*args, **kwargs)\n t = time.perf_counter() - start\n\n # update average\n func.k[0] += 1\n func.mean_time[0] += (t - func.mean_time[0]) / func.k[0]\n\n print(f\"{func.__name__} took {t} s (Average: {func.mean_time[0]} s)\")\n return ret\n return wrapper\n</code></pre>\n\n<p>Which you can use like this in general:</p>\n\n<pre><code>@timeit\ndef f():\n time.sleep(0.1)\n\nfor _ in range(10):\n f()\n# f took 0.1002191620063968 s (Average: 0.1002191620063968 s)\n# f took 0.10021526199852815 s (Average: 0.10021721200246247 s)\n# f took 0.10016683799767634 s (Average: 0.10020042066753376 s)\n# f took 0.10014399800274987 s (Average: 0.10018631500133779 s)\n# f took 0.10016678299871273 s (Average: 0.10018240860081278 s)\n# f took 0.10017002299719024 s (Average: 0.10018034433354235 s)\n# f took 0.10020436099875951 s (Average: 0.10018377528571623 s)\n# f took 0.1001491690039984 s (Average: 0.1001794495005015 s)\n# f took 0.10017034399788827 s (Average: 0.10017843777798892 s)\n# f took 0.10020105999865336 s (Average: 0.10018070000005536 s)\n</code></pre>\n\n<p>And here specifically:</p>\n\n<pre><code>@timeit\ndef connect(ip, user, passw, port):\n ...\n</code></pre>\n\n<p>Note that this will slow down the overall execution time a bit (since stuff needs to be done in addition), but you do learn if the connect is the bottleneck (and you can always remove the timing again later).</p>\n\n<hr>\n\n<p>To find out if it is just the number of permutations, I would add some debug prints. I would also factor out the generating of the passwords from trying them further:</p>\n\n<pre><code>def brute_force_n(chars, password_length):\n start = time.perf_counter()\n for i, guess in enumerate(itertools.product(chars, repeat=password_length)):\n yield ''.join(guess)\n print(f\"Tried all {i + 1} permutations of length {password_length}.\")\n print(f\"It took {time.perf_counter() - start} s.\")\n\ndef brute_force(max_length=8):\n chars = string.digits + string.ascii_letters\n for password_length in range(1, max_length + 1):\n yield from brute_force_n(chars, password_length)\n\ndef crack(ip, user, port):\n for guess in brute_force():\n p = connection(ip, user, guess, port)\n if '230'.encode() in p:\n print('Username : ' + user + '\\nPassword : ' + guess)\n sys.exit(1)\n</code></pre>\n\n<p>When testing this you will quickly discover that there are many permutations to try and even when doing nothing with them, this takes quite some time:</p>\n\n<pre><code>for _ in brute_force(5):\n pass # do nothing with it\n\n# Tried all 62 permutations of length 1.\n# It took 3.321799886180088e-05 s.\n# Tried all 3844 permutations of length 2.\n# It took 0.0009744890048750676 s.\n# Tried all 238328 permutations of length 3.\n# It took 0.06495958699815674 s.\n# Tried all 14776336 permutations of length 4.\n# It took 4.06446365499869 s.\n# Tried all 916132832 permutations of length 5.\n# It took 310.80436263100273 s.\n</code></pre>\n\n<p>I stopped at length 5, you want to go to length 8. As you can see in this plot, the time rises very quickly (note the logarithmic y-axis):</p>\n\n<p><a href=\"https://i.stack.imgur.com/94ULk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/94ULk.png\" alt=\"enter image description here\"></a></p>\n\n<p>Extrapolating this to <code>password_length = 8</code>, it would take about 536 days just to generate all combinations of that length.</p>\n\n<hr>\n\n<p>The real solution to this problem is that you need to use some more information/a more clever tactic. A common method is to try words in a dictionary (and then words in a dictionary with numbers at the end, with known common replacements, etc).</p>\n\n<p>Passwords are still used today <em>because</em> it is very hard to guess a (random) password of sufficient length.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T13:18:18.053", "Id": "408721", "Score": "0", "body": "Thanks. But I have a question. Why do you used '@' in some points? Like `@timeit` or `@wraps(func)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T13:37:16.360", "Id": "408722", "Score": "0", "body": "@AkınOktayATALAY: That is the way decorators are used. Have a look e.g. here: https://www.programiz.com/python-programming/decorator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T13:58:58.400", "Id": "408723", "Score": "0", "body": "The decorator doesn't work I get output: `TypeError: 'NoneType' object is not callable`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T14:14:29.100", "Id": "408724", "Score": "0", "body": "@AkınOktayATALAY Are you copying everything? Does it work with the dummy function `f`? In which line does the problem occur? It does work on my machine..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T10:45:34.020", "Id": "211371", "ParentId": "211365", "Score": "3" } } ]
{ "AcceptedAnswerId": "211371", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T07:51:46.447", "Id": "211365", "Score": "1", "Tags": [ "python", "python-3.x", "socket" ], "Title": "Python Making Bruteforce Password Crack Faster" }
211365
<p>My goal is to go through the <a href="https://github.com/dwyl/english-words" rel="nofollow noreferrer">list of all English words</a> (separated by <code>'\n'</code> characters) and find the longest word which doesn't have any of these characters: <code>"gkmqvwxz"</code>. And I want to optimize it as much as possible. Here's what I came up with:</p> <pre><code>#include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stddef.h&gt; #include &lt;unistd.h&gt; static inline int is_legal(size_t beg, size_t end, char* buffer) { static const char* bad = "gkmqvwxzio"; /* unwanted chars */ for (; beg != end; ++beg) { /* go through current word */ char ch = tolower(buffer[beg]); /* The char might be upper case */ for (size_t j = 0; bad[j]; ++j) if (ch == bad[j]) /* If it is found, return false */ return 0; } return 1; /* else return true */ } int main(void) { char *buffer = NULL; /* contents of the text file */ size_t length = 5000000; /* maximum size */ FILE* fp; fp = fopen("words.txt", "rb"); if (fp) { fseek(fp, 0, SEEK_END); fseek(fp, 0, SEEK_SET); buffer = malloc(length); if (buffer) { fread(buffer, 1, length, fp); /* read it all */ } fclose(fp); } size_t beg = 0; /* current word boundaries */ size_t end = 0; size_t mbeg = 0; /* result word */ size_t mend = 0; while (buffer[end]) { beg = end++; for (; buffer[end] &amp;&amp; buffer[end] != '\n'; ++end) /* read the next word */ ; /* for loop doesn't have a body */ if ((end - beg) &gt; (mend - mbeg) &amp;&amp; is_legal(beg, end, buffer)) { /* if it is a fit, save it */ mbeg = beg; mend = end; } } printf("%.*s\n", mend - mbeg, buffer + mbeg); /* print the output */ return 0; } </code></pre> <p>I read it all at once, then go through it with two indexes denoting beginning and ending of current word. When I find a word that fits, I save the corresponding indexes. Finally I print the output, which is <code>"supertranscendentness"</code>. The output is correct, but I'd like to know:</p> <ol> <li>If there's undefined behavior in my code</li> <li>If there's a better way of doing this (without sacrificing performance)</li> <li>If there's a way to improve the performance </li> </ol> <p>Another point is the <code>size_t length = 5000000;</code> part. It is an estimated size of the string based of the file size. </p>
[]
[ { "body": "<p>The code is not bad as it stands, but I think there are some things that could be improved.</p>\n\n<h2>Think of the user</h2>\n\n<p>The input file name and unwanted letters are all hardcoded at the moment. It would be nice if the user could specify one or both of these parameters on the command line.</p>\n\n<h2>Add error handling</h2>\n\n<p>There is almost no error checking or handling. It's not hard to add, and it makes the program much more robust. Here's how the start of <code>main</code> might look:</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n if (argc != 2) {\n puts(\"Usage: longword filename\");\n return 0;\n }\n FILE* fp;\n fp = fopen(argv[1], \"rb\");\n\n if (!fp) {\n perror(\"couldn't open words file\");\n return 3;\n }\n size_t length = 5000000;\n char *buffer = malloc(length);\n if (buffer == NULL) {\n perror(\"couldn't allocate memory\");\n return 2;\n }\n length = fread(buffer, 1, length, fp);\n if (ferror(fp)) {\n perror(\"couldn't read file\");\n free(buffer);\n return 1;\n }\n // rest of program here\n free(buffer);\n}\n</code></pre>\n\n<h2>Consider using standard library functions</h2>\n\n<p>At a very small performance penalty (as measured on my machine), one could write a very clean version using only standard functions:</p>\n\n<pre><code>char *longest = NULL;\nint longestlen = 0;\nchar *word = strtok(buffer, \"\\n\");\nwhile (word) {\n const int len = strlen(word);\n if (len &gt; longestlen) {\n if (strpbrk(word, \"gkmqvwxzio\") == NULL) { \n longestlen = strlen(word);\n longest = word;\n }\n }\n word = strtok(NULL, \"\\n\");\n}\nprintf(\"%s\\n\", longest);\n</code></pre>\n\n<p>That is the way I'd probably write it unless there were some compelling reason that's not fast <em>enough</em>.</p>\n\n<h2>Use functions</h2>\n\n<p>Your <code>is_legal</code> function is not bad, but I'd also write a <code>get_word_len</code> function to fetch the length of the next word in the buffer.</p>\n\n<pre><code>static inline int get_word_len(const char *buff, const char *end) {\n int len = 0;\n for ( ; *buff != '\\n' &amp;&amp; buff &lt; end; ++buff, ++len) \n {}\n return len;\n}\n</code></pre>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>is_legal</code> function doesn't alter the passed string, so that parameter should be <code>const</code>.</p>\n\n<h2>Think carefully about the problem</h2>\n\n<p>The current code might print the word followed by <code>\\n</code>, but if the words doesn't happen to be the first in the file, it will also print the <code>\\n</code> from the previous word. It's not necessarily wrong, but it's not consistent.</p>\n\n<h2>Use <code>bool</code> for boolean values</h2>\n\n<p>The implmentation of <code>bool</code> is in <code>&lt;stdbool.h&gt;</code> and should be used as the return type of <code>is_legal</code>.</p>\n\n<h2>Use only the required headers</h2>\n\n<p>In this program neither <code>&lt;stddef.h&gt;</code> nor <code>&lt;unistd.h&gt;</code> appear to be needed; I'd recommend omitting them and only including headers that are actually needed.</p>\n\n<h2>Consider using pointers</h2>\n\n<p>There may not be a performance difference in this case, but for problems like these, the use of pointers seems more natural to me. For example:</p>\n\n<pre><code>const char *end = buffer + length;\nconst char *longest = buffer;\nint longestlen = 0;\n\nfor (const char *curr=buffer; curr &lt; end; ) {\n const int wordlen = get_word_len(curr, end);\n if (wordlen &gt; longestlen) {\n if (is_good_word(curr, wordlen)) {\n longestlen = wordlen;\n longest = curr;\n }\n }\n curr += wordlen + 1;\n}\nprintf(\"%.*s\\n\", longestlen, longest);\n</code></pre>\n\n<p>Here, <code>is_good_word</code> is like your <code>is_legal</code> function:</p>\n\n<pre><code>static inline bool is_good_word(const char *curr, int wordlen) {\n static const char* bad = \"gkmqvwxzio\";\n for ( ; wordlen; --wordlen) {\n char ch = tolower(*curr++);\n for (const char *badptr = bad; *badptr; ++badptr) {\n if (ch == *badptr) {\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n\n<h2>Don't leak memory</h2>\n\n<p>The program allocates but does not free the buffer space. Yes, the operating system will clean up after you, but a <code>free</code> costs very little and allows for better memory leak checking with tools like <code>valgrind</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T19:20:54.500", "Id": "408741", "Score": "0", "body": "Great points, agreed with most of them. Quick questions:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T19:22:01.380", "Id": "408742", "Score": "0", "body": "**Add error handling**: I would really appreciate a few pointers to sources about error handling in such cases; Best practices, best design patterns" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T19:25:47.633", "Id": "408743", "Score": "0", "body": "**Use only the required headers**: I used `<stddef.h>` for `size_t` and `<unistd.h>` for `fread`. Are these not the correct headers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T19:28:33.953", "Id": "408744", "Score": "1", "body": "I've updated my answer to show error handling examples. Also, `fread` is defined in `<stdio.h>` and since `fread` returns a `size_t`, we know it is already defined once we have `<stdio.h>`. See this: https://en.cppreference.com/w/c/types/size_t" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T16:42:37.183", "Id": "211378", "ParentId": "211366", "Score": "4" } }, { "body": "<p>The <code>fseek()</code> calls in <code>main()</code> achieve nothing. They appear to be relicts of an attempt to measure file size that would look something like this (once the error checking has been added):</p>\n\n<pre><code>FILE *const fp = fopen(\"words.txt\", \"rb\");\nif (!fp) {\n perror(\"fopen\");\n return 1;\n}\n\nif (fseek(fp, 0, SEEK_END)) {\n perror(\"fseek\");\n return 1;\n}\nlong length = ftell(fp);\nif (length &lt; 0) {\n perror(\"ftell\");\n return 1;\n}\nif (fseek(fp, 0, SEEK_SET)) {\n perror(\"fseek\");\n return 1;\n}\n\nchar *const buffer = malloc(length+1);\nif (!buffer) {\n fputs(\"malloc failed\", stderr);\n return 1;\n}\nfread(buffer, 1, length, fp); /* read it all */\nfclose(fp);\nbuffer[length] = '\\0'; /* add a string terminator */\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T11:46:20.313", "Id": "211471", "ParentId": "211366", "Score": "2" } }, { "body": "<p>Your code:</p>\n\n<ol>\n<li><p>You only use things from 3 of the 6 includes. <code>&lt;string.h&gt;</code>, <code>&lt;stddef.h&gt;</code>, and <code>&lt;unistd.h&gt;</code> are superfluous, the last one just limiting portability.</p></li>\n<li><p><code>is_legal()</code> does not need to know about the bigger buffer. Just the sequence it should inspect is sufficient.</p></li>\n<li><p>You assume everything works out perfectly fine:</p>\n\n<ul>\n<li>The file can be opened for reading.</li>\n<li>You succeed in allocating 5_000_000 bytes.</li>\n<li>You can read all those Bytes from the file.</li>\n</ul></li>\n<li><p>You fail to free the array you <code>malloc()</code>-ed. Not really a problem though, as the program terminates immediately afterwards.</p></li>\n<li><p>If you allocate a fixed amount of memory on <em>every</em> run, why not just make it a static array?</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code> since C99.</p></li>\n</ol>\n\n<p>Design limitations and considerations:</p>\n\n<ol>\n<li><p>Consider using a smaller fixed buffer (size should be a power of 2, at least 32k or so), and scanning the file from start to end, instead of slurping it all in.</p></li>\n<li><p>Consider allowing the user to override which characters are forbidden.</p></li>\n<li><p>You are only handling single-byte character-sets. That might be enough, and it certainly simplifies things significantly.</p></li>\n<li><p>Your code is almost certainly IO-bound, so the gains from optimising the algorithm are probably strictly limited. Still, consider a bit of pre-processing to cut out the more expensive calls.</p>\n\n<p>Specifically, prepare two bitfields <code>character</code> and <code>whitespace</code>, and use a simple lookup.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:08:09.480", "Id": "408938", "Score": "0", "body": "Great points, thank you. A couple of quick questions:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:09:51.940", "Id": "408939", "Score": "0", "body": "Wouldn't fixing the size to 32k and reading into it in a loop mean I have to copy the \"longest legal word\" candidate every time there's one? Sounds inefficient, how would I go about fixing that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:11:00.127", "Id": "408940", "Score": "0", "body": "How could I consider supporting longer than single-byte character-sets?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:12:24.813", "Id": "408941", "Score": "0", "body": "Wouldn't an array of size 5,000,000 cause stackoverflow if I were to make it static?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T20:48:14.670", "Id": "408975", "Score": "0", "body": "@Ayxan You could have two dynamic buffers, for the longest yet, respectively the current prospect. And that's just in case the longest word is unexpectedly long. If you want to support more than single-Byte character-sets, things get complicated, just take a peek into unicode as an example. And variables with static lifetime don't have anything to do with the stack, they aren't automatic." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T12:34:04.480", "Id": "211474", "ParentId": "211366", "Score": "3" } } ]
{ "AcceptedAnswerId": "211378", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T09:36:16.100", "Id": "211366", "Score": "6", "Tags": [ "performance", "c" ], "Title": "Finding the longest word without these characters" }
211366
<blockquote> <p><strong>Problem</strong></p> <p>Given a Dictionary with <code>user_id</code> and a list of <code>alert_words</code> (words and phrases too look for in an sentence) and a string <code>content</code>. We have to look if the <code>alert_words</code> appears in the <code>content</code> and return the list of <code>user_ids</code> who's <code>alert_words</code> appears in the <code>content</code></p> <p><strong>Example</strong></p> <p>input = { 1 : ['how are you'], 2 : ['you are'] }</p> <p>content = 'hello, how are you'</p> <p>output = [1]</p> <p><code>user_id</code> = 1 has 'how are you' while <code>user_id</code> = 2 has the words but not in the correct order so only user 1 is returned.</p> </blockquote> <p><strong>Solution</strong> </p> <p>I'm using <a href="https://github.com/google/pygtrie" rel="nofollow noreferrer">Google's pygtrie</a> implementation of <code>Trie</code> data structure to achieve this. [<a href="https://pygtrie.readthedocs.io/en/latest/" rel="nofollow noreferrer">pygtrie documentation</a>]</p> <p>Algorithm:</p> <ul> <li>For each word in the given sentence </li> <li>Check if the word is a key, if yes add it to the list of user_ids</li> <li>check if the word has a subtrie i.e. that current word is the starting of a alert_word. So add it to another set <code>alert_phrases</code></li> <li>for each word in <code>alert_phrases</code> we check if we can extent with the current word and do the same set of operations if it is a key/subtrie </li> </ul> <p><strong>Code</strong></p> <pre><code>import pygtrie from typing import Dict, List, Set def build_trie(realm_alert_words : Dict[int, List[int]]) -&gt; pygtrie.StringTrie: trie = pygtrie.StringTrie() for user_id, words in realm_alert_words.items(): for word in words: alert_word = trie._separator.join(word.split()) if trie.has_key(alert_word): user_ids_for_word = trie.get(alert_word) user_ids_for_word.update([user_id]) else: trie[alert_word] = set([user_id]) return trie def get_user_ids_with_alert_words(trie : pygtrie.StringTrie, content : str) -&gt; Set[int]: """Returns the list of user_id's who have alert_words present in content""" content_words = content.split() alert_phrases = set() user_ids_in_messages = set() for possible_alert_word in content_words: #has_node returns 1(HAS_VALUE) if the exact key is found, 2(HAS_SUBTRIE) if the key is a sub trie, # 3 if it's both 0 if it's none #https://pygtrie.readthedocs.io/en/latest/#pygtrie.Trie.has_node alert_word_in_trie = trie.has_node(possible_alert_word) if alert_word_in_trie &amp; pygtrie.Trie.HAS_VALUE: user_ids = trie.get(possible_alert_word) user_ids_in_messages.update(user_ids) deep_copy_alert_phrases = set(alert_phrases) # Check if extending the phrases with the current word in content is a subtrie or key. And # Remove the word if it is not a subtrie as we are interested only in continuos words in the content for alert_phrase in deep_copy_alert_phrases: alert_phrases.remove(alert_phrase) extended_alert_phrase = alert_phrase + trie._separator + possible_alert_word alert_phrase_in_trie = trie.has_node(extended_alert_phrase) if alert_phrase_in_trie &amp; pygtrie.Trie.HAS_VALUE: user_ids = trie.get(extended_alert_phrase) user_ids_in_messages.update(user_ids) if alert_phrase_in_trie &amp; pygtrie.Trie.HAS_SUBTRIE: alert_phrases.add(extended_alert_phrase) if alert_word_in_trie &amp; pygtrie.Trie.HAS_SUBTRIE: alert_phrases.add(possible_alert_word) return user_ids_in_messages </code></pre> <p><strong>Tests</strong></p> <pre><code>input = {1 : ['hello'], 7 : ['this possible'], 2 : ['hello'], 3 : ['hello'], 5 : ['how are you'], 6 : ['hey']} alert_word_trie = build_trie(input) content = 'hello how is this possible how are you doing today' result = get_user_ids_with_alert_words(alert_word_trie, content) assert(result == set([1, 2, 3, 5, 7])) input = {1 : ['provisioning', 'Prod deployment'], 2 : ['test', 'Prod'], 3 : ['prod'], 4 : ['deployment'] } alert_word_trie = build_trie(input) content = 'Hello, everyone. Prod deployment has been completed' result = get_user_ids_with_alert_words(alert_word_trie, content) assert(result == set([1, 2, 4])) input = {1 : ['provisioning/log.txt'] } alert_word_trie = build_trie(input) content = 'Hello, everyone. Errors logged at provisioning/log.txt ' result = get_user_ids_with_alert_words(alert_word_trie, content) assert(result == set([1])) </code></pre> <p>The two methods are part of a larger classes which have some not so related code. You get a list of <code>user_id</code>s and their <code>alert_words</code> from the database and you process every message <code>content</code> based on the trie already build up.</p> <p>This is for a chat application so frequency of running the <code>get_user_id_with_alert_words</code> is high when the <code>build_trie</code> is relatively less since it will be cached.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T22:16:55.400", "Id": "408751", "Score": "0", "body": "If `content` is `Hello, how [some words] are [more words] you`, what the result should be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T05:23:29.773", "Id": "408778", "Score": "0", "body": "@Carcigenicate you solution iterates the entire alert_words which grows in size as users increase. Also i don't think the `in` a list is of linear time complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T09:13:29.733", "Id": "408785", "Score": "1", "body": "@thebenman: `in` is O(n) for lists (and strings): https://wiki.python.org/moin/TimeComplexity" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T09:14:24.840", "Id": "408786", "Score": "0", "body": "Since the time complexity is important to you, what do you think is the time complexity of using Tries?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T11:56:58.327", "Id": "408796", "Score": "1", "body": "@Graipher Finding a word in a trie is `O(m)` where `m` is the length of the word and finding it in a list would be `O(n)` where `n` is the total number of elements in the list which can grow as opposed to the number of words in the message." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T15:52:19.940", "Id": "408805", "Score": "0", "body": "@vnp this solution expects that the exact word be found in the sentence without any trailing or preceding characters." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T10:06:39.127", "Id": "211370", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "trie" ], "Title": "Looking for words from a list of words in a sentence" }
211370
<p>I am using this code to forward my syslog logs (converted to json using <code>syslog-ng</code>) to Azure Log Analytics on an ARM board (since there is no official client for ARM). It uses the <a href="https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-data-collector-api" rel="nofollow noreferrer">HTTP Data Collector API</a> to submit the logs.</p> <p>The idea is to read logs from stdin (each line is a JSON object) in separate thread with a buffer and send them when tokio worker thread is ready or the buffer gets full (body can't be more 30MB).</p> <p>My questions:</p> <ul> <li>Is my usage of async Rust correct?</li> <li>Is there a way to improve performance?</li> </ul> <h3>src/main.rs</h3> <pre class="lang-rust prettyprint-override"><code>use futures::sync::mpsc::channel; use futures::{Future, Stream}; use hyper::client::HttpConnector; use hyper_tls::HttpsConnector; use native_tls::{Protocol, TlsConnector}; use std::io::BufRead; use std::{io, thread}; const AZURE_REQUEST_LIMIT: usize = 30 * 1000 * 1000; // 30 MB const LINE_LENGTH_LIMIT: usize = AZURE_REQUEST_LIMIT - 2; // should fit in '[' + &lt;30 mb of json&gt; + ']' fn aggregated_logs() -&gt; impl Stream&lt;Item = String, Error = ()&gt; { let (mut tx, rx) = channel(0); thread::spawn(move || { let input = io::stdin(); let mut lock = input.lock(); let mut buf = String::new(); loop { let empty = buf.is_empty(); let c = if empty { '[' } else { ',' }; buf.push(c); let mut read_bytes = lock.read_line(&amp;mut buf).expect("failed to read line"); if read_bytes == 0 &amp;&amp; empty { break; } // remove newline read_bytes -= 1; buf.pop(); assert!( read_bytes &lt;= LINE_LENGTH_LIMIT, "line is too long: {} bytes", read_bytes ); let under_limit = buf.len() &lt;= AZURE_REQUEST_LIMIT - 1; let mut msg = if under_limit { // send the entire buffer std::mem::replace(&amp;mut buf, String::new()) } else { // buffer got too big, save next line for next iteration let prev_len = buf.len() - read_bytes; let mut msg = String::from("["); msg.push_str(&amp;buf[prev_len..]); buf.truncate(prev_len); std::mem::replace(&amp;mut buf, msg) }; msg.push(']'); while let Err(e) = tx.try_send(msg) { debug_assert!(e.is_full()); msg = e.into_inner(); if under_limit { buf = msg; buf.pop(); // remove ']' break; } } } }); rx } const RESOURCE: &amp;'static str = "/api/logs"; const CONTENT_TYPE: &amp;'static str = "application/json"; const X_MS_DATE: &amp;'static str = "x-ms-date"; type HmacSha256 = hmac::Hmac&lt;sha2::Sha256&gt;; use hmac::Mac; fn signature(rfc1123date: &amp;str, len: usize, customer_id: &amp;str, mut hmac: HmacSha256) -&gt; String { let string_to_hash = format!( "POST\n{}\n{}\n{}:{}\n{}", len, CONTENT_TYPE, X_MS_DATE, rfc1123date, RESOURCE ); hmac.input(string_to_hash.as_bytes()); let result = hmac.result(); let base64 = base64::encode(&amp;result.code()); format!("SharedKey {}:{}", customer_id, base64) } fn main() { let customer_id = std::env::var("CUSTOMER_ID").expect("Missing CUSTOMER_ID"); let shared_key = std::env::var("SHARED_KEY").expect("Missing SHARED_KEY"); let log_type = std::env::var("LOG_TYPE").expect("Missing LOG_TYPE"); let time_generated = std::env::var("TIME_GENERATED_FIELD"); let decoded_key = base64::decode(&amp;shared_key).unwrap(); let hmac = HmacSha256::new_varkey(&amp;decoded_key).unwrap(); let mut http = HttpConnector::new(num_cpus::get()); http.enforce_http(false); let connector = TlsConnector::builder() .min_protocol_version(Some(Protocol::Tlsv12)) .build() .unwrap(); let mut https: HttpsConnector&lt;_&gt; = (http, connector).into(); https.https_only(true); let client = hyper::Client::builder().build::&lt;_, hyper::Body&gt;(https); let uri = format!( "https://{}.ods.opinsights.azure.com{}?api-version=2016-04-01", customer_id, RESOURCE ); tokio::run( aggregated_logs() .then(move |data| { let data = data.unwrap(); let rfc1123date = chrono::Utc::now() .format("%a, %d %b %Y %H:%M:%S GMT") .to_string(); let len = data.len(); let signature = signature(&amp;rfc1123date, len, &amp;customer_id, hmac.clone()); let body: hyper::Body = data.into(); let mut builder = hyper::Request::post(&amp;uri); builder .header("Content-Type", CONTENT_TYPE) .header("Content-Length", len) .header("Authorization", signature) .header("Log-Type", log_type.as_str()) .header(X_MS_DATE, rfc1123date); if let Ok(time_generated) = &amp;time_generated { builder.header("time-generated-field", time_generated.as_str()); } let request = builder.body(body).unwrap(); client.request(request).and_then( |response| -&gt; Box&lt;dyn Future&lt;Item = (), Error = hyper::Error&gt; + Send&gt; { let status = response.status(); if status.is_success() { Box::new(futures::finished(())) } else { Box::new(response.into_body().concat2().and_then(move |chunk| { let message = String::from_utf8(chunk.to_vec()).unwrap(); eprintln!("{} {}", status, message); Ok(()) })) } }, ) }) .for_each(|_| Ok(())) .then(|e| { e.unwrap(); Ok(()) }), ) } </code></pre> <h3>Cargo.toml:</h3> <pre><code>[package] name = "log_analytics" version = "0.1.0" edition = "2018" [dependencies] tokio = "0.1.13" hyper = "0.12.19" futures = "0.1.25" hmac = "0.7.0" sha2 = "0.8.0" hyper-tls = "0.3.1" chrono = "0.4.6" base64 = "0.10.0" native-tls = "0.2.2" num_cpus = "1.9.0" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T09:30:06.583", "Id": "408879", "Score": "1", "body": "`let under_limit = buf.len() <= AZURE_REQUEST_LIMIT - 1;` is either an error or over complication for `let under_limit = buf.len() < AZURE_REQUEST_LIMIT;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-11T06:39:42.977", "Id": "488391", "Score": "0", "body": "Your code sample helped me with TimeGenerated issue. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T11:24:55.570", "Id": "211372", "Score": "1", "Tags": [ "multithreading", "asynchronous", "http", "rust" ], "Title": "A syslog to Azure Log Analytics forwarder" }
211372
<p>A year ago, I implemented an evaluation algorithm for <a href="https://en.wikipedia.org/wiki/Conway_chained_arrow_notation" rel="nofollow noreferrer">Conway's chained arrow notation</a> in Python. I'd like to get a review on my code, especially about readability and if it is pythonic. I'd also like to know if there is a bug. I'm not too much concerned about performance since this notation runs faster into unsolvable memory problems than it runs into long loops. For example, <code>resolve('3-&gt;3-&gt;2-&gt;2')</code> would have to build a list with 7.6 trillion strings if it didn't raise a <code>MemoryError</code> manually before.</p> <pre><code># coding: utf-8 MAX_BYTES = 1 &lt;&lt; 30 def do_brackets_match(chain): open_brackets = 0 for c in chain: if c == '(': open_brackets += 1 if c == ')': open_brackets -= 1 if open_brackets &lt; 0: return False return open_brackets == 0 def split_by_inner_bracket(chain): start, part3 = chain.partition(')')[::2] start, middle = start.rpartition('(')[::2] return [start, middle, part3] def is_arrow_chain(chain): return '-&gt;' in chain def resolve_pure(chain): assert '(' not in chain and ')' not in chain # remove whitespace chain = chain.replace(' ', '') chain = chain.replace('\t', '') # get values str_values = chain.split('-&gt;') # handle short chains length = len(str_values) if length == 1: return str_values[0] b = int(str_values[-2]) n = int(str_values[-1]) if length == 2: if n.bit_length() &gt; 1024 or b.bit_length() * 8 * n &gt; MAX_BYTES: raise MemoryError return str(b ** n) if b &gt; MAX_BYTES: raise MemoryError # remove everything after a 1 for i, s in enumerate(str_values): if str_values[i] == '1': str_values = str_values[:i] break # construct the next iteration step leading_chain = '-&gt;'.join(str_values[:-2]) resolved_chain = '-&gt;('.join([leading_chain] * b) resolved_chain += (')-&gt;' + str(n-1)) * (b-1) resolved_chain = resolved_chain.replace('-&gt;1)', ')') if resolved_chain.endswith('-&gt;1'): resolved_chain = resolved_chain[:-3] return resolved_chain def resolve(chain, show_progress=False, depth=0): while is_arrow_chain(chain): if show_progress: print(' ' * depth + chain) if '(' in chain or ')' in chain: part = split_by_inner_bracket(chain) if is_arrow_chain(part[1]): part[1] = resolve(part[1], show_progress, depth+1) chain = ''.join(part) else: chain = resolve_pure(chain) return chain def main(): print(resolve('2-&gt;3-&gt;3', True)) print('----------------') print(resolve('2-&gt;2-&gt;3-&gt;3', True)) print('----------------') print(resolve('3-&gt;2-&gt;3', True)) if __name__ == '__main__': main() </code></pre> <p>Output:</p> <pre><code>2-&gt;3-&gt;3 2-&gt;(2-&gt;(2)-&gt;2)-&gt;2 2-&gt;(2-&gt;2-&gt;2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 2-&gt;4-&gt;2 2-&gt;(2-&gt;(2-&gt;(2))) 2-&gt;(2-&gt;(2-&gt;2)) 2-&gt;2 2-&gt;(2-&gt;4) 2-&gt;4 2-&gt;16 65536 ---------------- 2-&gt;2-&gt;3-&gt;3 2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2)-&gt;2)-&gt;2 2-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;4-&gt;2)-&gt;2 2-&gt;2-&gt;4-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2))) 2-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2-&gt;4)) 2-&gt;2-&gt;4 2-&gt;(2)-&gt;3 2-&gt;2-&gt;3 2-&gt;(2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;4) 2-&gt;2-&gt;4 2-&gt;(2)-&gt;3 2-&gt;2-&gt;3 2-&gt;(2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 2-&gt;2-&gt;4 2-&gt;(2)-&gt;3 2-&gt;2-&gt;3 2-&gt;(2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 2-&gt;2-&gt;4-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2))) 2-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;(2-&gt;2-&gt;4)) 2-&gt;2-&gt;4 2-&gt;(2)-&gt;3 2-&gt;2-&gt;3 2-&gt;(2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 2-&gt;2-&gt;(2-&gt;2-&gt;4) 2-&gt;2-&gt;4 2-&gt;(2)-&gt;3 2-&gt;2-&gt;3 2-&gt;(2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 2-&gt;2-&gt;4 2-&gt;(2)-&gt;3 2-&gt;2-&gt;3 2-&gt;(2)-&gt;2 2-&gt;2-&gt;2 2-&gt;(2) 2-&gt;2 4 ---------------- 3-&gt;2-&gt;3 3-&gt;(3)-&gt;2 3-&gt;3-&gt;2 3-&gt;(3-&gt;(3)) 3-&gt;(3-&gt;3) 3-&gt;3 3-&gt;27 7625597484987 </code></pre>
[]
[ { "body": "<p>After looking at the code again I was able to discover some issues.</p>\n\n<blockquote>\n <p><code>def do_brackets_match(chain):</code></p>\n</blockquote>\n\n<p>Actually a nice function to check if the input is a valid chain notation ... I was really surprised when I didn't find any call to it. <code>resolve_pure()</code> doesn't accept chains with parenthesis, so <code>do_brackets_match()</code> would be used in <code>resolve()</code></p>\n\n<blockquote>\n <p><code>def split_by_inner_brackets(chain):</code></p>\n</blockquote>\n\n<p>It looks a bit ugly to slice the result of <code>str.partition()</code> in order to discard the separator. Today I would prefer <code>str.split()</code> with <code>maxsplit=1</code>.</p>\n\n<blockquote>\n <p><code>def resolve_pure(chain)</code></p>\n</blockquote>\n\n<p>First of all, I consider renaming this function to <code>expand_chain</code> or similar. I would also rename the variable <code>resolved_chain</code> to <code>expanded_chain</code> in that case.\nSecondly, this loop is a bit confusing:</p>\n\n<pre><code>for i, s in enumerate(str_values):\n if str_values[i] == '1':\n</code></pre>\n\n<p>I should definitly rewrite the second line to <code>if s == '1'</code>. I mean, that's the whole point of using <code>enumerate()</code>, isn't it?</p>\n\n<p>As you might have noticed from the examples, a chain which starts with <code>'2-&gt;2-&gt;'</code> always results in <code>'4'</code>. I could handle that special case.</p>\n\n<blockquote>\n <p><code>def resolve(chain, show_progress=False, depth=0):</code></p>\n</blockquote>\n\n<p>As mentioned before, this function should call <code>do_brackets_match()</code>, probably right at the start. If it fails, it should raise an exception or at least print a message and return <code>''</code>. When evaluating the inner bracket, it might be useful to call <code>eval</code> in order to evaluate common arithmetic expressions like <code>(2*5+3)</code>.</p>\n\n<p>Neither <code>resolve_pure()</code> nor <code>resolve</code> check for negative values which should be avoided as they can cause an error</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:31:46.900", "Id": "212293", "ParentId": "211376", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T15:51:16.507", "Id": "211376", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "reinventing-the-wheel", "math-expression-eval" ], "Title": "Python implementation of Conway's chained arrow notation" }
211376
<p>This is my Singly Linked List implementation in ES6.</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>class LinkedList{ constructor(){ this.head = null; this.size = 0; } insert(item){ this.size ++; let p = new Node(item); if(this.head === null){ this.head = p; } else{ p.next = this.head; this.head = p; } } insertAt(item, index){ if(index &gt; this.size){ throw "Wrong index"; } let p = new Node(item); if(index === 0){ p.next = this.head; this.head = p; return; } let curr = this.head; while(curr !== null){ if(index === 0){ if(curr.next === null){ curr.next = p; return; } else if(curr.next.next === null){ curr.next = p; }else{ curr.next.next = p.next; curr.next = p; } return; } curr = curr.next; index --; } } remove(item){ let curr, prev; prev = curr = this.head; if(item === curr.val){ this.head = this.head.next; this.size --; return; } while(curr !== null){ if (curr.val === item){ prev.next = curr.next; this.size --; return; } prev = curr; curr = curr.next; } throw "Item doesn't exist in list." } length(){ return this.size; } is_empty(){ return this.size === 0; } printList(){ let curr = this.head; let out = []; while(curr !== null){ if(curr.next === null){ out.push(curr.val); }else{ out.push(curr.val); out.push("-&gt;") } curr = curr.next; } return out.join(""); } } class Node{ constructor(val){ this.val = val; this.next = null; } } const list = new LinkedList(); list.insert(12); list.insert(9); list.insert(13); list.insert(17); console.log(list.printList()); list.remove(12); console.log(list.printList()); console.log(list.length()); console.log(list.is_empty()); list.insertAt(21, 2); console.log(list.printList());</code></pre> </div> </div> </p> <p>Invite reviews please on all fronts, improvements, modern usage of JS. Thanks.</p>
[]
[ { "body": "<h1>TL;DR</h1>\n\n<ul>\n<li>Style could better adhere to established standards.</li>\n<li><code>insertAt</code> has bugs to resolve.</li>\n<li>This class is missing basic add/remove functions which prevent it from being useful.</li>\n<li>Writing a linked list class in JS only makes sense from an educational standpoint; primitive arrays are efficient, universal and offer more functionality with less code.</li>\n</ul>\n\n<hr>\n\n<h1>Style</h1>\n\n<h3>Spacing</h3>\n\n<ul>\n<li><p>Use a space between <code>)</code>s, <code>{</code>s and keywords, e.g. </p>\n\n<pre><code>if(this.head === null){ \n</code></pre>\n\n<p>is cleaner as </p>\n\n<pre><code>if (this.head === null) {\n</code></pre></li>\n<li><p>Add vertical spacing between lines to group logical code blocks together and separate loop, conditional and function logic from declarations. For example,</p>\n\n<pre><code>let curr = this.head;\nwhile(curr !== null){\n</code></pre>\n\n<p>is easier to read as </p>\n\n<pre><code>let curr = this.head;\n\nwhile (curr !== null) {\n</code></pre></li>\n<li><p><code>this.size ++</code> is clearer as <code>this.size++</code>.</p></li>\n<li><p>Be consistent--sometimes you use <code>}else{</code>, and sometimes you use </p>\n\n<pre><code>}\nelse{\n</code></pre></li>\n<li><p>Your whitespace fixes can be done by putting the code into SE's Code Snippet and pressing \"Tidy\", then adding blank lines around blocks by hand. Generally, I don't see reason to deviate from this prescribed style.</p></li>\n</ul>\n\n<h3>Variable and function naming</h3>\n\n<ul>\n<li>Function names switch between <code>snake_case</code> and <code>camelCase</code>. All JS naming should be <code>camelCase</code>, except class names, which are <code>UpperCamelCase</code> (as you use).</li>\n<li>Avoid single-letter variable names like <code>p</code> unless the meaning is obvious. In this case, something like <code>newNode</code> might be clearer.</li>\n</ul>\n\n<hr>\n\n<h1>Functionality</h1>\n\n<h3>Errors</h3>\n\n<ul>\n<li><code>throw \"Wrong index\";</code> is an unclear error message. What exactly is wrong with the index? Consider <code>throw \"Index out of list bounds\";</code> which more accurately describes the problem. </li>\n<li><p>You may wish to reconsider using errors at all. I find throwing errors in JS generally less appropriate than return values because the calling code can stick to normal conditionals to handle control flow. </p>\n\n<p>Also, not throwing errors is in keeping with JS's builtin library functions, which generally don't complain about invalid or missing input. For <code>insertAt</code>, for example, you could return <code>true</code> if the insertion was successful and <code>false</code> otherwise. If the user provides something silly as an index that causes a crash, they'll get an appropriate stack trace that likely explains the problem better than a hand-written error string.</p>\n\n<p>If you do wish to stick with error throwing, ensure it is comprehensive. For example, <code>if (index &gt; this.size)</code> doesn't handle the case when <code>index &lt; 0</code> which could result in difficult-to-track-down bugs for the client who has to make design assumptions based on your throw.</p>\n\n<p>Then, once you've covered that scenario, it begs the question whether you should now validate that the provided input is an integer number and throw an error message for that as well. </p>\n\n<p>The point is, adding errors gives the client the illusion of a comprehensive and robust set of argument and function state restrictions, which is problematic if they aren't actually robust. Throwing no errors, assuming the client is behaving, and reporting <code>true</code>/<code>false</code> as to whether some function failed or not seems preferential.</p></li>\n</ul>\n\n<h3>Variable keywords</h3>\n\n<ul>\n<li>Use <code>const</code> when appropriate in place of <code>let</code>. This should apply to almost everything except for loop counters, accumulator variables and runner nodes. For example, <code>let out = [];</code> should be <code>const out = [];</code>. Even if the risk of bugs caused by accidental reassignment is low, this has semantic benefits.</li>\n</ul>\n\n<h3>Misleading function names</h3>\n\n<ul>\n<li><code>printList()</code> is a misleading name; it stringifies the list rather than printing. I recommend overriding <code>toString()</code> here.</li>\n<li><code>insert()</code> usually refers to insertion at some specific element, which is the behavior your <code>insertAt()</code> function offers. With <code>insert()</code>, It's not obvious <em>where</em> the insertion is happening; one of <code>addFront</code>, <code>unshift</code> or <code>push</code> seem clearer, depending on which end of your list you decide the front to be. </li>\n</ul>\n\n<h3>Internal logic</h3>\n\n<ul>\n<li><code>insertAt</code> is not working correctly, placing items incorrectly, not at all, and neglecting to increment the size.</li>\n<li>Consider adjusting your <code>insertAt</code> code to avoid using <code>return</code>s and <code>curr.next.next</code>, which is difficult to reason about and causing bugs.</li>\n<li>In <code>printList</code>, pains are taken to conditionally add the <code>-&gt;</code> arrow only for non-last elements when you can simply walk the list and use <code>out.join(\"-&gt;\")</code>.</li>\n<li>Since your internal code relies only on <code>Node</code> objects, you can make your code cleaner by testing <code>while (curr)</code> instead of <code>while (curr === null)</code>. This is debatable, because it restricts your internal logic from distinguishing between <code>null</code> and <code>undefined</code> or other falsey values, but if you trust yourself to be consistent about it, I prefer the cleaner look.</li>\n</ul>\n\n<h3>Interface</h3>\n\n<ul>\n<li><p>As written, I find your provided function interface insufficient for typical linked list needs. It's not obvious what functionality this class offers over, say, a primitive array.</p>\n\n<p>Consider <code>remove(item)</code>. This sort of function that takes an element and searches the structure for it is best used for hashes with random access. The whole point of linked lists is to offer fast insertion and removal of front and back elements, regardless of what those elements might be. Anything in the middle is of no concern, and libraries that offer access to these elements, such as Java's <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html\" rel=\"nofollow noreferrer\">LinkedList</a> collection are generally considered to be flawed because clients may make false assumptions about the time complexity of provided operations.</p>\n\n<p>Without constant time <code>front</code> and <code>back</code> adds, removals and peeks, I can't foresee a reason to use this class instead of a primitive array. <code>insert</code> is the only useful linked list function your interface offers (disregarding <code>isEmpty</code>, <code>printList</code>, etc as useful but trivial).</p></li>\n</ul>\n\n<hr>\n\n<h1>Rewrites</h1>\n\n<h3>Revision #1 (same functionality)</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class LinkedList {\n constructor() {\n this.head;\n this.size = 0;\n }\n\n addFront(value) {\n const newNode = new Node(value);\n \n if (this.head) {\n newNode.next = this.head;\n } \n \n this.head = newNode;\n this.size++;\n }\n \n insertAt(value, idx) {\n let curr = this.head;\n let prev;\n \n while (curr &amp;&amp; idx &gt; 0) {\n prev = curr;\n curr = curr.next;\n idx--;\n }\n \n if (prev) {\n prev.next = new Node(value);\n prev.next.next = curr;\n this.size++;\n }\n else {\n this.addFront(value);\n } \n }\n \n remove(value) {\n let curr = this.head;\n let prev;\n \n while (curr) {\n if (curr.val === value) {\n if (prev) {\n prev.next = curr.next;\n }\n else {\n this.head = undefined;\n }\n \n this.size--;\n return true;\n }\n \n prev = curr;\n curr = curr.next;\n }\n \n return false;\n }\n \n length() {\n return this.size;\n }\n\n empty() {\n return !this.size;\n }\n \n toString() {\n const result = [];\n let curr = this.head;\n\n while (curr) {\n result.push(curr.val);\n curr = curr.next;\n }\n \n return result.join(\"-&gt;\");\n }\n}\n\nclass Node {\n constructor(val, nextNode=null) {\n this.val = val;\n this.next = nextNode;\n }\n}\n\nconst list = new LinkedList();\nlist.remove(1123);\nlist.insertAt(21, 33);\nlist.remove(21);\nlist.addFront(12);\nlist.addFront(9);\nlist.addFront(13);\nlist.addFront(17);\nlist.remove(1123);\nconsole.log(list.toString());\nlist.remove(12);\nconsole.log(list.toString());\nconsole.log(list.length(), list.empty());\nlist.insertAt(21, 2);\nconsole.log(list.toString(), list.length());\nlist.insertAt(11, 0);\nconsole.log(list.toString(), list.length());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Revision #2 (added front/back operations)</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class LinkedList {\n constructor() {\n this.head;\n this.tail;\n }\n\n addFront(value) {\n const newHead = new Node(value);\n \n if (this.head) {\n newHead.next = this.head;\n } \n else {\n this.tail = newHead;\n }\n \n this.head = newHead;\n }\n \n addBack(value) {\n if (this.tail) {\n this.tail.next = new Node(value);\n this.tail = this.tail.next;\n }\n else {\n this.head = this.tail = new Node(value);\n }\n }\n \n peekFront() {\n return this.head ? this.head.val : null;\n }\n \n peekBack() {\n return this.tail ? this.tail.val : null;\n }\n \n popFront() {\n if (this.head) {\n const value = this.head.val;\n this.head = this.head.next;\n \n if (!this.head) {\n this.tail = null;\n }\n \n return value;\n }\n }\n \n empty() {\n return !this.head;\n }\n \n toString() {\n const result = [];\n let curr = this.head;\n\n while (curr) {\n result.push(curr.val);\n curr = curr.next;\n }\n \n return result.join(\"-&gt;\");\n }\n}\n\nclass Node {\n constructor(val, nextNode=null) {\n this.val = val;\n this.next = nextNode;\n }\n}\n\nconst list = new LinkedList();\nlist.popFront();\nconsole.log(list.toString(), list.empty());\nlist.addBack(1);\nconsole.log(list.toString(), list.empty());\nlist.popFront();\nconsole.log(list.toString(), list.empty());\nlist.addFront(2);\nconsole.log(list.toString());\nlist.addBack(3);\nconsole.log(list.toString());\nlist.popFront();\nconsole.log(list.toString());\nlist.addFront(4);\nlist.addBack(5);\nconsole.log(list.toString());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Note that there is no <code>popBack()</code> because this operation would be linear without doubly linked nodes. However, the class is sufficient to support both stacks and queues with all operations in constant time. Without the <code>tail</code> pointer, only a stack could be supported. Adding <code>popBack()</code> and double links would give you a <a href=\"https://en.wikipedia.org/wiki/Double-ended_queue\" rel=\"nofollow noreferrer\">deque</a> class.</p>\n\n<h3>Revision #3 (supported a queue)</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Queue {\n constructor() {\n this.list = new LinkedList();\n }\n \n offer(value) {\n this.list.addBack(value);\n }\n \n poll() {\n return this.list.popFront();\n }\n \n peek() {\n return this.list.peekFront();\n }\n \n empty() {\n return this.list.empty();\n }\n \n toString() {\n return this.list.toString();\n }\n}\n\nclass LinkedList {\n constructor() {\n this.head;\n this.tail;\n }\n\n addFront(value) {\n const newHead = new Node(value);\n \n if (this.head) {\n newHead.next = this.head;\n } \n else {\n this.tail = newHead;\n }\n \n this.head = newHead;\n }\n \n addBack(value) {\n if (this.tail) {\n this.tail.next = new Node(value);\n this.tail = this.tail.next;\n }\n else {\n this.head = this.tail = new Node(value);\n }\n }\n \n peekFront() {\n return this.head ? this.head.val : null;\n }\n \n peekBack() {\n return this.tail ? this.tail.val : null;\n }\n \n popFront() {\n if (this.head) {\n const value = this.head.val;\n this.head = this.head.next;\n \n if (!this.head) {\n this.tail = null;\n }\n \n return value;\n }\n }\n \n empty() {\n return !this.head;\n }\n \n toString() {\n const result = [];\n let curr = this.head;\n\n while (curr) {\n result.push(curr.val);\n curr = curr.next;\n }\n \n return result.join(\"-&gt;\");\n }\n}\n\nclass Node {\n constructor(val, nextNode=null) {\n this.val = val;\n this.next = nextNode;\n }\n}\n\nconst q = new Queue();\nq.offer(1);\nconsole.log(q.poll());\nconsole.log(q.poll());\n\nfor (let i = 0; i &lt; 5; i++) {\n q.offer(i);\n}\n\nwhile (!q.empty()) {\n console.log(q.poll());\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>After all that work, a <a href=\"https://jsperf.com/linkedlist-vs-primitive-array\" rel=\"nofollow noreferrer\">benchmark</a> shows that it's no faster than a primitive array. This is likely due to overhead from object creation, function calls and garbage collection, which counteracts the shifting necessary on the primitive array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T00:29:09.487", "Id": "408847", "Score": "1", "body": "A delight to read! Dear OP, Look into iterators. That would enable `forEach` coding. Also Blindman76 warning of lack of private variables in `class` is notable. You really want to protect clients from themselves and make sure the linkedList can be used only as intended." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T20:56:24.807", "Id": "211390", "ParentId": "211380", "Score": "4" } }, { "body": "<h1>Unsafe and unusable.</h1>\n\n<h2>Class syntax is dangerous</h2>\n\n<p>The class syntax encourages you to expose the objects state, this means it can mutate outside your control.</p>\n\n<p>New developments allow class to have private properties. <code>#privateNamed</code> the hash means private. However its implementations is an abomination to the languages, we now have a situation where access type is embedded in the variable name. Names should be independent of any language constructs. Anyways I digress...</p>\n\n<p>As it stands your object (<code>class</code>) is unsafe, you expose <code>head</code> and <code>size</code> (in <code>LinkedList</code>) and <code>next</code> (in <code>Node</code>) meaning that outside code can deliberately or by accident mutate the objects state such that your function becomes inoperable. </p>\n\n<p>It is possible for your code to indefinitely block the page, meaning that the only way to fix the problem is for the page to crash or it to be forced to close.</p>\n\n<h3>Mutation examples</h3>\n\n<pre><code>const list = new LinkedList()\nlist.insert(\"\");\nlist.head.next = list.head; // cyclic link. \nlist.remove(\"☠\"); // Untrappable page blocking error\nlist.printList(); // will crash the page with out of memory error\n\nconst list = new LinkedList()\nlist.size = \"\";\nconsole.log(list.length); // &gt;&gt; \"\" nonsense \n\n\nconst list = new LinkedList()\nlist.insert(\"A\");\nconst a = list.head;\nlist.insert(\"B\");\nconst b = list.head;\nlist.insert(\"C\");\nlist.insert(\"D\");\nconst d = list.head; \nb.next = d; // removes c \n\nconsole.log(list.length()); // &gt;&gt; 4 Incorrect\nvar node = a;\nfor(let i = 0; i &lt; list.length; i++){\n console.log(node.value); // WTF throws error on 4th iteration\n node = node.next;\n}\n</code></pre>\n\n<h3>Normal use errors</h3>\n\n<pre><code>const list = new LinkedList()\nlist.insert(\"A\"); \nlist.insertAt(\"B\", -1); // does not insert returning undefined.\n\n\nconst list = new LinkedList()\nlist.size = 100; \nconsole.log(list.is__Empty()); // &gt;&gt; false, wrong answer the list is empty\n</code></pre>\n\n<p>I could go on, there are many dangers when you expose internal state. Programmers, you included will be tempted to use a shortcuts, or accidently mutate the list with catastrophic consequences.</p>\n\n<p>I would never allow such a dangerous object into a project, it is unusable because of its dangerous behaviour.</p>\n\n<h2>Object factories</h2>\n\n<p>Consider using a factory to create your Object.</p>\n\n<p>Factories let you create a private state via closure that can not be mutate. You can confidently use the state because it is hidden and immutable. </p>\n\n<h3>Factory example.</h3>\n\n<p>The factory returns a frozen object with the state hidden via closure. I add to functions. Iterator <code>LinkedList.values</code> to iterate the list from <code>0</code> to <code>size-1</code> eg <code>console.log([...list.values()])</code> will list items as an array. Also <code>linkedList.itemAt(index)</code> as the linked list is useless without them. </p>\n\n<p>You do not get access to nodes, only the values they contain. And <code>printList</code> is called <code>toString</code></p>\n\n<p>Note code is untested and as an example only. May contain typos or logic errors.</p>\n\n<pre><code>function LinkedList() {\n var head, size = 0;\n const add = (value, next) =&gt; {\n size ++;\n return {value, next};\n }\n const vetIndex = idx =&gt; isNaN(idx) || idx &gt; size || idx &lt; 0;\n const list = Object.freeze({\n get length() { return size },\n get isEmpty() { return size === 0 },\n insert(item) { head = add(item, head) },\n insertAt(item, idx = 0) {\n if (vetIndex(idx)) { throw new RangeError(\"Bad index\") }\n if (idx === size) { head = add(item, head) } \n else {\n let curr = head;\n while (++idx &lt; size) { curr = curr.next }\n curr.next = add(item, curr.next);\n }\n },\n remove(item) {\n if (head.value === item) { \n head = head.next;\n size --;\n } else {\n let curr = head;\n while (curr &amp;&amp; curr.next &amp;&amp; curr.next.value !== item) { curr = curr.next }\n if (curr) {\n curr.next = curr.next ? curr.next.next : undefined;\n size --;\n }\n }\n },\n toString() {\n var str = \"\";\n if (size) {\n str += head.value;\n let curr = head.next;\n while (curr) {\n str += \"-&gt;\" + curr.value;\n curr = curr.next;\n }\n }\n return str;\n }, \n *values() {\n var idx = 0;\n while (idx &lt; size) { yield list.itemAt(idx++) }\n },\n itemAt(idx) {\n if (size &amp;&amp; !vetIndex(idx)) {\n vetIndex(idx);\n if (idx === size) { return head.value }\n else {\n let curr = head;\n while (++idx &lt; size) { curr = curr.next }\n return curr.value\n }\n }\n }, \n });\n return list;\n}\n</code></pre>\n\n<h3>Some more points on your code</h3>\n\n<ul>\n<li>Function scope variables should be declared as <code>var</code>. Show you understand the language and use the correct declaration type.</li>\n<li>Use <code>const</code> for constants. Eg in <code>printList</code> you define an array <code>let out = [];</code> <code>out</code> is a reference to an array, the reference never changes, only the content of the array does, so use a constant <code>const out = [];</code></li>\n<li>Only throw if not doing so will damage state such that continuing will create undefined behaviours. You threw if an item could not be found in <code>remove</code> There is no reason to throw as it does not damage your state. Return <code>undefined</code> and let the calling function deal with their problems.</li>\n<li>When you throw do not throw strings (many catches assume an object and rethrow if its just a string). Use appropriate error objects. eg you throw a string <code>throw \"Wrong index\";</code> you should throw an error <code>throw new RangeError(\"Bad index\");</code> Or <code>throw new Error(\"Bad index\");</code></li>\n<li>Don't add redundant code. the function <code>insertAt</code> has 3 returns yet can be written with on extra <code>else</code> and a <code>break</code>, with no <code>return</code> tokens.</li>\n<li>Don't use <code>null</code>, its <code>undefined</code> if not defined. </li>\n<li>Always use the shorts form. Eg <code>if(this.head === null)</code> use <code>if(!this.head)</code> and <code>if (!curr.next) { curr.next = p;} else if (!curr.next.next) { curr.next = p;}</code> becomes <code>if(!curr.next || !curr.next..next) { curr.next = p }</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T20:49:53.297", "Id": "211434", "ParentId": "211380", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T17:22:50.017", "Id": "211380", "Score": "3", "Tags": [ "javascript", "linked-list", "ecmascript-6" ], "Title": "Singly Linked List Implementation in ES6" }
211380
<p>Initially, I was using the <code>class</code> syntax to structure my code. While it sure did feel nice to work with, I found it lacked some important functionalities, like private properties and interfaces. Things that I had found useful in other OOP languages like Java.</p> <p>I understand JavaScript doesn't have classes, I'm trying here to experiment with prototypes. So this thread belongs more to <a href="https://codereview.stackexchange.com/tags/object-oriented/info">Prototypal Class Design</a> (no documentation there...).</p> <p>I'm going for a <a href="https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)" rel="nofollow noreferrer">Factory Function design</a>, here are some of the advantages of using such technique to construct a "class" in JavaScript:</p> <ul> <li><p><strong>the factory and its instances can enclose private variables</strong>. This solves the problem of not having actual private instance/static properties usually seen in OOP languages.</p></li> <li><p>we <strong>have control over the object's prototype</strong> allowing us to combine prototypes from different factories. This makes it possible to "extend" factories with more properties/methods or mix multiple prototypes together similar to how interfaces work in OOP languages.</p></li> <li><p>we can <strong>keep a good structure for our factories</strong>, if we extend a factory with some methods, the instances coming from this new extended factory will remain as an instance of the initial factory. In other words, the opertator <code>instanceof</code> will still work.</p></li> </ul> <hr> <p>I have implemented such design using a IIFE wrapping the actual factory function. Here's the initial factory called <strong>Person</strong>, and below a factory called <strong>Singer</strong> which extends <strong>Person</strong>'s factory.</p> <pre class="lang-js prettyprint-override"><code>const Person = (function() { // private shared variables let total = 0; let average = 0; const updateAverage = function() { average = total / Person.count; } // public static attributes Person.count = 0; Person.prototype = { sayHi() { return `Hi, I'm ${this.name}`; } } function Person(name, age) { // private instance variables // public instance attributes const properties = { name, gapToAverage() { return Math.abs(age - average); } } // some logic Person.count += 1; total += age; updateAverage(); // return the instance return Object.create( Object.create(Person.prototype), // Person's prototype Object.getOwnPropertyDescriptors(properties) // Person's own public instance properties ); } // return the constructor return Person; })(); </code></pre> <pre class="lang-js prettyprint-override"><code>const Singer = (function() { let songs = {}; const prototypeExtension = { sing(song) { return songs[song]; } } // extend Person's prototype Singer.prototype = Object.create( Person.prototype, Object.getOwnPropertyDescriptors(prototypeExtension) ); function Singer(name, age, songs) { const properties = { getSongTitles() { return Object.keys(songs); } } // return the instance return Object.assign( Object.create(Singer.prototype), // Singer's prototype Person(name, age), // Person's public instance properties properties // Singer's own public instance properties ); } // return the constructor return Singer; })(); </code></pre> <p>This is considered the best approach to object-oriented programming in JavaScript. What do you think of this approach to OOP in JavaScript?</p> <p>I know it's possible to do the exact same thing with the class syntax by declaring variables and enclosing them inside the scope of the class' constructor. Which is better though?</p> <hr> <p>Here is the full code with an example:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// creating an instance of Person const person = Person('Nina', 32); console.log(Object.keys(person)); console.log("person instanceof Person: ", person instanceof Person) // creating an instance of Singer const singer = Singer('John', 20, { 'Little Bird Fly': 'blah' }); console.log(Object.keys(singer)); console.log("singer instanceof Person: ", singer instanceof Person) console.log("singer instanceof Singer: ", singer instanceof Singer)</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt;const Person=(function(){let total=0;let average=0;const updateAverage=function(){average=total/Person.count} Person.count=0;Person.prototype={sayHi(){return `Hi, I'm ${this.name}`}} function Person(name,age){const properties={name,gapToAverage(){return Math.abs(age-average)}} Person.count+=1;total+=age;updateAverage();return Object.create(Object.create(Person.prototype),Object.getOwnPropertyDescriptors(properties))} return Person})();const Singer=(function(){let songs={};const prototypeExtension={sing(song){return songs[song]}} Singer.prototype=Object.create(Person.prototype,Object.getOwnPropertyDescriptors(prototypeExtension));function Singer(name,age,songs){const properties={getSongTitles(){return Object.keys(songs)}} return Object.assign(Object.create(Singer.prototype),Person(name,age),properties)} return Singer})()&lt;/script&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:23:28.720", "Id": "412681", "Score": "0", "body": "It doesn't look as though your `sing` method will function properly. Nothing updates the in-scope version of `songs` that it uses. But it also likely doesn't make sense here, since if that *was* updated, then you might get Kanye West singing Elton John's or Marian Anderson's songs... and we don't want to hear that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:25:40.167", "Id": "412682", "Score": "0", "body": "\"I know it's possible [to use the built-in syntax]... Which is better?\" Although I'm not a fan of the class syntax, if it's available to you and does what you want without any additional overhead, I can't see a reason *not* to use it." } ]
[ { "body": "<p>Your code looks fine except for the fact it's not super-readable. You may consider other solutions. If you look for private properties, some recommend using ES6 Symbols or WeakMaps. Babel also offers some solutions. For interfaces you can check the <a href=\"https://www.npmjs.com/package/es6-interface\" rel=\"nofollow noreferrer\">es6-interface npm package</a> or <a href=\"https://codeburst.io/interfaces-in-javascript-with-es6-naive-implementation-91b703110a09\" rel=\"nofollow noreferrer\">naive interface implementation using Symbols</a>. I don't know which approach is better, but one of the most important things in OOP for me is readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T22:22:42.760", "Id": "211395", "ParentId": "211382", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T18:15:32.033", "Id": "211382", "Score": "1", "Tags": [ "javascript", "object-oriented" ], "Title": "Experimenting with a OOP design pattern in JavaScript" }
211382
<p><sub>I have started to learn C. At the time of writing I don't know anything about the language. The following I wrote today in a few hours. Though I do have a lot of programming experience, I find C hard to learn. That may be only a temporary impression, however.</sub></p> <hr> <p>The purpose of the following function is to determine if the string, <strong>whatever its length is</strong>, contains an integer number. There might be many ways, and/or I might have done some rookie mistakes.</p> <hr> <pre class="lang-c prettyprint-override"><code>#include &lt;stdbool.h&gt; // bool type, true / false values, ... #include &lt;stdio.h&gt; // printf() #include &lt;ctype.h&gt; // isdigit() #include &lt;string.h&gt; // strlen(), strncmp(), ... bool string_contains_integer(const char *str) /* This function iterates through an array of chars, and checks each character to be a digit. Returns true if the string contains a number (string of digits); Returns false if the string contains another character(s). Starting "-" gets ignored, as we accept negative numbers too. */ { // I'd like to avoid repeated strlen() calls int string_length = strlen(str); // if the string is empty, return right away if (string_length == 0) return false; bool negative_sign = false; // iterate through all characters in the string for (int i = 0; i &lt; string_length; i++) { // extract character on index char chr = str[i]; // repeated presence of negative sign is handled here if (strncmp("-", &amp;chr, 1) == 0) { // if the negative sign gets detected // for the second time, return right away if (negative_sign) return false; // once a negative sign is detected, we make note of it here negative_sign = true; // now we want to skip the check for a digit continue; } // this is actually the core part checking on digits if (!isdigit(chr)) return false; } // If we got here, then all the characters are digits, // possibly starting with a negative sign. return true; } int main() { // the function can handle very big numbers as shown here if (string_contains_integer("-123456789123456789123456789123456789123456789123456789123456789")) { printf("%s\n", "PASS: Input is a number."); } else { printf("%s\n", "FAIL: Input is not a number!"); } } </code></pre> <hr> <p>This program I compile on Linux Mint 19.1 as follows:</p> <pre class="lang-c prettyprint-override"><code>gcc-8 -std=c18 -Wall -Wextra -Werror -Wpedantic -pedantic-errors -o bigInteger bigInteger.c </code></pre> <hr> <p>Would you be that kind to review the code? However, there might be alternative ways of doing the same thing, you may, of course, suggest them, but my primary goal now is to check upon my learning curve and to fix bugs of course, optimize this code, etc.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T18:43:40.310", "Id": "408739", "Score": "3", "body": "Is it intentional that \"123-456\" passes the test as an integer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T21:43:11.270", "Id": "408750", "Score": "0", "body": "Some test cases to consider: \"0\", \"0-0\", \"-0\", \"+9\", \"--9\"" } ]
[ { "body": "<p><strong>Good observation</strong></p>\n\n<p>Many new C programmers do not realize that <code>n = strlen(s)</code> when called in a loop can take code from linear performance O(n) to worse O(n*n) performance when <code>s</code> may change or with weak compilers.</p>\n\n<pre><code>// I'd like to avoid repeated strlen() calls\nint string_length = strlen(str); // Good!!\n</code></pre>\n\n<p><strong>Good use of <code>const</code></strong></p>\n\n<p>Nice. <code>string_contains_integer(const char *str)</code></p>\n\n<p><strong>Nicely formatted code</strong></p>\n\n<p>I hope you are using an auto formatter. Life is too short for manual formatting.</p>\n\n<hr>\n\n<p><strong>\"whatever its length is\"</strong></p>\n\n<p><em>Strings</em> can have a length that exceeds <code>INT_MAX</code>. Note that <code>strlen()</code> returns type <code>size_t</code>. That is the right-sized type for array indexing and sizing. Note: <code>size_t</code> is some <em>unsigned</em> type.</p>\n\n<pre><code>// int string_length = strlen(str);\n// for (int i = 0; i &lt; string_length; i++)\n\nsize_t string_length = strlen(str);\nfor (size_t i = 0; i &lt; string_length; i++)\n</code></pre>\n\n<p><strong>Expensive sign compare</strong></p>\n\n<p>Rather than call <code>strncmp()</code>, just compare characters.</p>\n\n<pre><code>// char chr = str[i];\n// if (strncmp(\"-\", &amp;chr, 1) == 0)\nif (str[i] == '-')\n</code></pre>\n\n<p>OP's code is tricky here. <code>strncmp()</code> can handle non-strings (which is what <code>&amp;chr</code> points to) as long as they do not exceed <code>n</code>. With <code>n==1</code>, code is effectively doing a <code>char</code> compare.</p>\n\n<p><strong>Sign at the beginning</strong></p>\n\n<p>Conversion of strings to numeric values allow a <em>leading</em> sign, either <code>'-'</code>, <code>'+'</code> or none. This code errantly allows a <code>'-'</code> <em>someplace</em>. <a href=\"https://codereview.stackexchange.com/questions/211384/biginteger-check-in-c-from-a-string#comment408739_211384\">@Martin R</a>. </p>\n\n<p>Just start with </p>\n\n<pre><code>bool string_contains_integer(const char *str) {\n if (*str == '-' || *str == '+') {\n str++;\n }\n ....\n\n // Other sign code not needed\n</code></pre>\n\n<p><strong><code>strlen()</code> not needed.</strong></p>\n\n<p>Rather than <code>i &lt; string_length</code>, just test <code>str[i] != '\\0'</code>. This speeds up detection of non-numeric strings as the entire string does not need to be read.</p>\n\n<p><strong><code>is...(int ch)</code> quirk</strong></p>\n\n<p><code>is...()</code> functions are specified for <code>int</code> values in the <code>unsigned char</code> range and <code>EOF</code>. On common platforms where <code>char</code> is signed, <code>isdigit(chr)</code> risks <em>undefined behavior</em> (UB) when <code>chr &lt; 0</code>. Best to cast here.</p>\n\n<pre><code>// isdigit(chr)\nisdigit((unsigned char) chr)\n</code></pre>\n\n<p><strong><code>{ block }</code></strong></p>\n\n<p>Of coding style, I recommend to always use <code>{}</code> after <code>if,else</code>, even if one line.</p>\n\n<pre><code>//if (string_length == 0)\n// return false;\n\nif (string_length == 0) {\n return false;\n}\n</code></pre>\n\n<p><strong>Minor: Simplification</strong></p>\n\n<p>To simply prints a line, code could use <code>puts()</code>. But what you did is OK. Note <code>puts()</code> appends a <code>'\\n'</code>.</p>\n\n<pre><code>// printf(\"%s\\n\", \"PASS: Input is a number.\");\nputs(\"PASS: Input is a number.\");\n</code></pre>\n\n<hr>\n\n<p><strong>Alternative</strong></p>\n\n<p>This does not use array indexing. Just increment the pointer as needed.</p>\n\n<pre><code>bool string_contains_integer_alt(const char *str) {\n if (*str == '-' || *str == '+') {\n str++;\n }\n\n if (*str == '\\0') {\n return false;\n }\n\n while (isdigit((unsigned char)*str)) {\n str++;\n }\n\n return *str == '\\0';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T05:42:51.203", "Id": "408779", "Score": "0", "body": "@Vlastimil I did not forget. `main() `is special. The return is optional. [Is It Necessary to Return a Value in Main()?](https://stackoverflow.com/questions/8376421/is-it-necessary-to-return-a-value-in-main) IMO, it is better to include. Follow your group's style guide." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T21:44:01.500", "Id": "211392", "ParentId": "211384", "Score": "6" } }, { "body": "<p>You already have a good review by chux; I'll not repeat the observations from there. Instead, I'll highlight a couple of opportunities to advance beyond &quot;beginner&quot; level C.</p>\n<h1>Become more comfortable with pointers</h1>\n<p>Many C beginners seem to be intimidated by pointers. That can lead to clumsy non-idiomatic C using indexing instead. Whilst that's functionally correct, it will look unwieldy to the experienced C programmer, and will also hinder your ability to read code written in a more pointer-oriented style.</p>\n<p>It's worth practising your pointer code until your are completely confident you can both write and understand that style.</p>\n<h1>Learn what's in the Standard Library</h1>\n<p>The C Standard Library contains many functions to make your life easier. You're using <code>isdigit()</code> which is great; another function that may help us is <code>strspn()</code>, which can replace the loop for us (but we'll have to specify the allowed digits, which loses us some of the locale-independence that <code>isdigit()</code> gives us):</p>\n<pre><code>bool string_contains_integer(const char *str)\n{\n if (*str == '-') {\n ++str;\n }\n\n size_t digit_count = strspn(str, &quot;0123456789&quot;);\n return digit_count &gt; 0\n &amp;&amp; str[digit_count] == '\\0';\n}\n</code></pre>\n<p>The <code>digit_count &gt; 0</code> test ensures we have at least one digit, and <code>str[digit_count] == '\\0'</code> checks that the first non-digit is the the end of the string.</p>\n<h1>Add more tests</h1>\n<p>It's worth writing a small helper function:</p>\n<pre><code>static bool test_contains_integer(bool expected, const char *str)\n{\n if (expected == string_contains_integer(str)) {\n return true;\n }\n fprintf(stderr, &quot;FAIL: Expected %s but got %s for input %s\\n&quot;,\n expected ? &quot;true&quot; : &quot;false&quot;,\n expected ? &quot;false&quot; : &quot;true&quot;,\n str);\n return false;\n}\n</code></pre>\n<p>When we have a lot of tests, it helps to produce output only for the failures. We can count how many pass and how many fail:</p>\n<pre><code>int main(void)\n{\n /* counts of failure and pass */\n int counts[2] = { 0, 0 };\n\n ++counts[test_contains_integer(false, &quot;&quot;)];\n ++counts[test_contains_integer(false, &quot;-&quot;)];\n ++counts[test_contains_integer(true, &quot;0&quot;)];\n ++counts[test_contains_integer(true, &quot;-0&quot;)]; /* questionable */\n ++counts[test_contains_integer(true, &quot;-00&quot;)]; /* questionable */\n ++counts[test_contains_integer(true, &quot;1&quot;)];\n ++counts[test_contains_integer(false, &quot;1a&quot;)];\n ++counts[test_contains_integer(true, &quot;-10&quot;)];\n\n printf(&quot;Summary: passed %d of %d tests.\\n&quot;,\n counts[true], counts[false] + counts[true]);\n\n return counts[false] != 0;\n}\n</code></pre>\n<hr />\n<p>Finally, a minor nit: prefer to declare a <code>main</code> that takes no arguments, rather than one that takes unspecified arguments:</p>\n<pre><code>int main(void)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T14:50:34.050", "Id": "408915", "Score": "0", "body": "The ancient orders of Ones` Complement Preservation Society and Sign Magnitude Forever wish to lodge a protest of the besmirch-ment of `\"-0\")]; /* questionable */`. [`\"-0\"`](https://scrapbookofhumor.weebly.com/hyperbolic-humor.html) are people too. ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T15:34:17.050", "Id": "408922", "Score": "0", "body": "@chux, protest noted ;-) In my defence, I'll point out that that I actually meant that we should question/confirm that the behaviour is the one that's desired; \"questionable\" != \"wrong\" when I'm reviewing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T11:04:29.077", "Id": "211464", "ParentId": "211384", "Score": "3" } } ]
{ "AcceptedAnswerId": "211392", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T18:34:43.587", "Id": "211384", "Score": "5", "Tags": [ "beginner", "c", "strings", "integer" ], "Title": "BigInteger check in C from a string" }
211384
<p>I have an assignment to draw rectangles that get larger and larger each time I draw them. Just like shown below. I've labeled them TL = Top Left, TR = Top Right, BL = Bottom Left, BR = Bottom Right. The smallest boxes are 8 pixels by 8 pixels. From this drawing I pulled these algorithms for each box. Where n represents the level you are drawing. Level 0 is the inside set of four and grows out by 1.</p> <pre><code>TL = (x-n(8), y - n(8)) TR = ((x + 8) - (n*8), y - n(8)) BL = (x - n(8), y - (n+1)(8)) BR = ((x+8)+(n*8), (y+8)-(n*8)); </code></pre> <p>My real questions is this. I feel like I can combine these algorithms into something smaller but I'm new to this type of thinking. This is the first Computer Science Class I've taken that required me to do this type of thinking. Do you have any suggestions? </p> <p><a href="https://i.stack.imgur.com/rwxA0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rwxA0.png" alt=""></a></p> <p>From these algorithms I wrote this code in Java. </p> <pre><code> public static void drawRectangle(Graphics g, int xCenter, int yCenter, int levelsNeeded){ //all squres are based off an 8 pixel system. I use this to shift things around ALOT. final int CHANGECONSTANT = 8; int width = 8; int height = 8; int dcg = 1; //Dimension Change Factor Point origin = new Point(xCenter -= CHANGECONSTANT, yCenter -= CHANGECONSTANT); //Sets Origin to top left of inner most set of squares for (int level = 0; level &lt; levelsNeeded; level++) { g.setColor(Color.GRAY); //Top Left g.fillRect( (int)origin.getX()-(level*CHANGECONSTANT), // XCord (int)origin.getY()-(level*CHANGECONSTANT), // YCord width, //width. This stays at 8 for all iterations height*dcg);//height. This gets multiplied by odd factors each time //Draw outline g.setColor(Color.BLACK); g.drawRect( (int)origin.getX()-(level*CHANGECONSTANT), // XCord (int)origin.getY()-(level*CHANGECONSTANT), // YCord width, //width. This stays at 8 for all iterations height*dcg);//height. This gets multiplied by odd factors each time g.setColor(Color.GRAY); //Bottom Left g.fillRect( (int)origin.getX()-(level*CHANGECONSTANT), //XCrod (int)origin.getY()+((level+1)*CHANGECONSTANT), //YCord width*dcg, //width. This gets multiplied by odd factors each time height); //height. This stays at 8 for all iterations g.setColor(Color.BLACK); //Draw Outline g.drawRect( (int)origin.getX()-(level*CHANGECONSTANT), //XCrod (int)origin.getY()+((level+1)*CHANGECONSTANT), //YCord width*dcg, //width. This gets multiplied by odd factors each time height); //height. This stays at 8 for all iterations g.setColor(Color.WHITE); //Top Right g.fillRect( ((int)origin.getX()+CHANGECONSTANT)-(level*CHANGECONSTANT), //XCord (int)origin.getY()-(level*CHANGECONSTANT), //YCord width*dcg,//width. This gets multiplied by odd factors each time height);//height. This stays at 8 for all iterations //Draw Outline g.setColor(Color.BLACK); g.drawRect( ((int)origin.getX()+CHANGECONSTANT)-(level*CHANGECONSTANT), //XCord (int)origin.getY()-(level*CHANGECONSTANT), //YCord width*dcg,//width. This gets multiplied by odd factors each time height);//height. This stays at 8 for all iterations g.setColor(Color.WHITE); //Bottom Right g.fillRect( ((int)origin.getX()+CHANGECONSTANT)+(level*CHANGECONSTANT), //Xcord ((int)origin.getY()+CHANGECONSTANT)-(level*CHANGECONSTANT), //Ycord width,//width. This gets multiplied by odd factors each time height*dcg);//Height. This stays at 8 for all iterations. //Draw Outline g.setColor(Color.BLACK); g.drawRect( ((int)origin.getX()+CHANGECONSTANT)+(level*CHANGECONSTANT), //Xcord ((int)origin.getY()+CHANGECONSTANT)-(level*CHANGECONSTANT), //Ycord width,//width. This gets multiplied by odd factors each time height*dcg);//Height. This stays at 8 for all iterations. dcg += 2; //Increment DCG by two at end of each loop } } </code></pre> <p>Here is what my final product looks like right now. Disregard the triangle shapes that a different method that calls the first one multiple times.</p> <p><a href="https://i.stack.imgur.com/VyEYq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VyEYq.png" alt=""></a></p> <p>This is my first quarter learning Java and I'm new to programming. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T19:03:14.370", "Id": "408820", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h3>Naming</h3>\n\n<blockquote>\n<pre><code> public static void drawRectangle(Graphics g, int xCenter, int yCenter, int levelsNeeded){\n</code></pre>\n</blockquote>\n\n<p>I would call this <code>drawRectangles</code>, as it draws four rectangles on each iteration of the loop. Also, that leaves room for a <code>drawRectangle</code> method. </p>\n\n<h3>Typos</h3>\n\n<blockquote>\n<pre><code> //all squres are based off an 8 pixel system. I use this to shift things around ALOT.\n</code></pre>\n</blockquote>\n\n<p>This has two typos. </p>\n\n<pre><code> // all squares are based off an 8 pixel system. I use this to shift things around A LOT.\n</code></pre>\n\n<h3>Comments</h3>\n\n<blockquote>\n<pre><code> Point origin = new Point(xCenter -= CHANGECONSTANT, yCenter -= CHANGECONSTANT); //Sets Origin to top left of inner most set of squares\n</code></pre>\n</blockquote>\n\n<p>If you break this up into two lines, it's easier to read</p>\n\n<pre><code> // Sets Origin to top left of inner most set of squares\n Point origin = new Point(xCenter -= CHANGECONSTANT, yCenter -= CHANGECONSTANT);\n</code></pre>\n\n<p>And it doesn't put a scroll bar on my StackExchange screen. </p>\n\n<h3>Refactoring</h3>\n\n<blockquote>\n<pre><code> g.setColor(Color.GRAY);\n //Top Left\n g.fillRect(\n (int)origin.getX()-(level*CHANGECONSTANT), // XCord\n (int)origin.getY()-(level*CHANGECONSTANT), // YCord\n width, //width. This stays at 8 for all iterations\n height*dcg);//height. This gets multiplied by odd factors each time\n //Draw outline\n g.setColor(Color.BLACK);\n g.drawRect(\n (int)origin.getX()-(level*CHANGECONSTANT), // XCord\n (int)origin.getY()-(level*CHANGECONSTANT), // YCord\n width, //width. This stays at 8 for all iterations\n height*dcg);//height. This gets multiplied by odd factors each time\n</code></pre>\n</blockquote>\n\n<p>You repeat this pattern four times. Consider </p>\n\n<pre><code> public static void drawRectangle(Graphics g, int x, int y, int width, int height, Color color) {\n g.setColor(color);\n g.fillRect(x, y, width, height);\n\n g.setColor(Color.BLACK);\n g.drawRect(x, y, width, height);\n }\n</code></pre>\n\n<p>Then we can just write </p>\n\n<pre><code> // the corner coordinates change by a constant amount each level\n final int maximumDelta = levelsNeeded * CHANGECONSTANT;\n for (int delta = 0; delta &lt; maximumDelta; delta += CHANGECONSTANT)\n {\n final int left = (int)origin.getX() - delta;\n final int top = (int)origin.getY() - delta;\n\n // the width and height change twice as fast as the corner locations\n final int wide = narrow + 2 * delta;\n final int tall = small + 2 * delta;\n\n drawRectangle(g, left, top, narrow, tall, Color.GRAY);\n drawRectangle(g, left, bottom - delta, wide, small, Color.GRAY);\n drawRectangle(g, right - delta, top, wide, small, Color.WHITE);\n drawRectangle(g, right + delta, bottom + delta, narrow, tall, Color.WHITE);\n }\n</code></pre>\n\n<p>This assumes a previous change of <code>width</code> and <code>height</code> to <code>narrow</code> and <code>small</code>. We still have <code>width</code> and <code>height</code> in the helper method. Add <code>right</code> and <code>bottom</code> with them, outside the loop.</p>\n\n<pre><code> final int right = (int)origin.getX() + CHANGECONSTANT;\n final int bottom = (int)origin.getY() + CHANGECONSTANT;\n</code></pre>\n\n<p>This is both shorter and more readable in my opinion. Rather than recalculating everything as needed, it calculates everything once. By using these names, we can easily see that a particular rectangle is the \"left, top\" that is drawn gray in \"narrow, tall\" aspect. We don't need comments, as these names are self-documenting. </p>\n\n<p>We can make all of these <code>final</code>, but you don't need to do so. </p>\n\n<p>I eliminated <code>dcg</code>. It was confusingly named and as I looked at it more carefully, unnecessary. </p>\n\n<p>You could also make things easier by changing this from a <code>static</code> (class) method to an object method. Then your constructor could take a <code>Graphics</code> object. That would save passing it around all the time. You don't provide enough context to say whether this is a good idea. This might require moving this method to a different class. </p>\n\n<p>I would add an underscore to <code>CHANGECONSTANT</code> and call it <code>CHANGE_CONSTANT</code>. Or change the name to something else entirely, e.g. <code>INTERVAL</code> or <code>STANDARD_DIMENSION</code>. </p>\n\n<p>You haven't provided driver code; I haven't tried to run this version to see if it gives the same behavior. Beware of errors that might have been found by running the code. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T07:55:29.230", "Id": "211407", "ParentId": "211386", "Score": "2" } } ]
{ "AcceptedAnswerId": "211407", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T20:26:28.980", "Id": "211386", "Score": "4", "Tags": [ "java", "beginner", "algorithm", "homework", "graphics" ], "Title": "Drawing consecutive rectangles with an algorithm" }
211386
<p>I'm implementing HTTP traffic monitor (proxy) for my project right now. It's performance is satisfactory. I've updated regex settings and improved performance but I think there are also ways to make it better.</p> <pre><code>//mipt public class TrafficMonitor { private int _port; private bool _isWorking; private TcpListener _listener; private static readonly Regex myReg = new Regex(@"Host: (((?&lt;hostName&gt;.+?):(?&lt;port&gt;\d+?))|(?&lt;hostName&gt;.+?))\s+", RegexOptions.Compiled); public TrafficMonitor(int port) { _port = port; _listener = new TcpListener(IPAddress.Parse("127.0.0.1"), _port); } public void Start() { _listener.Start(); _isWorking = true; while (_isWorking) { TcpClient client = _listener.AcceptTcpClient(); Task.Factory.StartNew(() =&gt; Worker(client.Client)); } } public void Stop() { _isWorking = false; _listener.Stop(); } private void Worker(Socket clientSocket) { if (clientSocket.Connected) { byte[] httpRequest = ReadToEnd(clientSocket); Match m = myReg.Match(Encoding.ASCII.GetString(httpRequest)); string hostName = m.Groups["hostName"].Value; int port = 0; if (!int.TryParse(m.Groups["port"].Value, out port)) { port = 80; } IPHostEntry hostEntry = Dns.GetHostEntry(hostName); IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(endPoint); if (socket.Send(httpRequest, httpRequest.Length, SocketFlags.None) == httpRequest.Length) { byte[] httpResponse = ReadToEnd(socket); if (httpResponse != null &amp;&amp; httpResponse.Length &gt; 0 ) clientSocket.Send(httpResponse, httpResponse.Length, SocketFlags.None); } socket.Close(); clientSocket.Close(); } } private byte[] ReadToEnd(Socket socket) { byte[] recievedData = new byte[socket.ReceiveBufferSize]; int len = 0; using (MemoryStream m = new MemoryStream()) { while (socket.Poll(1000000, SelectMode.SelectRead) &amp;&amp; (len = socket.Receive(recievedData, socket.ReceiveBufferSize, SocketFlags.None)) &gt; 0) { m.Write(recievedData, 0, len); } return m.ToArray(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T23:32:48.820", "Id": "408757", "Score": "0", "body": "your regex has to backtrack a lot. Try something like `Host: (?<host>[\\w.-]+) :? (?<port> (?: (?<=:) \\d+ )? ) \\s ` (spaces added for readability; they should be removed)." } ]
[ { "body": "<p>I don't program in C and I don't know the exact input strings that you're expecting, but I can offer a couple of regex suggestions based on reasonable assumptions.</p>\n\n<p>Your regex:</p>\n\n<pre><code>@\"Host: (((?&lt;hostName&gt;.+?):(?&lt;port&gt;\\d+?))|(?&lt;hostName&gt;.+?))\\s+\"\n</code></pre>\n\n<p>Your pattern looks for a hostname followed by a colon then a port number then whitespace characters OR a hostname followed by whitespace characters.</p>\n\n<ul>\n<li>Since you are not capturing the whitespace and merely using the whitespace as an end point, the pattern can be reconfigured.</li>\n<li>Since the colon-port substring is optional, the zero or one quantifier <code>?</code> can be used to eliminate the redundant named capture group (which was causing trouble at regex101.com).</li>\n<li><code>+?</code> calls for \"lazy\" matching. If you want your pattern to execute quickly, rewrite your pattern to use greedy quantifiers.</li>\n</ul>\n\n<p>New pattern:</p>\n\n<pre><code>@\"Host: (?&lt;hostName&gt;[^:\\s]+)(:(?&lt;port&gt;\\d+))?\"\n</code></pre>\n\n<p>Here is a cheap and cheerful demo: <a href=\"https://regex101.com/r/NqSJ8L/1/\" rel=\"nofollow noreferrer\">https://regex101.com/r/NqSJ8L/1/</a></p>\n\n<p>Note, my above pattern could be massaged a few different ways. For instance, you might use <code>^</code> and an <code>m</code> pattern modifier to anchor the pattern to the start of the line of text. Again, I don't program in C, so I don't know if there are incapatabilities with certain pattern entities.</p>\n\n<p>Or instead of a negated character class, you can list the valid character for a hostname:</p>\n\n<pre><code>@\"Host: (?&lt;hostName&gt;[\\w.-]+)(:(?&lt;port&gt;\\d+))?\"\n</code></pre>\n\n<p>P.s. It just occurred to me that my optional pattern will not always deliver a named capture group for the port, so if you don't want to write code to check that the port capture group is generated, here is OhMyGoodness's commented pattern without the trailing whitespace matching. <code>(?&lt;= )</code> is a lookbehind. <code>(?: )</code> is a non-capturing group.</p>\n\n<pre><code>Host: (?&lt;hostName&gt;[\\w.-]+):?(?&lt;port&gt;(?:(?&lt;=:)\\d+)?)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T00:15:23.023", "Id": "211401", "ParentId": "211389", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T20:51:31.527", "Id": "211389", "Score": "1", "Tags": [ "c#", "regex", "http" ], "Title": "C# HTTP proxy performance" }
211389
<p>The aim of my code is to decode an image format that is based on the JPEG chain of compression/decompression, however it is not compatible with the default JPEG flow as far as I know, since all libraries I have tried fail to properly decode the data. I am only interested decompression in this case. It follows the standard pattern:</p> <ul> <li>Read Huffman values -> Like normal JPEG</li> <li>unzigzag -> Like normal JPEG</li> <li>Dequantize -> Like normal JPEG</li> <li>IDCT -> Almost like normal JPEG, but different range/clamping</li> <li>Color Space conversion -> Custom, not YCbCr</li> </ul> <p>For one 8x8 except for the last step that looks like this right now:</p> <pre><code>int16_t processBlock(int16_t prevDc, BitStream &amp;stream, const tHuffTable &amp;dcTable, const tHuffTable &amp;acTable, float *quantTable, bool isLuminance, int16_t *outBlock) { int16_t workBlock[64] = {0}; int16_t curDc = decodeBlock(stream, workBlock, dcTable, acTable, prevDc); unzigzag(workBlock); dequantize(workBlock, quantTable); idct(outBlock, workBlock, isLuminance); return curDc; } </code></pre> <p>after this the <code>outBlock</code> is treated by the color space conversion based on the image type.</p> <p>What I want to optimize is the overall performance. The entire image is decompressed in the following way with 4 luminance blocks for component 1, 1 chrominance block for component 2 and 1 chrominance block for component 3. There are 4 more blocks for another luminance component, but I dont know what it is used for, so we can ignore it. The code looks like this:</p> <pre><code>void decodeImageType0( uint32_t width, uint32_t height, std::vector&lt;uint8_t&gt; &amp;outData, BitStream &amp;stream, const tHuffTable &amp;dcLumTable, const tHuffTable &amp;acLumTable, const tHuffTable &amp;dcCromTable, const tHuffTable &amp;acCromTable, float *lumQuant[4], float *cromQuant[4]) { int16_t lum0[4][64]{}; int16_t lum1[4][64]{}; int16_t crom0[64]{}; int16_t crom1[64]{}; uint32_t colorBlock[16 * 16]{}; const auto actualHeight = ((height + 15) / 16) * 16; const auto actualWidth = ((width + 15) / 16) * 16; int16_t prevDc[4] = {0}; for (auto y = 0; y &lt; (actualHeight / 16); ++y) { for (auto x = 0; x &lt; (actualWidth / 16); ++x) { for (auto &amp;lum : lum0) { prevDc[0] = processBlock(prevDc[0], stream, dcLumTable, acLumTable, lumQuant[0], true, lum); } prevDc[1] = processBlock(prevDc[1], stream, dcCromTable, acCromTable, cromQuant[1], false, crom0); prevDc[2] = processBlock(prevDc[2], stream, dcCromTable, acCromTable, cromQuant[2], false, crom1); for (auto &amp;lum : lum1) { prevDc[3] = processBlock(prevDc[3], stream, dcLumTable, acLumTable, lumQuant[3], true, lum); } decodeColorBlockType0(lum0, lum1, crom0, crom1, colorBlock); for (auto row = 0; row &lt; 16; ++row) { if(y * 16 + row &gt;= height || x * 16 &gt;= width) { continue; } const auto numPixels = std::min(16u, width - x * 16); memcpy(outData.data() + (y * 16 + row) * width * 4 + x * 16 * 4, &amp;colorBlock[row * 16], numPixels * 4); } } } } </code></pre> <p>Now my measurements have shown that over 80% of the time is spent inside the <code>idct</code> function, so this is where I want to optimize. The function looks like this, after I applied what I could think of to optimize it. I have created a cache of the static coefficients used in the IDCT process which significantly improved performance, but I hope there is still room for more, for example nanojpg is 3 times faster (however with invalid results).</p> <pre><code>float idctHelper(const int16_t *inBlock, int32_t u, int32_t v, int32_t blockWidth, int32_t blockHeight) { glm::vec&lt;4, float, glm::packed_lowp&gt; vec3{}; float result = 0.0f; for (auto y = 0; y &lt; blockHeight; ++y) { for (auto x = 0; x &lt; blockWidth; x += 4) { const auto idx = (v * 8 + u) * 64 + y * 8 + x; vec3 = glm::vec&lt;4, float, glm::packed_lowp&gt;(inBlock[y * blockWidth + x], inBlock[y * blockWidth + x + 1], inBlock[y * blockWidth + x + 2], inBlock[y * blockWidth + x + 3]) * glm::vec&lt;4, float, glm::packed_lowp&gt;(idctLookup[idx], idctLookup[idx + 1], idctLookup[idx + 2], idctLookup[idx + 3]); result += vec3.x + vec3.y + vec3.z + vec3.w; } } return result; } template&lt;typename T, typename U = T&gt; U clamp(T value, T min, T max) { return static_cast&lt;U&gt;(std::min&lt;T&gt;(std::max&lt;T&gt;(value, min), max)); } void idct(int16_t *outBlock, int16_t *inBlock, bool isLuminance, int32_t blockWidth = 8, int32_t blockHeight = 8) { for (auto y = 0; y &lt; blockHeight; ++y) { for (auto x = 0; x &lt; blockWidth; ++x) { auto value = static_cast&lt;int16_t&gt;(std::round( 0.25f * idctHelper(inBlock, x, y, blockWidth, blockHeight))); if (isLuminance) { value = clamp&lt;int16_t&gt;(static_cast&lt;int16_t&gt;(value + 128), 0, 255); } else { value = clamp&lt;int16_t&gt;(value, -256, 255); } outBlock[y * blockWidth + x] = value; } } } </code></pre> <p>This is the cache that is created once at the start of the application outside of time measurements:</p> <pre><code>float alphaFunction(int32_t n) { static float INV_SQRT_2 = 1.0f / sqrtf(2.0f); if (n == 0) { return INV_SQRT_2; } else { return 1; } } for (auto u = 0; u &lt; 8; ++u) { for (auto v = 0; v &lt; 8; ++v) { for (auto x = 0; x &lt; 8; ++x) { for (auto y = 0; y &lt; 8; ++y) { idctLookup[(v * 8 + u) * 64 + y * 8 + x] = alphaFunction(x) * alphaFunction(y) * cosf((2 * u + 1) * x * (float) M_PI / 16.0f) * cosf((2 * v + 1) * y * (float) M_PI / 16.0f); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T04:17:39.107", "Id": "408774", "Score": "1", "body": "The code at the end with the four nested `for` loops — is that part of a function or what?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T08:10:20.413", "Id": "408784", "Score": "0", "body": "I have edited the question. It is created only once at the start of the application and is not part of the measured times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T13:46:08.410", "Id": "464253", "Score": "0", "body": "Instead of `round(0.25f` etcetera use integer math (i.e. int division). Where feasible." } ]
[ { "body": "<p>DCT can be implemented with a fast algorithm. I understand you implemented it with a matrix multiplication, which is much less efficient. </p>\n\n<p>DCT algorithms are similar to FFT ones. You can find many references with a simple search, on Wikipedia for example</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T10:10:17.127", "Id": "211409", "ParentId": "211391", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T21:24:48.603", "Id": "211391", "Score": "3", "Tags": [ "c++", "performance", "image" ], "Title": "Optimizing custom JPEG decompression" }
211391
<p>Could you guys tell me if my code is safe? And i want to know how to improve it. You will see a detailed explanation about the code on the comment blocks inside the code.</p> <p>profileIMGform.php <pre><code>require_once 'db.php'; if(!empty($_SESSION['user_id'])){ $user_id = $_SESSION['user_id']; }else{ $user_id = NULL; } // here i check if the user is logged in if(\array_key_exists('user_id', $_SESSION) &amp;&amp; $user_id = \filter_var($_SESSION['user_id'], \FILTER_VALIDATE_INT)){ if($_SERVER['REQUEST_METHOD'] == 'POST'){ //i use this condition because i have another code about file upload inside this file if(!empty($_FILES['uploadedIMG']['size'])){ $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $_FILES["uploadedIMG"]["tmp_name"]); $allowedMimeTypes = [ 'image/jpeg', 'image/jpg', 'image/png' ]; list($width, $height) = getimagesize($_FILES["uploadedIMG"]["tmp_name"]); $sizeFILE = filesize($_FILES["uploadedIMG"]["tmp_name"]); //here i check if the uploaded file is a "valid" image, the function "getimagesize()" // is not 100% trustable, but i added this function here as a "wall" if(in_array($mimeType, $allowedMimeTypes) &amp;&amp; $width != null &amp;&amp; $height != null &amp;&amp; $sizeFILE &lt;= 768000){ //if the uploaded file is a "valid" image, then it will execute this code on the //try/catch try{ $linkN = $_SESSION['linkN']; //user local folder name $imgPF = $_SESSION['img']; //user defaut avatar img that is set when they //resgister the account $capaPF = $_SESSION['capa']; //user defaut wallpaper that is set when they //resgister the account $linkNPFFetch = $linkN; $folderPFFetch = 'user/'.$linkN.'/'; //this variable is used on the glob() //function bellow // here i made a SELECT query to get the slug from the username, just in case //if they changed the username while logged in, this slug is used on the URL $perfilUpdated = $conn-&gt;prepare("SELECT `slug_UN` FROM `users` WHERE `user_id` = :user_id"); $perfilUpdated-&gt;bindParam(':user_id', $user_id, PDO::PARAM_INT); $perfilUpdated-&gt;execute(); $rowPFUpdated = $perfilUpdated-&gt;fetch(PDO::FETCH_ASSOC); $SlgUSPFFetch = $rowPFUpdated['slug_UN']; $ext = explode('.',$_FILES['uploadedIMG']['name']); $extension = end($ext); //here i get the extension of the uploaded file, $newname = mt_rand(10000, 10000000); //generate a random name $folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension; //here i check if exist a file on the user's folder $imgUserPasta = glob($folderPFFetch.'avatar/*')[0] ?? NULL; // i don't remember why i made this variable, anyways it's not relevant, //you can just forget it $checkPathEdelet = $folderPFFetch.'avatar/'.($_FILES['uploadedIMG']['name']); $imagickWrite = 'C:/xampp/htdocs/site/user/'.$linkN.'/avatar/'.$newname.'_'.time().'.'.$extension; if($imgUserPasta != NULL &amp;&amp; $imgUserPasta != $checkPathEdelet){ unlink($imgUserPasta); } // here is how i'm 99% sure that i will get only valid images, if the uploaded image //is not valid it won't execute the Imagick code and will print out a error, but //i'm using a try/catch and this error won't appers $imgk = new Imagick($_FILES["uploadedIMG"]["tmp_name"]); $imgk-&gt;thumbnailImage(180, 180, true); $imgk-&gt;writeImage($imagickWrite); $imgUserPastaIMCK = glob($folderPFFetch.'avatar/*')[0] ?? NULL; if(file_exists($imgUserPastaIMCK)){ $avatar = $siteURL.'/'.$imgUserPastaIMCK; }else{ $avatar = $siteURL.'/img/avatar/'.$imgPF.'.jpg'; } echo json_encode(['avatar' =&gt; $avatar]); }catch(Exception $e){ // even if Imagick will only upload valid images, it's recommended to use other //ways to also validade images //so i have 3 "walls": // 1° - i check the mimetype with "finfo_open()", // 2° - i check if is a "valid" image with "getimagesize()" // 3° - Imagick will only upload valid images // if a user falls here on the "catch" block, i'm 100% sure that it's a "malicious" //user, so i made this query to delete his profile from my database, altrough it //don't give any protection against attackers, it will make their life a //bit harder, because they will need to create another account to try uploaded //malicious files to my server. // i know that there's ways to forge a user ID, i don't know if it can be possible //in my project because i don't generate ID when the user loge in, i store the user //ID on my database when they register the account, anyways i think that this DELETE //query will be better than nothing. $deleteProfile = $conn-&gt;prepare("DELETE FROM `users` WHERE `user_id` = :user_id"); $deleteProfile-&gt;bindParam(':user_id', $user_id, PDO::PARAM_INT); $deleteProfile-&gt;execute(); session_unset(); session_destroy(); echo json_encode(['delete' =&gt; 'true']); } } } } } $conn = null; ?&gt; </code></pre> <p>This is the code that is inside <code>success</code> on Ajax call, it's not related to security, because important things should be made on back-end, but i will put this code here just to you guys see how exactally my code works:</p> <pre><code>$('#imgUpload').change(function (event) { ... ... ... success: function (data){ var jsonPF = JSON.parse(data); if($.trim(jsonPF.delete)){ // if the data returned from //the profileIMGform.php contains the array 'delete', then //te page will be reloaded and the user will seen a error page, //with the mensage: "You need to be logged in to view this page" $("img.imgPform").css('opacity', '0.4'); $("#loadingIMG").show(); window.location = siteURL; }else{ $("#loadingIMG").hide(); $("img.imgPform").css('opacity', '1'); $(imgEdit).attr('src', jsonPF.avatar+'?'+ new Date().getTime()); if(window.matchMedia("screen and (max-width: 1172px)").matches) { $(imgEditMd).attr('src', jsonPF.avatar+'?'+ new Date().getTime()); }else if(window.matchMedia("screen and (min-width: 1173px)").matches) { $(imgEditMm).attr('src', jsonPF.avatar+'?'+ new Date().getTime()); } } } </code></pre>
[]
[ { "body": "<h3>Indentation</h3>\n\n<p>First of all, format your code wisely. Do not make your main program body shifted by <strong>five levels</strong> of indentation. It makes it awfully hard to read (and review, mind you). </p>\n\n<p>Fail early. If a condition makes the further code execution impossible - just make it throw an error and then keep writing the following code on the same level, like</p>\n\n<pre><code>require_once 'db.php';\n\nif(!empty($user_id)) {\n die(json_encode(['error' =&gt; 'Unauthorized']));\n}\n$user_id = $_SESSION['user_id'];\nif(empty($_FILES['uploadedIMG']['size'])) {\n die(json_encode(['error' =&gt; 'No file uploaded']));\n}\n</code></pre>\n\n<p>As you can see, here we made your code die early (but informative, so in case the code won't process the image you would have an idea why), and then continue from the same indentation level. </p>\n\n<h3>Code pollution</h3>\n\n<p>As you can see, I removed <strong>a lot</strong> of code from a mere few lines. It means there was a lot of code which is just useless. There are two reasons for this:</p>\n\n<ul>\n<li>What you wrote in the user id checking code could be called \"defensive programming\" but in reality it is not:\n\n<ul>\n<li>First of all, a defensive programming code should <strong>always raise an error</strong> if a condition is not met. While your code just silently bypasses it. So if ever a user id won't be int, you will just have no idea why your code suddenly stopped working. </li>\n<li>even a defensive programming should be justified. You can wrap every operator in a dozen conditions, but it will just make no sense. Use strict verifications only if there is a chance that a variable could be the wrong type. Assuming user_id coming from a database, I don't see how a non-empty one could be any other type than int.</li>\n</ul></li>\n<li>You don't take the surrounding code into consideration. For example,\n\n<ul>\n<li>you are checking the <code>$_SESSION['user_id']</code> variable twice. Why? One condition is enough, then just assign it to a variable.</li>\n<li>this one is rather tricky but <code>$_FILES['uploadedIMG']['size']</code> will be empty if <code>$_SERVER['REQUEST_METHOD']</code> is not 'POST'. So it makes the latter superfluous. </li>\n</ul></li>\n</ul>\n\n<p>So just remember - the more code you write, the harder it is to read and the more errors you introduce. </p>\n\n<h3>Security</h3>\n\n<p>Like it often happens, while trying to do \"the most secure way\" you are overreacting. Most of your verification code is just duplicates itself. For example, <code>getimagesize()</code> would use the same mechanism as fileinfo. So just one call is enough. </p>\n\n<p>At the same time, there is an <strong>open vulnerability</strong>. Your web-server doesn't judge your files by whatever \"mime type\" but by the extension. In means that if an image file will have a .php extension, a web-server will try to run it as a PHP file, not serve it as an image file. So, security-wise all your numerous mime-type checks are rather useless while <strong>the only real protection is missing.</strong></p>\n\n<h3>You must verify the file extension against a while list</h3>\n\n<pre><code>$allowedExts = array('png', 'jpeg', 'jpg', 'gif');\n$ext = pathinfo($name, PATHINFO_EXTENSION);\nif( !in_array($ext, $allowedExts) )\n{\n die(json_encode(['error' =&gt; 'invalid image format'));\n}\n</code></pre>\n\n<p>this one, given you are renaming the files, will be the real protection.</p>\n\n<h3>Innocent users' experience</h3>\n\n<p>It is very important not to spoil the innocent users' experience in pursue for the imaginary security. And you are outright deleting a user account if their image upload failed, which is gross. Imagine your frustration as are an active member for several years who just accidentally uploaded a broken image, like sometimes our cameras produce. Then out of the blue you have your account deleted! </p>\n\n<p>At the same time, as you admit yourself, it \"don't give any protection against attackers\"! The consequences are just incomparable! So this approach won't offer any real protection but could ruin the whole site. </p>\n\n<blockquote>\n <p>There was an old short story from the great science fiction writer Robert Sheckley, \"Ghost V\". Arnold, the main character, was trapped in the space ship with nightmares. On one occasion, he had to keep the lights on, but but wast tricked into believe that some creatures are attacking the lights. So he shot on them and as a result shot all the lights off!</p>\n</blockquote>\n\n<p>Don't be like Arnold, do not shoot your users off only to \"make an attacker's life a bit harder\".</p>\n\n<h3>Better user experience</h3>\n\n<p>It is considered a standard to let a user know what is their fault. So don't just return an empty response but tell a user what's wrong.</p>\n\n<pre><code>if (filesize($_FILES[\"uploadedIMG\"][\"tmp_name\"]) &gt; 768000){\n die(json_encode(['error' =&gt; 'File is too big']));\n}\n</code></pre>\n\n<h3>Error reporting</h3>\n\n<blockquote>\n <p>i'm using a try/catch and this error won't appear</p>\n</blockquote>\n\n<p>Here you are outright wrong. PHP has a designated setting that prevents errors from appearing. And it should be set to OFF on a live site. While in the program code there should be no operators responsible for this task. Please refer to my article on <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"noreferrer\">PHP error reporting</a> for the further explanation.</p>\n\n<p>However, as image processing error is a deliberately recoverable error, you can just inform the user and let it go.</p>\n\n<h3>The refactored code.</h3>\n\n<p>To be honest, I was unable to understand the whole affair with the image name, but as far as I can tell there was an awful lot of code that is either duplicated or not used at all. So, assuming there could be just one avatar, I decided to make its name static.</p>\n\n<pre><code>&lt;?php\nrequire_once 'db.php';\n\nif(!empty($user_id)) {\n die(json_encode(['error' =&gt; 'Unauthorized']));\n}\n$user_id = $_SESSION['user_id'];\nif(empty($_FILES['uploadedIMG']['size'])) {\n die(json_encode(['error' =&gt; 'No file uploaded']));\n}\n//Image verifications\n$size = getimagesize($_FILES[\"uploadedIMG\"][\"tmp_name\"]);\nif (!$size) {\n die(json_encode(['error' =&gt; 'Unrecognized file format']));\n}\nif (filesize($_FILES[\"uploadedIMG\"][\"tmp_name\"]) &gt; 768000){\n die(json_encode(['error' =&gt; 'File is too big']));\n}\n$allowedExts = array('png', 'jpeg', 'jpg', 'gif');\n$ext = pathinfo($name, PATHINFO_EXTENSION);\nif( !in_array($ext, $allowedExts) )\n{\n die(json_encode(['error' =&gt; 'invalid image format']));\n}\n// saving the image\n$imagePath = \"/user/{$_SESSION['linkN']}/avatar/avatar.$ext\";\n$imagickWrite = $_SERVER['DOCUMENT_ROOT'].$imagePath;\ntry {\n $imgk = new Imagick($_FILES[\"uploadedIMG\"][\"tmp_name\"]);\n $imgk-&gt;thumbnailImage(180, 180, true);\n $imgk-&gt;writeImage($imagickWrite);\n} catch (ImagickException $e){\n die(json_encode(['error' =&gt; 'Error processing the image']));\n}\necho json_encode(['avatar' =&gt; $imagePath]);\n</code></pre>\n\n<p>Note that you should amend your client side code in order to make it process errors returned.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T19:32:04.373", "Id": "408823", "Score": "0", "body": "`accidentally uploaded a broken image` I think i got what you said about the `DELETE` query. But this `broken` image will pass the `getimagesize()` condition?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T19:44:30.743", "Id": "408825", "Score": "0", "body": "What about the ImageMagick? the guy bellow said that if someone modify the headers of the image (inserting some code inside the image) it will be uploaded successfully to my server. Should i use GD to read the file and create a new one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T20:05:54.037", "Id": "408828", "Score": "0", "body": "This is what i should do https://stackoverflow.com/a/18948152/10443076 ? There's some ways to disable execution of scripts on a folder, as you can see on the other answears in this link." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T10:31:06.690", "Id": "211410", "ParentId": "211397", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T23:12:20.560", "Id": "211397", "Score": "3", "Tags": [ "php", "security", "image", "ajax" ], "Title": "Upload a user's avatar" }
211397