body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>We've just finished learning about queues in my data structures class; I want to make sure I really understand it. I'm still feeling a bit lost on how to optimize the data use of a queue. I've created a little program here:</p> <pre><code>#include &lt;iostream&gt; class Queue{ public: Queue(int size = 10){ ptr = new int[size]; head = counter = 0; qSize = size; } void push(int value){ if(counter == qSize) doubleSize(); ptr[counter++] = value; } int pop(){ if(counter == 0){ std::cout &lt;&lt; "The queue is empty!!! \n"; return -1; } if(head &gt;= counter - 1){ int temp = ptr[head]; std::cout &lt;&lt; "This is the last item in the queue. \n"; delete[] ptr; ptr = new int[qSize]; head = counter = 0; return temp; } return ptr[head++]; } private: int *ptr; int head; int counter; int qSize; void doubleSize(){ int prevSize = qSize; qSize *= 2; int *temp = new int[qSize]; for(int i = 0; i &lt; prevSize; i++){ temp[i] = ptr[i]; } delete[] ptr; ptr = temp; } }; </code></pre> <p>So, as you can test, the program runs fine; but what I'm looking for is how I can optimize my queues to be as efficient as possible. I.E. Is there a specific way that I should be programming these queues that uses the minimum amount of data, and has the smallest Order complexity?</p> <p>P.S. I am aware that there is a queue library. I am more seeking to optimize how I program out queues themselves.</p>
[]
[ { "body": "<p>It would be a good idea for the <code>Queue</code> class to offer a <code>.size()</code> method, so that the caller can avoid popping an empty queue.</p>\n\n<p>While your memory-management technique will work, it is not efficient. If you repeatedly push and pop elements, you'll end up reallocatin...
{ "AcceptedAnswerId": "205859", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T21:12:09.220", "Id": "205853", "Score": "5", "Tags": [ "c++", "performance", "reinventing-the-wheel", "queue" ], "Title": "A queue implemented using an array" }
205853
<p>Simple variadic function implementation in NASM Assembly. When implemented like I have below:</p> <p><strong>sum.asm</strong></p> <pre><code>;; bits 64 default rel extern printf section .text global main global sum main: sub rsp, 40 mov r9d, 3 mov r8d, 2 mov edx, 1 mov ecx, 3 call sum lea rcx, [fmt] mov edx, eax call printf xor eax, eax add rsp, 40 ret sum: sub rsp, 24 test ecx, ecx mov qword [rsp+28H], rdx lea rdx, [rsp+28H] mov qword [rsp+30H], r8 mov qword [rsp+38H], r9 mov qword [rsp+8H], rdx jle .end lea eax, [rcx-1H] lea rcx, [rsp+rax*8+30H] xor eax, eax .recurse: add eax, dword [rdx] add rdx, 8 cmp rdx, rcx jnz .recurse add rsp, 24 ret .end: xor eax, eax add rsp, 24 ret %macro str 2 %2: db %1, 0 %endmacro section .rdata str "%d", fmt </code></pre> <p>We can change how many variables are being given to the function without having to change the amount of memory being allocated to the function itself.</p> <pre><code>main: sub rsp, 72 mov dword [rsp+30H], 6 mov dword [rsp+28H], 5 mov dword [rsp+20H], 4 mov r9d, 3 mov r8d, 2 mov edx, 1 mov ecx, 6 call sum lea rcx, [fmt] mov edx, eax call printf xor eax, eax add rsp, 72 ret </code></pre> <p>There are no comments in the code since what I'm doing should be pretty self-explanatory. Any advice and all topical comments on optimizing the code and its performance, as well as standard conventions, is appreciated!</p> <p>Compiled as follows using <code>VS2017 x64 Native Tools Command Prompt</code>:</p> <blockquote> <pre><code>&gt; nasm -g -f win64 sum.asm &gt; cl /Zi sum.obj msvcrt.lib legacy_stdio_definitions.lib </code></pre> </blockquote>
[]
[ { "body": "\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov qword [rsp+8H], rdx\n</code></pre>\n</blockquote>\n\n<p>Why would you store this value at all? You never use the stored value afterwards!</p>\n\n<p>You can easily dismiss all of the local storage for the <em>sum</em> routin...
{ "AcceptedAnswerId": "205988", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T22:03:00.810", "Id": "205856", "Score": "1", "Tags": [ "windows", "assembly", "variadic" ], "Title": "Variadic Functions in NASM Win64 Assembly" }
205856
<p>I am fetching the friend list for a chat application using a Vuex store. I need to dispatch the getter via an interval. Is there a best practices way to do this?</p> <pre><code>&lt;template&gt; &lt;aside class="friend-list"&gt; &lt;h5 class="whos-online"&gt;Who's Online&lt;/h5&gt; &lt;ul class="users"&gt; &lt;UserListItem v-for="user in friendList" :user="user" :key="user.user_id" /&gt; &lt;/ul&gt; &lt;/aside&gt; &lt;/template&gt; &lt;script&gt; import UserListItem from './UserListItem' import { mapGetters } from 'vuex' export default { name: 'FriendList', components: { UserListItem, }, created() { this.fetchFriendList() setInterval(this.fetchFriendList, 3000) }, destroy() { clearInterval(this.fetchFriendList) }, methods: { fetchFriendList() { console.log(this.friendList) this.$store.dispatch('chat/fetchFriendList') } }, computed: mapGetters({ friendList: 'chat/friendList' }), } &lt;/script&gt; </code></pre>
[]
[ { "body": "<h2>Responding to your question</h2>\n\n<blockquote>\n <p>Is there a best practices way to [dispatch the getter via an interval]?</p>\n</blockquote>\n\n<p>You could consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\" rel=\"nofollow noreferrer\"><c...
{ "AcceptedAnswerId": "207502", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T22:27:50.567", "Id": "205858", "Score": "1", "Tags": [ "javascript", "ecmascript-6", "html5", "timer", "vue.js" ], "Title": "Dispatching Vuex getter via setInterval" }
205858
<p>I wrote a small vector with a few lines of unsafe Rust.</p> <p>The idea is to have a vector, which can be read from simultaneously, but it needs the ability to grow. To realize that, the storage is organized in pages. As page, I use <a href="https://crates.io/crates/arrayvec" rel="nofollow noreferrer">arrayvec</a>:</p> <pre><code>const ELEMENTS_PER_PAGE: usize = 1024; type Page&lt;T&gt; = ArrayVec&lt;[T; ELEMENTS_PER_PAGE]&gt;; </code></pre> <p>The main problem is, when putting those pages in a <code>Vec</code>, the access may gets invalidated, while pushing to the vector. To solve this, I have an array of <code>*mut Page&lt;T&gt;</code> (so basically <code>Vec&lt;Box&lt;Page&lt;T&gt;&gt;&gt;</code>) and another pointer which points to this array: <code>*mut *mut Page&lt;T&gt;</code>. When adding pages, the vector will be copied without cloning the Pages (this is why I need the raw pointer). Now the <code>*mut *mut</code> ptr will be updated to the new vector and everyone will be headed to the correct memory.</p> <p>As a small optimization, I use <code>Box&lt;[_]&gt;</code> instead of <code>Vec</code>, since the <code>Vec</code> will never grow directly:</p> <pre><code>pub struct ConstVec&lt;T&gt; { // storage, which holds the actual pages pages: Mutex&lt;Box&lt;[*mut Page&lt;T&gt;]&gt;&gt;, // points to the storage. Used for wait-free access. pages_pointer: AtomicPtr&lt;*mut Page&lt;T&gt;&gt;, len: AtomicUsize, } </code></pre> <p>We need two helper functions to get the indices for the page and the element in a specific page:</p> <pre><code>const fn page_index(index: usize) -&gt; usize { index / ELEMENTS_PER_PAGE } const fn element_index(index: usize) -&gt; usize { index % ELEMENTS_PER_PAGE } </code></pre> <p>and a <code>len</code> method:</p> <pre><code>pub fn len(&amp;self) -&gt; usize { self.len.load(atomic::Ordering::Acquire) // 1 } </code></pre> <p>This is the function for pushing into the vector:</p> <pre><code>pub fn push(&amp;self, value: T) { let mut pages = self.pages.lock().unwrap(); let index = self.len.load(atomic::Ordering::Acquire); // 1 let page_index = Self::page_index(index); // do we need an new page? if page_index == pages.len() { // allocate a new vector, which will replace the old one // and copy old elements into it. let mut new_pages = Vec::with_capacity(page_index + 1); new_pages.extend(pages.iter().cloned()); new_pages.push(Box::into_raw(Box::new(Page::new()))); // 2 // Update the pages pointer first. This will be used // to receive data. The pointers remains valid. self.pages_pointer .store(new_pages.as_mut_ptr(), atomic::Ordering::SeqCst); // 1 // replace "vector" mem::replace(pages.deref_mut(), new_pages.into_boxed_slice()); } unsafe { (*pages[page_index]).push(value); // 2 } self.len.store(index + 1, atomic::Ordering::Release); // 1 } </code></pre> <p>And of course we need to implement <code>Drop</code>:</p> <pre><code>fn drop(&amp;mut self) { for page_ptr in self.pages.lock().unwrap().iter() { unsafe { Box::from_raw(*page_ptr) }; // 2 } } </code></pre> <p>Now two questions came up (see the code numbers for references):</p> <ol> <li><p>Am I using the right <code>Ordering</code> for atomic access? If I see correctly, I can use <code>Acquire</code>/<code>Release</code> everywhere but in storing the <code>pages_pointer</code>. This needs to be <code>SeqCst</code>, because it would be fatal, if the <code>mem::replace</code> would be executed before (the old pointer would dangle). Also I don't thing, <code>Relaxed</code> can be used anywhere here. Are my assumptions correct?</p></li> <li><p>Are those <code>unsafe</code> actually safe? </p></li> </ol> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2015&amp;gist=da87e47a287c4711628d69373187a1ae" rel="nofollow noreferrer">playground</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T01:22:47.043", "Id": "205862", "Score": "3", "Tags": [ "rust", "vectors", "lock-free", "atomic" ], "Title": "A multithreaded, growable vector with immutable elements, which has wait-free reads" }
205862
<p>I am learning algorithms and have implemented the <a href="https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm" rel="nofollow noreferrer">Rabin-Karp</a> string search algorithm. I didn't implement a rolling <code>HashCode</code>, but it's judged correct by <a href="https://leetcode.com/problems/implement-strstr" rel="nofollow noreferrer">this online judge</a>.</p> <p>It's slower than the <code>str.indexOf()</code> implementation (7ms, compared to 4 ms). Can this be improved? What is the time complexity for this?</p> <pre><code>class Solution { public int strStr(String haystack, String needle) { if (haystack == null || needle == null) return -1; int needleHash = hashCode(needle); int plen = needle.length(); boolean t = true; int tlen = haystack.length() - needle.length() + 1; for (int i = 0; i &lt; tlen; i++) { String sub = haystack.substring(i, plen + i); int haystackHash = hashCode(sub); if (haystackHash == needleHash) { for (int j = 0; j &lt; plen; j++) { char[] charN = needle.toCharArray(); char[] charH = sub.toCharArray(); if (charN[j] != charH[j]) { t = false; } } if (t == true) { return i; } } } return -1; } public int hashCode(String value) { int h = 777; if (value.length() &gt; 0) { char val[] = value.toCharArray(); for (int i = 0; i &lt; val.length; i++) { h = 31 * h + val[i]; } } return h; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T06:53:56.323", "Id": "397115", "Score": "3", "body": "Do you have some tests that show it produces correct results? It would be useful to include them with the code, for the benefit of reviewers." }, { "ContentLicense": "CC...
[ { "body": "<p>You're missing the essential benefit of using a rolling hash:</p>\n<pre><code>for (int i = 0; i &lt; tlen; i++) {\n String sub = haystack.substring(i, plen + i);\n int haystackHash = hashCode(sub);\n</code></pre>\n<p>Here, we examine <strong><code>plen</code></strong> characters of <code>hay...
{ "AcceptedAnswerId": "205892", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T02:59:31.587", "Id": "205866", "Score": "0", "Tags": [ "java", "algorithm", "strings", "search" ], "Title": "Rabin-Karp String matching" }
205866
<p>I've come across a simple challenge: given a phrase, check if we can form the given word vertically by stacking words in rows. For example, we can form the word <code>"boom"</code> from this phrase:</p> <p>&nbsp;&nbsp;&nbsp;every <strong>b</strong>reath<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;y<strong>o</strong>u take<br> every m<strong>o</strong>ve<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;you <strong>m</strong>ake<br></p> <p>My Python code:</p> <pre><code>def can_spell(s, w): words = s.split() words_iter = iter(words) for char in w: try: next_word = next(words_iter) while char not in next_word: next_word = next(words_iter) except StopIteration: return False return True print(can_spell('every breath you take every move you make', 'boom')) # True </code></pre> <p>Is this the most efficient way to do it?</p>
[]
[ { "body": "<p>Staying close to your original appraoch, you could use another <code>for</code> loop with an <code>else</code> instead of <code>try/except</code> and <code>while</code>. The <code>else</code> is triggered when the inner loop has ended normally, without the <code>break</code>, i.e. when there are n...
{ "AcceptedAnswerId": "205882", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T08:14:25.750", "Id": "205876", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "strings" ], "Title": "Check if we can form a word across words in a sentence" }
205876
<p>I am trying to find the best way(/most efficent way) to setup my console program's menu. The way I have it set up is that I have a Menu class and then I use a menu pointer called currentMenu and I just change where it is pointing to. it runs fairly well so far but I'd like to know what I could do to improve it</p> <p>So Far it is seperated into 3 files(main.cpp,menu.h and menu.cpp) Full Code is here: <a href="https://repl.it/@SamuelHabtu/StudyBuddy-CLI" rel="noreferrer">https://repl.it/@SamuelHabtu/StudyBuddy-CLI</a></p> <p>Menu.h:</p> <pre><code>#ifndef MENU_H #define MENU_H #include &lt;iostream&gt; #include &lt;string&gt; class menu { public: std::string name; menu *prev; menu *right; menu *down; menu *up; void displayMenu(); }; #endif </code></pre> <p>Menu.cpp:</p> <pre><code>#include "menu.h" void menu::displayMenu() { std::string userInput; std::cout&lt;&lt;name&lt;&lt;" menu:\n"; if(prev != 0) { std::cout&lt;&lt;"0:"&lt;&lt;prev-&gt;name&lt;&lt;" menu\n"; } if(up != 0) { std::cout&lt;&lt;"1:"&lt;&lt;up-&gt;name&lt;&lt;" menu\n"; } if(down != 0) { std::cout&lt;&lt;"2:"&lt;&lt;down-&gt;name&lt;&lt;" menu\n"; } if(right != 0) { std::cout&lt;&lt;"3:"&lt;&lt;right-&gt;name&lt;&lt;" menu\n"; } } </code></pre> <p>Here is the function that I use to "fill" each menu</p> <pre><code>void buildMenu(menu *menu,std::string name,class menu *prev,class menu* up,class menu* down,class menu* right) { menu-&gt;name = name; menu-&gt;prev = prev; menu-&gt;right = right; menu-&gt;down = down; menu-&gt;up = up; } </code></pre> <p>This is How I am handling the Userinputs:</p> <pre><code>bool valid(std::string userInput,menu *currentMenu) { if(userInput != "1" &amp;&amp; userInput != "2" &amp;&amp; userInput != "3" &amp;&amp; userInput != "0") { std::cout&lt;&lt;"invalid input \n"; return false; } if(userInput == "0" &amp;&amp; currentMenu-&gt;prev == 0) { std::cout&lt;&lt;"invalid input \n"; return false; } if(userInput == "1" &amp;&amp; currentMenu-&gt;up == 0) { std::cout&lt;&lt;"invalid input \n"; return false; } if(userInput == "2" &amp;&amp; currentMenu-&gt;down == 0) { std::cout&lt;&lt;"invalid input \n"; return false; } if(userInput == "3" &amp;&amp; currentMenu-&gt;right == 0) { std::cout&lt;&lt;"invalid input \n"; return false; } return true; } </code></pre> <p>mainloop for the menu statemachine:</p> <pre><code> while(go) { currentMenu-&gt;displayMenu(); std::cin&gt;&gt;userInput; while(!valid(userInput,currentMenu)|| (userInput.size() &gt; 1)) { std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),'\n'); std::cin&gt;&gt;userInput; } switch(userInput[0]) { case '0': currentMenu = currentMenu-&gt;prev; break; case '1': currentMenu = currentMenu-&gt;up; break; case '2': currentMenu = currentMenu-&gt;down; break; case '3': currentMenu = currentMenu-&gt;right; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T15:00:12.540", "Id": "397167", "Score": "0", "body": "It's missing a lot of context. Could you post the full `main.cpp` here to give reviewers a better idea of how you intend to use this?" } ]
[ { "body": "<h2>Use a constructor to initialize class variables</h2>\n\n<p>Your function <code>buildMenu()</code> looks like it is just initializing all the members of a class <code>menu</code>. That is normally the task of a constructor. So why not write:</p>\n\n<pre><code>class menu\n{\n public:\n ...\n ...
{ "AcceptedAnswerId": "205913", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T09:51:50.383", "Id": "205884", "Score": "6", "Tags": [ "c++", "console", "state-machine" ], "Title": "C++ CLI Console Menu Statemachine" }
205884
<p>Here is my code for a class that is responsible for managing some common users task like registration, login and logout. It implements also a sub class that can be used to check the session of a logged in user. I've tested it and works fine, but I will improve it as soon as I can. Any suggestion on security improvements are appreciated. </p> <pre><code>&lt;?php require_once 'config.php'; Interface UserInterface{ public function createUser(array $args); public function loginUser(array $args); public function logoutUser(); } class User Implements UserInterface{ private $db; private $stmt; private $email; private $username; private $password; private $id; private $sessioncode; private $args; /* * @param $db must be a PDO instance * */ public function __construct(\PDO $db){ $this-&gt;db = $db; } /* * @param $args must be a key/value array * */ public function createUser(array $args){ if($this-&gt;checkEmail($args['email'])){ #header("HTTP/1.1 400 Email already exsist"); #http_response_code(400); echo 'Email address already exsist.'; } elseif($this-&gt;checkUsername($args['username'])){ #header("HTTP/1.1 400 Username already exsist"); #http_response_code(400); echo 'Username already exsist.'; } else { $this-&gt;password = password_hash($args['password'], PASSWORD_BCRYPT); $stmt = $this-&gt;db-&gt;prepare('INSERT INTO _users (email, username, password) VALUES (?, ?, ? )'); if($stmt-&gt;execute(array($args['email'],$args['username'],$this-&gt;password))){ echo 'Account successful created'; } } } /* * @param $args must be a key/value array * */ public function loginUser(array $args){ $stmt = $this-&gt;db-&gt;prepare('SELECT id,username,password FROM _users WHERE username = ?'); $stmt-&gt;execute(array($args['username'])); $result = $stmt-&gt;fetch(PDO::FETCH_OBJ); if(count($result) &gt; 0 &amp;&amp; password_verify($args['password'], $result-&gt;password)){ UserSessionHelper::setSession($result-&gt;username, $result-&gt;id); #header('HTTP/1.1 200'); echo 'Logged in'; } else { echo 'Wrong username or password'; #header('HTTP/1.1 400'); } } /* * This method wehn called will logout an user * */ public function logoutUser(){ UserSessionHelper::unsetSession(); header('HTTP/1.1 200'); #header('Location: '); #echo 'Logged out'; } /* * @param $email is a key part of the $args array; * This method will check if a given email is already registered. */ private function checkEmail($email){ $stmt = $this-&gt;db-&gt;prepare('SELECT email FROM _users WHERE email = ?'); $stmt-&gt;execute(array($email)); $result = $stmt-&gt;fetch(PDO::FETCH_OBJ); if(count($result) &gt; 0){ return true; } } /* * @param $username is a key part of the $args array; * This method will check if a given username is already registered. */ private function checkUsername($username){ $stmt = $this-&gt;db-&gt;prepare('SELECT username FROM _users WHERE username = ?'); $stmt-&gt;execute(array($username)); $result = $stmt-&gt;fetch(PDO::FETCH_OBJ); if(count($result) &gt; 0){ return true; } } } interface UserSessionHelperInterface{ public static function unsetSession(); public static function setSession(string $username, int $user_id); public static function validateSessionID(string $session_id, string $session_hash); } class UserSessionHelper implements UserSessionHelperInterface{ private $session_hash; private $username; private $user_id; /* * @params $username must be a string, $user_id must be an integer. * This method will register the $_SESSION variables when an user login. */ public static function setSession(string $username,int $user_id){ $_SESSION['session_'] = self::sessionHash(); $_SESSION['id_'] = $user_id; $_SESSION['username_'] = $username; return true; } /* * @param * This method will remove all $_SESSION data wehn an user logout. */ public static function unsetSession(){ session_destroy(); session_unset(); } /* * @params $session_id must be a valid string, $session_hash must be a valid string. * This method will check for valid session credentials when an user is logged in. */ public static function validateSessionID(string $session_id,string $session_hash){ $computed_session_hash = hash('sha384', $session_id); if(!preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) &gt; 0){ #return header('HTTP/1.1 403'); } elseif(!hash_equals($computed_session_hash, $session_hash)){ #return header('HTTP/1.1 403'); } else{ return true; } } /* * This method is responsable to hash the regenerated session id, then return it * */ private function sessionHash(){ session_regenerate_id(); $session_hash = hash('sha384', session_id()); return $session_hash; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T08:10:18.343", "Id": "398442", "Score": "0", "body": "Would `validateSessionID()` not get `$session_id` and `$session_hash` from `session_id()` and `$_SESSION['session_']`? Why have them as method arguments, if this is the case?" ...
[ { "body": "<ul>\n<li><p>For session management, you might want to take a look at <a href=\"http://php.net/manual/ru/class.sessionhandlerinterface.php\" rel=\"nofollow noreferrer\"><code>SessionHandlerInterface</code></a>. Generally, your class can handle it all, but further on - you can set custom session data ...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T10:23:51.997", "Id": "205888", "Score": "2", "Tags": [ "php", "object-oriented", "authentication", "pdo", "session" ], "Title": "PHP User management class" }
205888
<p>Something I've found myself having to do reasonably often is map properties from an Object (usually a heavily nested MongoDB document) to a different 'shape' to then pass it to a function call or API endpoint etc. Combine this with a development environment in which these 'shapes' are prone to change and it felt messy to do the mapping manually each time (though learning object destructuring often made it much neater!).</p> <p>I've written this code to accept two arrays containing key names, an object and a delimiter option. The function then returns an object containing the properties pointed to by the keys in the input array, but with the key names as specified in the output array.</p> <pre><code>const transposeObjectByArraysOfPairs = (input, output, object, delimiter = '.') =&gt; { const toReturn = {}; input.map((keyString, idx) =&gt; { const keysIn = keyString.split(delimiter); // copy object to avoid mutating original let _currentProp = Object.assign({}, object); for (let i = 0; i &lt; keysIn.length; i++) { _currentProp = _currentProp[keysIn[i]]; } const keysOut = output[idx].split(delimiter); let len = keysOut.length; let _obj = {[keysOut[len - 1]]: _currentProp}; for (let j = len - 2 ; j &gt;= 0; --j) { _obj = {[keysOut[j]]: _obj}; } Object.assign(toReturn, _obj); }); return toReturn; }; const object = {a : {b: { c: 10, d: 30 }}}; const input = ['a.b.c', 'a.b.d']; const output = ['A.B', 'B.C']; console.log(misc.transposeObjectByArraysOfPairs(input, output, object)); // { A: { B: 10 }, B: { C: 30 } } </code></pre> <p>Whilst this function has neatened up chunks of my code significantly, I can't help but feel there's a neater way to do this. Iterating through an array of keys to get to the desired property feels quite hacky in particular.</p> <p>In a perfect world I think I'd essentially have a function that mapped from one object schema to another and then I could simply maintain schema and know that if I made changes, I wouldn't need to modify the code that did the mapping.</p>
[]
[ { "body": "<p>Maybe I don't understand the question exactly, but what's stopping you from just creating a function to do the mapping, like this:</p>\n\n<pre><code>function obj1ToObj2(obj1){\n return {\n A: {\n B: obj1.a.b.c\n },\n B: {\n C: obj1.a.b.d\n }\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T11:41:40.120", "Id": "205890", "Score": "0", "Tags": [ "javascript", "algorithm", "ecmascript-6", "mongoose" ], "Title": "Mapping properties between two Objects of different structure" }
205890
<p>I've taken on the challenge of modeling a simple User Voice-like system. High-level description:</p> <ul> <li>It's a portal for some SaaS users;</li> <li>They come and leave feature requests, suggestions, etc.;</li> <li>They should be able to vote/unvote for any suggestions;</li> <li>They can leave as many comments as they like on suggestions;</li> <li>Comments may be removed by the owner, but may not be edited.</li> </ul> <p>I've modeled the domain as follows, using a DDD approach. Please advise about mistakes, warnings, improvements, etc.</p> <p>I've also applied the advices from these posts:</p> <ul> <li><a href="http://udidahan.com/2009/06/29/dont-create-aggregate-roots/" rel="nofollow noreferrer">Don't create aggregate roots</a></li> <li><a href="https://gedgei.wordpress.com/2016/10/19/creating-new-aggregates-in-ddd/" rel="nofollow noreferrer">Creating new aggregates in DDD</a></li> <li><a href="https://enterprisecraftsmanship.com/2016/03/08/link-to-an-aggregate-reference-or-id/" rel="nofollow noreferrer">Link to an aggregate: reference or Id?</a></li> </ul> <pre class="lang-cs prettyprint-override"><code>public abstract class Entity { public Guid Id { get; protected set; } = Guid.NewGuid(); } public class User : Entity // Aggregate Root { public string Key =&gt; $"{Email}:{MarketplaceUrl}"; public string Name { get; } public string Email { get; } public string MarketplaceName { get; } public Uri MarketplaceUrl { get; } internal User(string name, string email, string marketplaceName, Uri marketplaceUrl) { Name = name; Email = email; MarketplaceName = marketplaceName; MarketplaceUrl = marketplaceUrl; } public Suggestion MakeSuggestion(string text) { return new Suggestion(this, text); } } public class Suggestion : Entity // Aggregate Root { public string Text { get; /* a suggestion cannot be altered */ } public User ByUser { get; } public DateTime SuggestedAt { get; } public ICollection&lt;Comment&gt; Comments { get; } = new List&lt;Comment&gt;(); public ICollection&lt;Vote&gt; Votes { get; } = new List&lt;Vote&gt;(); internal Suggestion(User byUser, string text) { ByUser = byUser; Text = text; SuggestedAt = DateTime.UtcNow; } public Comment AddComment(User byUser, string text) { var comment = new Comment(byUser, text); Comments.Add(comment); return comment; } public void RemoveComment(Comment comment, User userRemovingComment) { Comments.Remove(comment); } public void Unvote(User byUser) { var vote = Votes.SingleOrDefault(v =&gt; v.ByUser == byUser)); if (vote != null) Votes.Remove(vote); } public Vote Vote(User byUser) { if (Votes.Any(v =&gt; v.ByUser == byUser)) throw new CannotVoteTwiceOnSameSuggestionException(); var vote = new Vote(byUser); Votes.Add(vote); return vote; } } public class Comment : Entity { public string Text { get; /* a comment cannot be changed */ } public User ByUser { get; } public DateTime CommentedAt { get; } internal Comment(User byUser, string text) { ByUser = byUser; Text = text; CommentedAt = DateTime.UtcNow; } } public class Vote : Entity { public User ByUser { get; } public DateTime VotedAt { get; } internal Vote(User byUser) { ByUser = byUser; VotedAt = DateTime.UtcNow; } } public interface IUserVoiceStore { Task AddUserAsync(User user); Task AddSuggestionAsync(Suggestion suggestion); Task&lt;Suggestion&gt; GetSuggestionAsync(Guid id); Task&lt;User&gt; GetUserAsync(Guid id); // For when comments and votes are added/removed to/from a suggestion. Task UpdateSuggestionAsync(Suggestion suggestion); } public class UserVoiceService { private readonly IUserVoiceStore store; public UserVoiceService(IUserVoiceStore store) { this.store = store; } public async Task&lt;User&gt; RegisterUserAsync(string name, string email, string marketplaceName, Uri marketplaceUrl) { var user = new User(name, email, marketplaceName, marketplaceUrl); await store.AddUserAsync(user); return user; } } public class CannotVoteTwiceOnSameSuggestionException : Exception { } public class CannotRemoveCommentFromAnotherUserExcetion : Exception { } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T14:04:59.603", "Id": "397159", "Score": "0", "body": "You are not using the `CannotRemoveComment...Exception` anywhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T16:18:40.980", "Id": "397176...
[ { "body": "<p>The design looks solid, a few thoughts though:</p>\n\n<ul>\n<li><p>I would split <code>IUserVoiceStore</code> into more granular <code>UserRepository</code> and <code>SuggestionRepository</code>. Also, <code>UpdateSuggestionAsync()</code> seems to indicate you can only update a suggestion and noth...
{ "AcceptedAnswerId": "205894", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T12:08:41.677", "Id": "205891", "Score": "2", "Tags": [ "c#", "ddd" ], "Title": "DDD modeling for a User Voice-like system" }
205891
<p>I'm writing an Azure function using Visual Studio (multi-layers project), where I'm managing all Azure ServiceBus related code in one class.</p> <p>(<a href="https://codereview.stackexchange.com/questions/205979/servicebus-queueclient-and-topicclient-object-resue">follow-up</a>)</p> <pre><code>public class MessageBroker : IMessageBroker, IDisposable { private readonly IAppConfiguration appConfiguration; private TopicClient topicClient; private QueueClient queueClient; public MessageBroker(IAppConfiguration appConfiguration) { this.appConfiguration = appConfiguration; } public async Task SendMessageToQueueAsync(string queueName, string message) { this.queueClient = QueueClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, queueName); BrokeredMessage brokeredMessage = new BrokeredMessage(message); await queueClient.SendAsync(brokeredMessage); } public async Task SendMessageToTopicAsync(string topicName, string message) { this.topicClient = TopicClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, topicName); BrokeredMessage brokeredMessage = new BrokeredMessage(message); await topicClient.SendAsync(brokeredMessage); } public void Dispose() { this.queueClient.Close(); this.topicClient.Close(); } } </code></pre> <p>I use the <code>[Inject]</code> attribute to use DI in the Azure function. Whenever I need to send any message into a queue or topic, I inject <code>IMessageBroker</code> and call thr <code>SendMessageToQueueAsync</code> method. I see a Microsoft recommendation <a href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements" rel="nofollow noreferrer">here</a> to reuse <code>QueueClient</code> and <code>TopicClient</code>.</p> <p><code>IMessageBroker</code> is Singleton in my DI configuration.</p> <p>Will the <code>QueueClient.CreateFromConnectionString</code> method create a new object every time or reuse a connection internally based on the same <code>ConnectionString</code> or queuename?</p> <p>Is there anything I can do better on this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T07:44:51.730", "Id": "397268", "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 y...
[ { "body": "<p>Having <code>topicClient</code> and <code>queueClient</code> as class fields is unnecessary here, and potentially leads to exception scenarios.</p>\n\n<p>For example, if you were to create a new <code>MessageBroker</code> and immediately call <code>Dispose()</code> without first calling both the o...
{ "AcceptedAnswerId": "205961", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T13:12:01.243", "Id": "205896", "Score": "1", "Tags": [ "c#", "azure" ], "Title": "ServiceBus QueueClient and TopicClient object resue" }
205896
<p>I'm beginning the long process of developing an Adventure Game/RPG and I was hoping to get some review on a resource system I'm coming up with. How it works is, a resource is generic to every resource in the world. Each resource will have a name, a random yield, and a random quality. So I've created an interface for the generic properties and function each resource will have.</p> <p><strong>Interface</strong></p> <pre><code>public interface IResource{ string Name {get;set;} string Quality {get;set;} int Yield{get;set;} string ConvertQualityToString(); int GetResourceYield(); } </code></pre> <p>Then I implement the interface in an actual resource base class.</p> <p><strong>Implementation</strong></p> <pre><code>public class Resource : MonoBehaviour, IResource{ public string Name { get; set; } public string Quality { get; set; } public int Yield { get; set; } public string ConvertQualityToString(){ var val = Random.Range(0, 3); string quality; switch (val){ case 1: quality = "Good"; break; case 2: quality = "Great"; break; default: quality = "Poor"; break; } return quality; } public int GetResourceYield(){ var val = Random.Range(1, 25); return val; } } </code></pre> <p>And finally, I create the specific resource itself and attach it to my game object in the inspector.</p> <p><strong>Resource Class</strong></p> <pre><code>public class Granite : Resource{ void Start(){ Name = "Granite"; Quality = ConvertQualityToString(); Yield = GetResourceYield(); } } </code></pre> <p>Is this the proper way to work this system? Obviously, the system actually does work as when I log the values on startup, <code>Yield</code> and <code>Quality</code> are randomized and the <code>Name</code> for each resource object I create is correct. Is there a better way to do this? Are there things I should change? Thanks in advance.</p>
[]
[ { "body": "<p>A few notes:</p>\n\n<ul>\n<li>All <code>IResource</code> properties have public setters. Are you absolutely certain that other code should be able to modify those? I'd recommend making these read-only unless you have specific reasons not to.</li>\n<li><code>ConvertQualityToString</code> and <code>...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T14:02:18.087", "Id": "205897", "Score": "3", "Tags": [ "c#", "unity3d" ], "Title": "World resource system for Adventure Game/RPG" }
205897
<p>I am trying to find the best average score from below two dimensional array:</p> <pre><code>String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } }; </code></pre> <p><strong>The output is:</strong> 80 (Arthit's score (60+100)/2)</p> <p>Till now I solved this problem with below approach, however I am looking for elegant solution with stream:</p> <pre><code>public static void main(String[] args) { String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } }; int highestAvg = Integer.MIN_VALUE; Function&lt;String[], Integer&gt; function = new Function&lt;String[], Integer&gt;() { @Override public Integer apply(String[] t) { int sum = 0, count = 0; for (int i = 0; i &lt; scores.length; i++) { if (t[0].equals(scores[i][0])) { count++; sum += Integer.parseInt(scores[i][1]); } } int avg = sum / count; return highestAvg &lt; avg ? avg : highestAvg; } }; System.out.println(Arrays.stream(scores).map(function).max((o1, o2) -&gt; o1.compareTo(o2)).get()); } </code></pre> <p>Would you please suggest, what's the better approach to handle two dimensional array using stream?</p> <p>Note: <strong>I am not looking the exact solution, just looking your valuable suggestion.</strong></p>
[]
[ { "body": "<p>Apologies for providing a full solution, I know you didn't ask for that, it was just easier for me to work through it by writing the code in full.</p>\n\n<p>I'm initially approaching about by thinking about how would I solve this in a database using SQL, and then applying a similar approach in Jav...
{ "AcceptedAnswerId": "205907", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T14:12:58.333", "Id": "205898", "Score": "1", "Tags": [ "java", "stream" ], "Title": "Stream operation with two dimensional array" }
205898
<p>I was successfully able to write a small script using PySpark to retrieve and organize data from a large .xml file. Being new to using PySpark, I am wondering if there is any better way to write the following code:</p> <pre><code>import pyspark from pyspark.sql import SparkSession from pyspark.sql.functions import monotonically_increasing_id ### xml file from https://wit3.fbk.eu/ sc = SparkSession.builder.getOrCreate() df = sc.read.format("com.databricks.spark.xml").option("rowTag","transcription").load('ted_en-20160408.xml') df_values = df.select("seekvideo._VALUE") df_id = df.select("seekvideo._id") df_values = df_values.withColumn("id", monotonically_increasing_id()) df_id = df_id.withColumn("id", monotonically_increasing_id()) result = df_values.join(df_id, "id", "outer").drop("id") answer = result.toPandas() transcription = dict() for talk in range(len(ted)): if not answer._id.iloc[talk]: continue transcription[talk] = zip(answer._id.iloc[talk], answer._VALUE.iloc[talk]) </code></pre> <p>where <code>df</code> is of the form:</p> <pre><code>DataFrame[_corrupt_record: string, seekvideo: array&lt;struct&lt;_VALUE:string,_id:bigint&gt;&gt;] </code></pre> <p>and <code>transcription</code> is a dictionary of the transcriptions of each TED Talk keyed by position. For example, <code>transcription[0]</code> is of the form:</p> <pre><code>[(800, u'When I moved to Harare in 1985,'), (4120, u"social justice was at the core of Zimbabwe's national health policy."), (8920, u'The new government emerged from a long war of independence'), (12640, u'and immediately proclaimed a socialist agenda:'), (15480, u'health care services, primary education'), ... ] </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T14:43:10.577", "Id": "205899", "Score": "1", "Tags": [ "python", "xml", "apache-spark" ], "Title": "Managing PySpark DataFrames" }
205899
<p>I have implemented a custom run length encoding algorithm that converts an m x n array into an p x (n+1) array. The extra column is to record counts. Probably easier to show through examples:</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>encode = (array) =&gt; { // crude array equality function arrayEquals = (...arr) =&gt; { return arr[0].map(x =&gt; { return JSON.stringify(x); }).every((x, _, a) =&gt; { return x === a[0]; }); }; let result = [], count = -1, len = array.length; array.reduce((acc, val, i) =&gt; { if (!arrayEquals([acc, val])) { // if current value differs from last if (i !== len - 1) { // push the count and data to the result result.push([++count, acc]); count = 0; // reset the count } else { // last iteration // push the (n - 1)th value result.push([++count, acc]); // now push the nth value result.push([1, val]); } } else { // if current value equals the last, increment counter and continue count++; if (i === len - 1) { // last iteration // push regardless count === 1 ? result.push([++count, val]) : result.push([count, val]); } } return val; }, array[0]); return result; }; console.log(encode([1, 1, 2, 2, 3, 3, 4])); console.log(encode([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ])); console.log(encode([ [1, 2, 3], [1, 2, 3], [4, 5, 6] ])); console.log(encode([ [0], [0], [1], [2, 3], [4, 5, 6], [], [] ]));</code></pre> </div> </div> </p> <p>I think I've tried the full range of common test cases and it has worked so far for all of them but I feel there must be a better way to implement this. The logic was awkward to write given the need to have knowledge of previous iterations and the current. I used reduce as it seemed to lend itself to this but even so, keeping track of when to increment was very difficult and doesn't make for the most readable code. My hunch is that there's a neat solution where one adds dummy elements to the beginning or end of the initial array and then can do away with the need for the (<code>if (i === len - 1)</code> logic)?</p> <p>Any improvements would be much appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T16:16:39.083", "Id": "397175", "Score": "0", "body": "I don't understand what this is doing. What is being counted? m rows becomes p rows. What is that about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018...
[ { "body": "<p>Output formatting is unreadable. It is extremely difficult to verify correct results.</p>\n\n<hr>\n\n<p><code>// crude array equality function</code> comment is not helpful because the function name tells me. But a comment about what <code>arrayEquality</code> equates on would be very helpful. I d...
{ "AcceptedAnswerId": "205922", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T15:10:02.787", "Id": "205901", "Score": "3", "Tags": [ "javascript", "algorithm", "compression" ], "Title": "Javascript run length encoding algorithm" }
205901
<p>I'd like to be able to better test application stability. Usually when you're doing this, you run the application and keep your fingers crossed that it won't crash when an error occurs (be it a missing file, no database connection or whatever service didn't work).</p> <p>The problem is that it's difficult to provoke <em>everything</em> that can go wrong. So instead of disabling services or removing files etc. I'd like to throw diagnostic exceptions that would pretend to be real errors.</p> <hr> <h3>Implementation</h3> <p>I call my solution <code>PhantomException</code> that is represented by this simple interface:</p> <pre><code>public interface IPhantomException { void Throw(string name, string message = default); } </code></pre> <p>It's implemented as a small service that gets injected to whatever specifies this as a dependency.</p> <pre><code>public class PhantomException : IPhantomException, IEnumerable&lt;IPhantomExceptionPattern&gt; { private readonly IList&lt;IPhantomExceptionPattern&gt; _patterns = new List&lt;IPhantomExceptionPattern&gt;(); public void Throw(string name, string message = default) { lock (_patterns) { var matches = _patterns.Where(t =&gt; t.Matches(name)).Join(", "); if (matches.Any()) { throw DynamicException.Create ( name ?? "Phantom", message ?? $"This phantom exception was thrown because it matches [{matches}]." ); } } } public void Add(IPhantomExceptionPattern pattern) =&gt; _patterns.Add(pattern); public IEnumerator&lt;IPhantomExceptionPattern&gt; GetEnumerator() =&gt; _patterns.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() =&gt; ((IEnumerable)_patterns).GetEnumerator(); } </code></pre> <p>The service requires a collection of <em>patterns</em> represented by an interface</p> <pre><code>public interface IPhantomExceptionPattern : IDisposable { bool Matches(string name); } </code></pre> <p>and a default implementation. It queries values from the collection and tests each of them if it's matched. A match means an exception can be thrown.</p> <pre><code>public abstract class PhantomExceptionPattern&lt;T&gt; : IPhantomExceptionPattern, IDisposable { private IEnumerator&lt;T&gt; _values; protected PhantomExceptionPattern(IEnumerable&lt;T&gt; values) { _values = values.GetEnumerator(); try { if (!_values.MoveNext()) { throw new ArgumentException ( paramName: nameof(values), message: $"Cannot initialize '{GetType().ToPrettyString()}' because there has to be at least one value." ); } } catch (Exception) { _values.Dispose(); throw; } Reset(); } [CanBeNull] public Func&lt;string, bool&gt; Predicate { get; set; } protected T Current =&gt; _values.Current; protected bool Eof =&gt; _values is null; public bool Matches(string name) { if (Eof) return false; if (Predicate?.Invoke(name) == false) return false; if (Matches() == false) return false; Reset(); if (!_values.MoveNext()) { _values.Dispose(); _values = null; } return true; } protected abstract bool Matches(); protected abstract void Reset(); public abstract override string ToString(); public void Dispose() =&gt; _values?.Dispose(); } </code></pre> <p>Matching of each value is passed to a concrete pattern. I have two of them:</p> <pre><code>public class CountPattern : PhantomExceptionPattern&lt;int&gt; { private int _counter; public CountPattern(IEnumerable&lt;int&gt; values) : base(values) { } protected override bool Matches() =&gt; ++_counter == Current; protected override void Reset() =&gt; _counter = 0; public override string ToString() =&gt; $"{nameof(CountPattern)}: {_counter}"; } public class IntervalPattern : PhantomExceptionPattern&lt;TimeSpan&gt; { private Stopwatch _stopwatch; public IntervalPattern(IEnumerable&lt;TimeSpan&gt; values) : base(values) { } protected override bool Matches() =&gt; _stopwatch.Elapsed &gt;= Current; protected override void Reset() =&gt; _stopwatch = Stopwatch.StartNew(); public override string ToString() =&gt; $"{nameof(IntervalPattern)}: {Current} at ({_stopwatch.Elapsed})"; } </code></pre> <p>The first one matches every n-call and the other one after the specified time. For each pattern a predicate can be specified to filter exceptions that should be thrown. If nothing is specified then everything matches. When the collection of values is exhausted, the enumerator is disposed and nulled. A pattern in this state (<code>Eof</code>) return always <code>false</code></p> <hr> <h3>Examples</h3> <p>This shows how I use it:</p> <pre><code>public class PhantomExceptionTest { [Fact] public void Can_throw_by_CountPattern() { var phantomException = new PhantomException { new CountPattern(Sequence.Constant(2)) { Predicate = name =&gt; name == "TooFast" } }; var counts = new List&lt;int&gt;(); foreach (var n in Sequence.Monotonic(0, 1).Take(10)) { try { phantomException.Throw("TooFast"); } catch (DynamicException ex) when (ex.NameMatches("^TooFast")) { counts.Add(n); } } Assert.Equal(Sequence.Monotonic(1, 2).Take(5), counts); } [Fact] public async Task Can_throw_by_IntervalPattern() { var phantomException = new PhantomException { new IntervalPattern(Sequence.Constant(TimeSpan.FromSeconds(2))) { //Predicate = // not using here } }; var counts = new List&lt;TimeSpan&gt;(); foreach (var n in Sequence.Constant(TimeSpan.FromSeconds(2.5)).Take(2)) { await Task.Delay(n); try { phantomException.Throw("TooFurious"); } catch (DynamicException ex) when (ex.NameMatches("^TooFurious")) { counts.Add(n); } } Assert.Equal(2, counts.Count); } } </code></pre> <hr> <h3><em>Bonus</em> - helper sequences</h3> <p>My tests here use <code>Sequence</code> helpers for generating collections. Here they are.</p> <p>This is the main abstraction that provide reusable code for concrete implementations:</p> <pre><code>public abstract class Sequence&lt;T&gt; : IEnumerable&lt;T&gt; { private readonly IEnumerable&lt;T&gt; _value; protected Sequence(IEnumerable&lt;T&gt; value) =&gt; _value = value; #region IEnumerable public virtual IEnumerator&lt;T&gt; GetEnumerator() =&gt; _value.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator(); #endregion } public abstract class Sequence { public static IEnumerable&lt;T&gt; Constant&lt;T&gt;(T value) =&gt; new ConstantSequence&lt;T&gt;(value); public static IEnumerable&lt;int&gt; Random(int min, int max) =&gt; new RandomSequence(min, max); public static IEnumerable&lt;T&gt; Fibonacci&lt;T&gt;(T one) =&gt; new FibonacciSequence&lt;T&gt;(one); public static IEnumerable&lt;T&gt; Monotonic&lt;T&gt;(T start, T step) =&gt; new MonotonicSequence&lt;T&gt;(start, step); public static IEnumerable&lt;T&gt; InfiniteDefault&lt;T&gt;() { using (var e = new InfiniteDefaultEnumerator&lt;T&gt;()) { while (e.MoveNext()) { yield return default; } } } } public class InfiniteDefaultEnumerator&lt;T&gt; : IEnumerator&lt;T&gt; { public T Current =&gt; default; object IEnumerator.Current =&gt; Current; public bool MoveNext() =&gt; true; public void Reset() { } public void Dispose() { } } </code></pre> <p>Sequence implementations:</p> <pre><code>public class ConstantSequence&lt;T&gt; : Sequence&lt;T&gt; { public ConstantSequence(T value) : base(Sequence.InfiniteDefault&lt;T&gt;().Select(_ =&gt; value)) { } } public class FibonacciSequence&lt;T&gt; : Sequence&lt;T&gt; { public FibonacciSequence(T one) : base(Create(one)) { } private static IEnumerable&lt;T&gt; Create(T one) { yield return one; var previous = one; var current = one; foreach (var _ in Sequence.InfiniteDefault&lt;T&gt;()) { yield return current; var newCurrent = BinaryOperation&lt;T&gt;.Add(previous, current); previous = current; current = newCurrent; } } } public class MonotonicSequence&lt;T&gt; : Sequence&lt;T&gt; { public MonotonicSequence(T start, T step) : base(Create(start, step)) { } private static IEnumerable&lt;T&gt; Create(T start, T step) { foreach (var _ in Sequence.InfiniteDefault&lt;T&gt;()) { yield return start; start = BinaryOperation&lt;T&gt;.Add(start, step); } } } public class RandomSequence : Sequence&lt;int&gt; { public RandomSequence(int min, int max, Func&lt;int, int, int&gt; next) : base(Sequence.InfiniteDefault&lt;int&gt;().Select(_ =&gt; next(min, max))) { } public RandomSequence(int min, int max) : this(min, max, CreateNextFunc((int)DateTime.UtcNow.Ticks)) { } private static Func&lt;int, int, int&gt; CreateNextFunc(int seed) { var random = new Random(seed); return (min, max) =&gt; random.Next(min, max); } } </code></pre> <hr> <h3>Questions</h3> <p>Would you say this code is easy to use? How about its implementation? Any other thoughts?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-28T16:59:15.290", "Id": "432330", "Score": "0", "body": "How would you use this in application code? Would you stub a dependency in a unit test and throw a phantom exception or would you paste this in your code while debugging? This pa...
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T15:57:42.643", "Id": "205902", "Score": "5", "Tags": [ "c#", "error-handling", "thread-safety", "integration-testing" ], "Title": "Testing application stability by throwing random diagnostic exceptions" }
205902
<p>I was trying to see if <code>data.table</code> could speed up a <code>gsub</code> pattern matching function over a list.</p> <p>Data for reprex. It's a list of 3 data frames with some asterisks placed here and there. Each data frame is 6500 rows, 2 columns, and generally representative of my actual data. My data does have multiple columns per data frame that need to be looped over, which is why I'm using the <code>mapply</code>.</p> <pre><code>library(data.table) library(microbenchmark) df1 &lt;- data.frame(name = rep(LETTERS, 250), code = rep(letters, 250), stringsAsFactors = FALSE) df1$name[df1$name == "D" | df1$name == "F" | df1$name == "L"] &lt;- "foo*" df1$code[df1$code == "d" | df1$code == "f" | df1$code == "l"] &lt;- "*foo" df2 &lt;- data.frame(name = rep(LETTERS, 250), code = rep(letters, 250), stringsAsFactors = FALSE) df2$name[df2$name == "A" | df2$name == "R" | df2$name == "T"] &lt;- "foo*" df2$code[df2$code == "a" | df2$code == "r" | df2$code == "t"] &lt;- "*foo*" df3 &lt;- data.frame(name = rep(LETTERS, 250), code = rep(letters, 250), stringsAsFactors = FALSE) df3$name[df3$name == "C" | df3$name == "Q" | df3$name == "W"] &lt;- "foo*" df3$code[df3$code == "c" | df3$code == "q" | df3$code == "w"] &lt;- "*f*oo" df &lt;- list(df1, df2, df3) dt &lt;- lapply(df, as.data.table) </code></pre> <p>In this example, I am trying to remove any <code>*</code> symbols from character strings. First function was just using an <code>mapply</code> and <code>gsub</code>. It deletes any <code>*</code>, looping over elements. Second was an attempt to do it using the <code>data.table</code> library.</p> <pre><code>mapply.remove.asterisk = function(x){ df2 &lt;- data.frame(mapply(gsub, "\\*", "", x, perl = TRUE)) colnames(df2) &lt;- colnames(x) } dt.remove.asterisk = function (x) { x[, lapply(.SD, function(x) gsub("\\*", "", x, perl = TRUE))] } </code></pre> <p>Testing them out doesn't show a big difference, but the <code>mapply</code> is slightly slower.</p> <pre><code>mapgsubtest = function(x) { df.test &lt;- lapply(x, mapply.remove.asterisk) } dtgsubtest = function(x) { dt.test &lt;- lapply(x, dt.remove.asterisk) } microbenchmark(mapgsubtest(df), dtgsubtest(dt), neval = 100) Unit: nanoseconds expr min lq mean median uq max neval mapgsubtest(df) 7161991 7388846 7780101.83 7483794 7651907 27860732 100 dtgsubtest(dt) 6759663 6991926 7181127.95 7109710 7275418 10102686 100 neval 0 0 12.26 0 1 902 100 </code></pre> <p>Is there something I'm doing within <code>data.table</code> that could be improved? I tried to see if a few things sped everything up, like having <code>*</code> only at the end of strings (only <code>foo*</code>), using an end of string regex anchor <code>$</code>, and setting an index key. Nothing changed noticeably.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T02:15:22.770", "Id": "397520", "Score": "1", "body": "I'm curious why you need to make your code faster (6500 rows and your current computation times seem pretty small), could you elaborate? That being said, using `gsub` with the `...
[ { "body": "<p>Is there a reason that you are using <code>mapply</code> to gsub through the number columns as well? You can just replace in the first column if that is all you need, which gets some speed improvement, about 2x on my machine. I also tried using <code>stringi</code> instead of gsub but it was not f...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T16:34:05.530", "Id": "205903", "Score": "1", "Tags": [ "performance", "r" ], "Title": "Character pattern replacement using gsub, loops, and data.table" }
205903
<p>Consider the following sorting algorithm:</p> <pre><code>df &lt;- data.frame(food_1 = c("APPLE 1534", "PEAR 2525", "BANANA 3045", "WATERMELON 5000"), food_2 = c("ORANGE 2035", "BROCCOLI 5000", "BLUEBERRY 2000", "TOMATO 3000"), stringsAsFactors = FALSE) # Sorting for (i in 1:nrow(df)){ foods &lt;- sort(c(df$food_1[i], df$food_2[i])) df$food_1[i] &lt;- foods[1] df$food_2[i] &lt;- foods[2] } </code></pre> <p>I have data frames which are of size 250,000+ rows that I've used the code above for, and I'm not sure how to make this more efficient. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T18:48:14.487", "Id": "397185", "Score": "0", "body": "The other option I can think of would be transposing and sorting with an apply, which is just a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10...
[ { "body": "<p>You solution does the job, but it is often better to vectorise your code. See the following example. First get the ordering of all elements in column a and b and then use this to rearrange the elements in the data.frame. </p>\n\n<pre><code>library(tictoc) #to get the run time\n\ndf &lt;- data.fram...
{ "AcceptedAnswerId": "205923", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T16:49:11.007", "Id": "205905", "Score": "1", "Tags": [ "performance", "sorting", "r" ], "Title": "Speed up sorting algorithm in R: make one column \"smaller\" than the other" }
205905
<p>I'm learning to code for fun, and just finished my first program. I don't know what to think about it since it's my first finished real code, but hey it works! I'm pretty sure that it can be written shorter or better than this.</p> <p>Right now it can only solve 1 problem at a time, but I'm going to make it so it can save the outcome and work further on and after that I'm of plan to change from using the console to having a real calculator look. I just want to improve myself by listening to your thoughts before working further on it.</p> <p>What could I do shorter/easier/simpler/better?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ZoneNumber1: //First number Console.WriteLine(); Console.WriteLine(); Console.Write("Number: "); double Number1; double Number2; while (!double.TryParse(Console.ReadLine(), out Number1)) { Console.Clear(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Wrong sort of input."); Console.Write("Enter a number: "); } Console.Clear(); Console.WriteLine(Number1); Console.WriteLine(); //Second number + action Action: Console.Write("Action: "); string Action = Console.ReadLine(); Console.Clear(); Console.WriteLine(Number1+""+Action); if ((Action == "*") || (Action == "/") || (Action == "-") || (Action == "+")) { switch (Action) { case "*": Console.WriteLine(); Console.Write("Number: "); while (!double.TryParse(Console.ReadLine(), out Number2)) { Console.Clear(); Console.WriteLine(Number1 + Action); Console.WriteLine(); Console.WriteLine("Wrong sort of input."); Console.Write("Enter a number: "); } Console.Clear(); Console.WriteLine(Number1 + "*" + Number2); Console.WriteLine(); Console.WriteLine("= "+ Number1 * Number2); Console.Write("Press enter to calculate again: "); Console.ReadLine(); Console.Clear(); goto ZoneNumber1; case "-": Console.WriteLine(); Console.Write("Number: "); while (!double.TryParse(Console.ReadLine(), out Number2)) { Console.Clear(); Console.WriteLine(Number1 + Action); Console.WriteLine(); Console.WriteLine("Wrong sort of input."); Console.Write("Enter a number: "); } Console.Clear(); Console.WriteLine(Number1 + "-" + Number2); Console.WriteLine(); Console.WriteLine("= " + (Number1 - Number2)); Console.Write("Press enter to calculate again: "); Console.ReadLine(); Console.Clear(); goto ZoneNumber1; case "+": Console.WriteLine(); Console.Write("Number: "); while (!double.TryParse(Console.ReadLine(), out Number2)) { Console.Clear(); Console.WriteLine(Number1 + Action); Console.WriteLine(); Console.WriteLine("Wrong sort of input."); Console.Write("Enter a number: "); } Console.Clear(); Console.WriteLine(Number1 + "+" + Number2); Console.WriteLine(); Console.WriteLine("= " + (Number1 + Number2)); Console.Write("Press enter to calculate again: "); Console.ReadLine(); Console.Clear(); goto ZoneNumber1; case "/": Console.WriteLine(); Console.Write("Number: "); while (!double.TryParse(Console.ReadLine(), out Number2)) { Console.Clear(); Console.WriteLine(Number1 + Action); Console.WriteLine(); Console.WriteLine("Wrong sort of input."); Console.Write("Enter a number: "); } Console.Clear(); Console.WriteLine(Number1 + "/" + Number2); Console.WriteLine(); Console.WriteLine("= " + (Number1 / Number2)); Console.Write("Press enter to calculate again: "); Console.ReadLine(); Console.Clear(); goto ZoneNumber1; } } else //if the input is not what it is supposed to be { Action = ""; Console.Clear(); Console.WriteLine(Number1 + Action); Console.WriteLine(); Console.WriteLine("False action input, choose between: / ; * ; - ; +"); goto Action; } } } } </code></pre>
[]
[ { "body": "<p>You should not be repeating. Put it below the the final else.</p>\n\n<pre><code>while (!double.TryParse(Console.ReadLine(), out Number2))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19...
{ "AcceptedAnswerId": "205915", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T17:40:11.837", "Id": "205906", "Score": "12", "Tags": [ "c#", "beginner", "console", "calculator" ], "Title": "Console calculator for 2 numbers at a time" }
205906
<pre><code>val y: Seq[Either[String, Int]] case class Response(value: String) val notFound = Response("Not Found") val found = Response("Found") val response: Response = y.lastOption .map(_.fold(_ =&gt; notFound, _ =&gt; found)) .getOrElse(notFound) </code></pre> <p>I am getting a list of Eithers. I want to get the last <code>Either</code> in the list. I then want to get <code>Right</code>value. If the list is empty or the Either is <code>Left</code>, I want to return a default value. The code does this but can this be done more elegantly and clearer in Scala with perhaps cats? I don't use scalaz.</p>
[]
[ { "body": "<p>Instead of <code>map()</code> - <code>fold()</code> - <code>getOrElse()</code>, you could just use two <code>fold()</code> calls.</p>\n\n<pre><code>val response = Response(y.lastOption\n .fold(\"Not Found\")(_.fold(_=&gt;\"Not Found\", _=&gt;\"Found\")))\n</code></pre>\n\n<...
{ "AcceptedAnswerId": "205932", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T00:30:55.200", "Id": "205926", "Score": "0", "Tags": [ "scala" ], "Title": "Getting last or return a default value in a Seq[Either[A, B]]" }
205926
<p><a href="https://codereview.stackexchange.com/questions/205667/n-puzzle-solver-using-a-with-manhattan-linear-conflict">Here</a> is the old thread that I started out with. The code I've got now is vastly different thanks to those two. What I have now functions fairly well and looks pretty good. I've managed to work it back down to some decent speeds, but I'm still encountering long solve states. I am "fairly" certain that I have both my solvable function and heuristic (manhattan and linear conflict) functions right.</p> <p>If you want to test the heuristic functions on the board to check, I built an excel file. Just uncomment <code>writeBoard(curr, n)</code> in <code>solve(...)</code> and put in a stop. Then open up the file board.csv and copy that into heuristic.xlsx. Only the main sheet (Manhattan) needs to be copied. Linear reads from that. The full heuristic value is output on the left side of Manhattan.</p> <p>I think I have something fundamentally wrong. I'm currently sorting by heuristic value instead of overall cost because that is what is actually working. When I change things to use cost, I rarely, if ever, get a solve.</p> <p>I also tried two different data structures for my open list. <code>std::priority_queue</code> and <code>std::set</code>. Priority queue is much, much faster (avg 0.3-0.5 when solved) than set (avg 7-8 when solved), but set had more reliable solves. It would still occasionally hit something though and I'd just kill the program after like 30 seconds. I also noticed that set had a lower number of steps than the queue. I noticed when debugging that the queue will retain its size when using <code>.pop()</code>. I'm pretty sure it then just appends the incoming node on the end which causes some issues. My main question for this is if there is any way to resize a queue. I've done some research on it and come up with only one thing: inheriting from an stdlib class. <a href="https://stackoverflow.com/questions/3666387/c-priority-queue-underlying-vector-container-capacity-resize">Here</a> is the best one I've found explaining it. Every time I found this, there were several condemning the very act. I'd also like a little clarification as to why. I noticed one comment on that accepted answer about "inheriting from a class that has a public non-virtual destructor makes feel bad, very bad". Why is that? Aside from this atrocity, is there maybe a better suited data structure I could use? I'm very comfortable with STL, but am open to learning a new library if need be.</p> <p>I'm also still working on implementing changes suggested by the two who answered my own question. I've done a lot, but not everything. I probably won't touch expanding to higher boards until I get these smaller ones down, so <code>encode</code> and <code>decode</code> are just there for the time being. I know they are limited to a max of 16 square tiles. I'd still very much appreciate some advice on how to clean it up!</p> <p>Edit: Forgot to post the <a href="https://github.com/abyssmu/n-Puzzle" rel="nofollow noreferrer">GitHub link</a>.</p> <h2>Main.cpp</h2> <pre><code>#include "Functions.h" int main() { auto start = std::chrono::system_clock::time_point(); auto end = std::chrono::system_clock::time_point(); auto b = Npuzzle::Board(); //Open list contains all unexplored nodes, sorted by heuristic value Npuzzle::set open; //Closed list contains all explored nodes, with values set to encoded parent board Npuzzle::map closed; auto n = 4; //std::cout &lt;&lt; "Input size of board: " &lt;&lt; std::endl; //std::cin &gt;&gt; n; start = std::chrono::system_clock::now(); solve(b, open, closed, n); end = std::chrono::system_clock::now(); auto t = std::chrono::duration&lt;double&gt;(); t = end - start; auto steps = print(Npuzzle::encode(b, n), closed, n); std::cout &lt;&lt; std::endl; std::cout &lt;&lt; std::fixed; std::cout &lt;&lt; std::setprecision(5); std::cout &lt;&lt; steps &lt;&lt; " steps in " &lt;&lt; t.count() &lt;&lt; " secs."; //Cleanup cleanup(open, closed); std::cin.get(); return 0; } </code></pre> <h2>Functions.h</h2> <pre><code>#include &lt;ctime&gt; #include &lt;fstream&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;thread&gt; #include "Npuzzle.h" bool duplicate( const Npuzzle::Board b, Npuzzle::map&amp; closed, const int n) { return closed.count(Npuzzle::encode(b, n)); } void addQueue( const Npuzzle::Board b, const Npuzzle::Board parent, Npuzzle::set&amp; open, Npuzzle::map&amp; closed, const int n) { auto c = new Npuzzle::Structures::Container; c-&gt;board = b; c-&gt;heuristic = Npuzzle::heuristic(b, n); open.emplace(c); closed.insert({ Npuzzle::encode(b, n), Npuzzle::encode(parent, n) }); } void addMoves( const Npuzzle::Board b, Npuzzle::set&amp; open, Npuzzle::map&amp; closed, const int n) { auto moves = std::vector&lt;Npuzzle::Board&gt;(4); auto parent = b; moves[0] = Npuzzle::up(b, n); moves[1] = Npuzzle::down(b, n); moves[2] = Npuzzle::left(b, n); moves[3] = Npuzzle::right(b, n); for (auto i = 0; i &lt; 4; ++i) { if (moves[i].size() == (n * n)) { if (!duplicate(moves[i], closed, n)) { addQueue(moves[i], parent, open, closed, n); } } } } void cleanup( Npuzzle::set&amp; open, Npuzzle::map&amp; closed) { //Used for set //open.clear(); //Used for priority queue while (!open.empty()) { delete open.top(); open.pop(); } closed.clear(); } void printBoard( const Npuzzle::Board b, const int n) { for (auto j = 0; j &lt; n * n; ++j) { std::cout &lt;&lt; b[j] &lt;&lt; "\t"; if (j % n == 3) { std::cout &lt;&lt; std::endl; } } } int print( Npuzzle::i64 b, Npuzzle::map closed, const int n) { std::vector&lt;Npuzzle::Board&gt; solution; do { auto p = b; solution.push_back(Npuzzle::decode(b, n)); b = closed[p]; } while (b != 0); auto size = int(solution.size() - 1); for (auto i = size; i &gt;= 0; --i) { printBoard(solution[i], n); std::this_thread::sleep_for(std::chrono::milliseconds(25)); if (i != 0) { system("CLS"); } } return size; } void reset( Npuzzle::Board&amp; curr, Npuzzle::set&amp; open, Npuzzle::map&amp; closed, const int n) { cleanup(open, closed); curr = Npuzzle::createBoard(n); addQueue(curr, Npuzzle::Board(n * n), open, closed, n); } void writeBoard( const Npuzzle::Board b, const int n) { std::ofstream board("board.csv"); for (auto i = 0; i &lt; n; ++i) { for (auto j = 0; j &lt; n; ++j) { auto k = i * n + j; board &lt;&lt; b[k] &lt;&lt; ","; } board &lt;&lt; std::endl; } } void solve( Npuzzle::Board&amp; curr, Npuzzle::set&amp; open, Npuzzle::map&amp; closed, const int n) { auto solved = false; //Create initial board curr = Npuzzle::createBoard(n); //Test state //curr = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 14, 15 }; addQueue(curr, Npuzzle::Board(n * n), open, closed, n); while (!solved) { //Used for set //auto top = *open.begin(); curr = open.top()-&gt;board; if (open.top()-&gt;heuristic == 0) { solved = true; } else { //writeBoard(curr, n); //Used for set //open.erase(top); //Used for priority queue delete open.top(); open.pop(); addMoves(curr, open, closed, n); } } } </code></pre> <h2>Npuzzle.h</h2> <pre><code>#include &lt;assert.h&gt; #include &lt;cstdint&gt; #include &lt;numeric&gt; #include &lt;queue&gt; #include &lt;random&gt; #include &lt;set&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; namespace Npuzzle { using Board = std::vector&lt;int&gt;; using i64 = std::uint_fast64_t; namespace Structures { struct Point { int x, y; }; struct Container { int heuristic; Board board; }; struct LessThanByHeur { bool operator()( const Container* lhs, const Container* rhs) const { return lhs-&gt;heuristic &gt; rhs-&gt;heuristic; } }; } //using set = std::set&lt;Structures::Container*, Structures::LessThanByHeur&gt;; using set = std::priority_queue&lt;Structures::Container*, std::vector&lt;Structures::Container*&gt;, Structures::LessThanByHeur&gt;; using map = std::unordered_map&lt;i64, i64&gt;; Structures::Point findZero( const Board b, const int n) { for (auto i = 0; i &lt; n * n; ++i) { if (b[i] == 0) { return { i % n, i / n }; } } return { -1, -1 }; } //Count inversions in board int inversions( const Board b, const int n) { auto count = 0; for (auto i = 0; i &lt; n * n - 1; ++i) { for (auto j = i + 1; j &lt; n * n; ++j) { if (b[i] == 0) { if (b[j] &lt; n * n) { ++count; } } else if (b[j] &lt; b[i]) { ++count; } } } return count; } bool solvable( const Board b, const int n) { auto zero = findZero(b, n); auto count = inversions(b, n); //If width is odd and count is even if ((n &amp; 1) &amp;&amp; !(count &amp; 1)) { return true; } //If width is even else { //If zero y pos is odd from bottom, and count is even if (((n - zero.y) &amp; 1) &amp;&amp; !(count &amp; 1)) { return true; } else if (count &amp; 1) { return true; } } return false; } Board createBoard( const int n) { auto b = Board(n * n); auto rng = std::mt19937_64(std::random_device()()); do { //Fill vector from 0 to n * n std::iota(b.begin(), b.end(), 0); //Randomize vector std::shuffle(b.begin(), b.end(), rng); } while (!solvable(b, n)); return b; } Board decode( i64&amp; code, const int n) { static Board b(n * n); for (auto i = (n * n) - 1; i &gt;= 0; --i) { auto val = 0; //Get first n bits val = code &amp; ((1 &lt;&lt; n) - 1); //Delete first n bits code = code &gt;&gt; n; //Save val in board b[i] = val; } return b; } i64 encode( const Board b, const int n) { i64 code = 0; for (auto i = 0; i &lt; n * n; ++i) { //Set first n bits if (i == 0) { code |= b[i]; } //Set rest of bits else { code = ((code &lt;&lt; n) | b[i]); } } return code; } int linear( const Board b, const int n) { auto count = 0; Board inCol(n * n), inRow(n * n); for (auto y = 0; y &lt; n; ++y) { for (auto x = 0; x &lt; n; ++x) { auto i = y * n + x; if (b[i] == 0) { continue; } auto bX = 0; auto bY = 0; if (b[i] % n == 0) { bX = n - 1; bY = b[i] / n - 1; } else { bX = b[i] % n - 1; bY = b[i] / n; } inCol[i] = (bX == x); inRow[i] = (bY == y); } } for (auto y = 0; y &lt; n; ++y) { for (auto x = 0; x &lt; n; ++x) { auto i = y * n + x; if (b[i] == 0) { continue; } if (inCol[i]) { for (auto z = y; z &lt; n; ++z) { auto j = z * n + x; if (b[j] == 0) { continue; } if (inCol[j]) { if ((b[j] &lt; b[i]) &amp;&amp; ((abs(b[j] - b[i]) % n) == 0)) { ++count; } } } } if (inRow[i]) { auto bI = b[i]; for (auto z = x + 1; z &lt; n; ++z) { auto j = y * n + z; auto bJ = b[j]; if (b[j] == 0) { continue; } if (inRow[j]) { if ((bJ &lt; bI) &amp;&amp; (0 &lt;= (bI - bJ)) &amp;&amp; ((bI - bJ) &lt; n)) { ++count; } } } } } } return 2 * count; } int manhattan( const Board b, const int n) { auto m = 0; Board solution(n * n); std::iota(solution.begin(), solution.end(), 1); solution[n * n - 1] = 0; //Calculate manhattan distance for each value for (auto i = 0; i &lt; n * n; ++i) { if (b[i] != solution[i]) { auto bX = 0; auto bY = 0; auto x = 0; auto y = 0; if (b[i] == 0) { ++i; } //Calculate goal pos if ((b[i] % n) == 0) { bX = n - 1; bY = b[i] / n - 1; } else { bX = b[i] % n - 1; bY = b[i] / n; } //Calculate the current pos auto val = i + 1; if ((val % n) == 0) { x = n - 1; y = val / n - 1; } else { x = val % n - 1; y = val / n; } m += abs(bX - x) + abs(bY - y); } } return m; } int heuristic( const Board b, const int n) { return manhattan(b, n) + linear(b, n); } Board swapPos( const Board b, const int n, const Structures::Point zero, const int newPos) { auto oldPos = 0; Board move(n * n); //Calculate old pos oldPos = zero.x + (zero.y * n); //Copy current board for (auto i = 0; i &lt; n * n; ++i) { move[i] = b[i]; } //Swap pos move[oldPos] = move[newPos]; move[newPos] = 0; return move; } Board down( const Board b, const int n) { Structures::Point zero = findZero(b, n); auto newPos = zero.y + 1; //Check if move is possible if (newPos &gt; (n - 1)) { return Board(0); } //Create new board based on newPos return swapPos(b, n, zero, zero.x + (newPos * n)); } Board left( const Board b, const int n) { Structures::Point zero = findZero(b, n); auto newPos = zero.x - 1; //Check if move is possible if (newPos &lt; 0) { return Board(0); } //Create new board based on newPos return swapPos(b, n, zero, newPos + (zero.y * n)); } std::vector&lt;int&gt; right( const Board b, const int n) { Structures::Point zero = findZero(b, n); auto newPos = zero.x + 1; //Check if move is possible if (newPos &gt; (n - 1)) { return Board(0); } //Create new board based on newPos return swapPos(b, n, zero, newPos + (zero.y * n)); } Board up( const Board b, const int n) { Structures::Point zero = findZero(b, n); auto newPos = zero.y - 1; //Check if move is possible if (newPos &lt; 0) { return Board(0); } //Create new board based on newPos return swapPos(b, n, zero, zero.x + (newPos * n)); } } </code></pre>
[]
[ { "body": "<h2>Don't put implementation in header files</h2>\n\n<p>You moved all of your code into header files. That's not what they are for. It is better to have only the declarations of the classes and functions in the .h files, and put the definitions of the functions in .cpp files. Compile your code using ...
{ "AcceptedAnswerId": "205999", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T08:38:25.510", "Id": "205935", "Score": "3", "Tags": [ "c++", "time-limit-exceeded", "a-star", "sliding-tile-puzzle" ], "Title": "Npuzzle solver using A* with Manhattan + Linear Conflict (Updated Code)" }
205935
<p>I have 2 solutions about puzzle I mentioned in title:</p> <p><strong>solution 1( O(n^3) ):</strong></p> <pre><code>public static boolean sumOfThree_1(List&lt;Integer&gt; list, int sum) { for (int i = 0; i &lt; list.size() - 2; i++) { for (int k = i + 1; k &lt; list.size() - 1; k++) { for (int m = k + 1; m &lt; list.size(); m++) if ((list.get(i) + list.get(k) + list.get(m)) == sum) { return true; } } } return false; } </code></pre> <p><strong>solution 2( O(n^2) ):</strong></p> <pre><code>public static boolean sumOfThree_2(List&lt;Integer&gt; list, int sum) { for (int i = 0; i &lt; list.size() - 2; i++) { int expectedSumOfTwo = sum - list.get(i); if (sumOfTwo_2(list.subList(i+1, list.size()), expectedSumOfTwo)) { return true; } } return false; } public static boolean sumOfTwo_2(List&lt;Integer&gt; list, int sum) { Set&lt;Integer&gt; set = new HashSet&lt;&gt;(); for (int element : list) { if (set.contains(sum - element)) { return true; } set.add(element); } return false; } </code></pre> <p>Any suggestions about solutions?</p> <p>Better solutions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T11:37:30.213", "Id": "397296", "Score": "0", "body": "This looks to be a variation of the 3SUM problem, which you can read more about on the [Wikipedia page](https://en.wikipedia.org/wiki/3SUM)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T11:18:33.097", "Id": "205939", "Score": "1", "Tags": [ "java", "algorithm", "k-sum" ], "Title": "Check if list contains 3 elements with predefined sum" }
205939
<p>Handling abstract types in <code>json.net</code> can be sometimes challenging because it requires a very long and complex syntax like:</p> <blockquote> <pre><code>"$type": "Namespace.Type, Assembly" </code></pre> </blockquote> <p>It's not that difficult if you have simple classes but as soon as there is some generics involved it becomes tricky pretty quickly:</p> <blockquote> <pre><code>"$type": "Namespace.Type`2[[System.Int32, mscorlib,..][System.String, mscorlib,..]], Assembly" </code></pre> </blockquote> <p>So I'd rather write</p> <blockquote> <pre><code>"$t": "Type&lt;int, string&gt;" </code></pre> </blockquote> <p>and be done.</p> <hr> <p>Solving this required to implement your own <code>JsonTextReader</code> and override the <code>Read</code> method. Here I'm looking for my new special property <code>$t</code> that stands for a <em>shortcut</em> and a pretty type string. If found, it rewirtes this property by using the original property name <code>$type</code> and the <code>PrettyTypeExpander</code> to convert the friendly name into a fully qualified <code>json.net</code> type description.</p> <pre><code>[UsedImplicitly] public class PrettyTypeReader : JsonTextReader { private readonly string _typePropertyName; private readonly PrettyTypeExpander _prettyTypeExpander; private bool _isPrettyType; public PrettyTypeReader(TextReader reader, [NotNull] string typePropertyName, [NotNull] Func&lt;string, Type&gt; typeResolver) : base(reader) { _typePropertyName = typePropertyName ?? throw new ArgumentNullException(nameof(typePropertyName)); _prettyTypeExpander = new PrettyTypeExpander(typeResolver ?? throw new ArgumentNullException(nameof(typeResolver))); } public PrettyTypeReader(TextReader reader, params Type[] assemblyProviders) : this(reader, "$t", PrettyTypeResolver.Create(assemblyProviders)) { } private const string DefaultTypePropertyName = "$type"; public override bool Read() { if (base.Read() is var hasToken) { switch (TokenType) { // Replace custom type-property-name with the default one, e.g. "-t" -&gt; "$type" case JsonToken.PropertyName when IsCustomTypePropertyName(Value): SetToken(JsonToken.PropertyName, DefaultTypePropertyName); _isPrettyType = true; break; // Expand type name definition, e.g. "MyType" -&gt; "Namespace.MyType, Assembly" case JsonToken.String when _isPrettyType &amp;&amp; Value is string typeName: SetToken(JsonToken.String, _prettyTypeExpander.Expand(typeName)); break; default: _isPrettyType = false; break; } } return hasToken; } private bool IsCustomTypePropertyName(object value) { return value is string propertyName &amp;&amp; propertyName.Equals(_typePropertyName); } } </code></pre> <p>The <code>PrettyTypeExpander</code> parses and analyzes the pretty-string and tries to resolve the actual type. Then it builds the full-name.</p> <pre><code>internal class PrettyTypeExpander { private static readonly IImmutableDictionary&lt;string, Type&gt; Types = ImmutableDictionary .Create&lt;string, Type&gt;(StringComparer.OrdinalIgnoreCase) .Add("bool", typeof(Boolean)) .Add("byte", typeof(Byte)) .Add("sbyte", typeof(SByte)) .Add("char", typeof(Char)) .Add("decimal", typeof(Decimal)) .Add("double", typeof(Double)) .Add("float", typeof(Single)) .Add("int", typeof(Int32)) .Add("uint", typeof(UInt32)) .Add("long", typeof(Int64)) .Add("ulong", typeof(UInt64)) .Add("object", typeof(Object)) .Add("short", typeof(Int16)) .Add("ushort", typeof(UInt16)) .Add("string", typeof(String)); // Used to specify user-friendly type names like: "List&lt;int&gt;" instead of "List`1[System.Int32...]" etc. // https://regex101.com/r/QZ5T5I/1/ // language=regexp private const string PrettyTypePattern = @"(?&lt;type&gt;(?i)[a-z0-9_.]+)(?:\&lt;(?&lt;genericArguments&gt;(?i)[a-z0-9_., ]+)\&gt;)?"; public PrettyTypeExpander([NotNull] Func&lt;string, Type&gt; typeResolver) { TypeResolver = typeResolver; } private Func&lt;string, Type&gt; TypeResolver { get; } public string Expand(string prettyType) { var match = Regex .Match(prettyType, PrettyTypePattern, RegexOptions.ExplicitCapture) .OnFailure(_ =&gt; new ArgumentException($"Invalid type alias: '{prettyType}'.")); var genericArguments = CreateGenericArguments(match.Groups["genericArguments"]); var type = ResolveType($"{match.Groups["type"].Value}{genericArguments.Signature}"); return $"{type.FullName}{genericArguments.FullName}, {type.Assembly.GetName().Name}"; } // Signature: "&lt;, &gt;" // FullName: "[[T1],[T2]]" - the "`2" prefix is provided by type-full-name later private (string Signature, string FullName) CreateGenericArguments(Group genericArguments) { if (genericArguments.Success) { // "&lt;, &gt;" var commas = string.Join(string.Empty, genericArguments.Value.Where(c =&gt; c == ',').Select(c =&gt; $"{c} ")); var signature = $"&lt;{commas}&gt;"; var genericArgumentNames = genericArguments.Value.Split(',').Select(x =&gt; x.Trim()).ToList(); var genericArgumentFullNames = ( from name in genericArgumentNames let genericType = GetTypeByAlias(name) ?? ResolveType(name) select $"[{genericType.FullName}, {genericType.Assembly.GetName().Name}]" ); // Creates: "[[Namespace.T1, ...],[Namespace.T2, ...]]" var fullName = $"[{string.Join(",", genericArgumentFullNames)}]"; return (signature, fullName); } else { return (default, default); } } private static Type GetTypeByAlias(string name) =&gt; Types.TryGetValue(name, out var t) ? t : default; private Type ResolveType(string typeName) { return TypeResolver(typeName) ?? Type.GetType(typeName, ignoreCase: true, throwOnError: false) ?? throw DynamicException.Create("TypeNotFound", $"Could not resolve '{typeName}'."); } } </code></pre> <p>There's one more utility that scans assemblies for type definitions any tries to find a type by it's <a href="https://github.com/he-dev/Reusable/blob/dev/Reusable.Core/src/PrettyString.cs" rel="noreferrer">pretty-string</a>. To reduce some noise I exclude anonymous and closure types.</p> <pre><code>public static class PrettyTypeResolver { public static Func&lt;string, Type&gt; Create(params Type[] assemblyProviders) { var types = ( from assemblyProvider in assemblyProviders.Distinct() from type in assemblyProvider.Assembly.GetTypes() let prettyName = type.ToPrettyString() where !prettyName.StartsWith("&lt;&gt;f__AnonymousType") &amp;&amp; !prettyName.StartsWith("&lt;&gt;c__DisplayClass") select (type, prettyName) ).ToList(); return prettyName =&gt; types.SingleOrDefault(t =&gt; SoftString.Comparer.Equals(t.prettyName, prettyName)).type; } } </code></pre> <p>As my tests show this works quite good. I'm not really concerned about type conflics as this is intended to be used for very specific polymorphic custom types so they should not exist anywhere else. Alghough specifying concrete types would be very easy. You would just need to create a different type-resolver and inject this to the reader.</p> <p>Here is how I tested it and how I intend to use it:</p> <pre><code>[TestClass] public class PrettyTypeReaderTest { [TestMethod] public void Deserialize_CanResolveTypeByAlias() { var json = @" { ""Test0"": { ""$t"": ""JsonTestClass0"" }, ""Test1"": { ""$t"": ""JsonTestClass1&lt;int&gt;"" }, ""Test2"": { ""$t"": ""JsonTestClass2&lt;int, string&gt;"" } } "; using (var streamReader = json.ToStreamReader()) using (var jsonTextReader = new PrettyTypeReader(streamReader, typeof(PrettyTypeReaderTest))) { var jsonSerializer = new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto }; var testClass0 = jsonSerializer.Deserialize&lt;JsonTestClass0&gt;(jsonTextReader); Assert.IsNotNull(testClass0); Assert.IsNotNull(testClass0.Test0); Assert.IsNotNull(testClass0.Test1); Assert.IsNotNull(testClass0.Test2); } } } internal class JsonTestClass0 { public JsonTestClass0 Test0 { get; set; } public TestInterface Test1 { get; set; } public TestInterface Test2 { get; set; } } internal interface TestInterface { } internal class JsonTestClass1&lt;T1&gt; : TestInterface { } internal class JsonTestClass2&lt;T1, T2&gt; : TestInterface { } </code></pre> <p>I'd be happy to read your feedback and improvement suggestions.</p>
[]
[ { "body": "<p>This was a short-lived project. I had to abandon this approach because it is not possible to chain <code>JsonTextReader</code>s. They do not support the decorator pattern or cannot be connected in any other way so one reader cannot work with the result of the previous one.</p>\n\n<p>I discovered t...
{ "AcceptedAnswerId": "208764", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T11:31:10.113", "Id": "205940", "Score": "6", "Tags": [ "c#", "inheritance", "reflection", "polymorphism", "json.net" ], "Title": "Making TypeNameHandling in json.net more convenient" }
205940
<p>I have programmed a card game in Python. How can I improve the code?</p> <p>There is a deck of cards. Each cards has a colour (red, black or yellow) and a number from 1-10. There are two players. Every round, each player takes one card from the top of the deck. Those cards are compared, and the winner of the round is assigned based on the following rules:</p> <ul> <li>Red beats black</li> <li>Black beats yellow</li> <li>Yellow beats red</li> </ul> <p>If both cards have the same colour, the card with the highest number wins. If they have the same colour and number, it is a draw.</p> <p>The winner of the round keeps both cards. If the round was a draw, the players keep their own cards.</p> <p>This is repeated until the deck is empty. The winner is the person with the most cards at the end of the game.</p> <p>main.py:</p> <pre><code>import os from random import shuffle from time import sleep from termcolor import colored # Card index constants COLOUR = 0 NUMBER = 1 # Player constants DRAW = 'draw' PLAYER1 = '1' PLAYER2 = '2' def clear(): print('\n' * 100) def main(): clear() if not login(): return game = Game() menu_loop = True menu_array = [ ' ', ' ', ' 1 - Play game ', ' 2 - Create a new deck ', ' 3 - Load a deck ', ' 4 - Delete a deck ', ' 5 - Change the speed of the game ', ' 6 - View the leaderboard ', ' 7 - Quit ', ' ', ' ' ] while menu_loop: clear() with open('title.txt', 'r') as image_file: image_text = image_file.read() for c in image_text: if c == '0': print(' ', end='') elif c == '1': c = colored(' ', 'yellow', 'on_yellow') print(c, end='') elif c == '=' or c == '|': c = colored(' ', 'blue', 'on_blue') print(c, end='') elif c == '\n': print() print() for i in range(len(menu_array)): line = menu_array[i] if i == 0 or i == len(menu_array) - 1: print(colored(' ' * len(line), 'blue', 'on_blue')) else: first_char = colored(' ', 'blue', 'on_blue') middle = colored(line[1:-1], 'cyan') last_char = colored(' ', 'blue', 'on_blue') print(first_char + middle + last_char) menu_option = input('\nEnter menu option: ') if menu_option == '1': clear() game.play() input('Press enter to continue.') elif menu_option == '2': clear() new_deck_menu() input('Press enter to continue.') elif menu_option == '3': clear() change_deck_menu() input('Press enter to continue.') elif menu_option == '4': clear() delete_deck_menu() input('Press enter to continue.') elif menu_option == '5': clear() change_speed() input('Press enter to continue.') elif menu_option == '6': clear() try: top5 = FileFunctions.read_top5() display_leaderboard(top5) if len(top5) &gt; 0 else print('\nThere are no players on the leaderboard yet.\n') except FileNotFoundError: print('\nCould not find leaderboard file.\n') input('Press enter to continue.') elif menu_option == '7': print('\nGoodbye.') menu_loop = False else: clear() print('\nPlease choose a number from the menu.\n') input('Press enter to continue.') def login(): try: # The password (for now) is 'Python'. password = FileFunctions.get_password() except EOFError: print('Could not read the password file. The game cannot be played.') return False except FileNotFoundError: print('Could not find the password file. The game cannot be played.') return False valid = False while not valid: password_attempt = input('Enter password: ') clear() if password_attempt == password: valid = True else: print('Incorrect password.') return True # Returns a tuple containing a colour and a number. def new_card(colour, number): return (colour, number) # Creates a new random deck. def new_deck(name, number_of_cards): deck = [] for _ in range(int(number_of_cards / 30)): for i in range(10): deck.append(new_card('red', i+1)) deck.append(new_card('black', i+1)) deck.append(new_card('yellow', i+1)) FileFunctions.write_deck(name, deck) def display_leaderboard(players): length = 20 print('\nLEADERBOARD\n') print('=' * (length + 2)) for i in range(len(players)): score = len(players[i]) - 1 string_part1 = str(i+1) + ' | ' + players[i][0] string_part2 = ' ' * (length - len(string_part1)) + str(score) print("%s%s" % (string_part1, string_part2)) print('=' * (length + 2)) print('\n') def change_deck_menu(): valid = False while not valid: yes_or_no = input('Loading a different deck will reset the leaderboard. Do you wish to proceed? (y/n)').lower() clear() if yes_or_no == 'y': valid = True elif yes_or_no == 'n': print('\nDeck has not been loaded.\n') return else: print('\nPlease answer with \'y\' or \'n\'.\n') FileFunctions.clear_leaderboard() valid = False try: decks = FileFunctions.load_deck_names() decks_found = True except FileNotFoundError: decks_found = False while not valid: if decks_found: print('\nDecks:\n') for deck in decks: print(deck) else: print('\nThe deck names could not be found, but you should still be able to load a deck.\n') deck_name = input('\nEnter name of deck to load: ') clear() if deck_name.strip() == '': print('\nThe deck name will contain at least one visible character.') continue try: f = open(deck_name + '.txt', 'r') f.close() valid = True except FileNotFoundError: print('\nDeck \'%s\' does not exist.' % deck_name) valid = False FileFunctions.change_current_deck_name(deck_name) print('\nDeck \'%s\' has been loaded.\n' % deck_name) def new_deck_menu(): print('\n\n') valid = False while not valid: yes_or_no = input('\nAre you sure you want to create a new deck? (y/n)') yes_or_no = yes_or_no.lower() clear() valid = True if yes_or_no == 'y': name_valid = False while not name_valid: banned_names = ('password', 'title', 'leaderboard', 'round_delay', 'current_deck') deck_name = input('\nEnter deck name: ') clear() if deck_name.strip() == '': print('\nThe deck name must contain at least one visible character.\n') elif ' ' in deck_name: print('\nThe deck name cannot contain spaces.\n') elif '.' in deck_name: print('\nThe deck name cannot contain dots (the file extension will be added automatically).\n') elif '\\' in deck_name or '/' in deck_name: print('\nThe deck name cannot contain slashes.\n') elif deck_name in banned_names: print('\nYour deck name cannot be any of the following:') for name in banned_names: print(name) print() else: name_valid = True number_valid = False while not number_valid: try: number = int(input('Enter amount of cards: ')) except ValueError: clear() print('\nPlease enter an integer.\n') continue clear() if not (number % 2 == 0 and number % 3 == 0): print('\nAmount must be an even multiple of 3.\n') elif number == 0: print('\nIf there are no cards in a deck, is it still a deck?\n') elif number &lt; 0: print('\nYou can\'t have a negative amount of cards.\n') else: number_valid = True new_deck(deck_name, number) print('\nThe new deck has been created.') elif yes_or_no == 'n': print('\nCreation of new deck has been cancelled.') else: print('\nPlease answer with \'y\' or \'n\'.') valid = False print('\n') def change_speed(): valid = False try: current_delay = FileFunctions.load_round_delay() except FileNotFoundError: print('\nThe round delay file could not be loaded.\n') return current_delay = round(current_delay, 3) current_delay = str(current_delay) while not valid: print('The current round delay is %s seconds.\n' % (current_delay)) yes_or_no = input('Are you sure you want to change the speed of the game? (y/n)').lower() valid = True clear() if yes_or_no == 'y': input_loop = True while input_loop: input_loop = False try: seconds = float(input('\nEnter delay between each round in seconds: ')) clear() if seconds &lt; 0: print('The round delay cannot be a negative number.\n') input_loop = True except ValueError: input_loop = True clear() print('Please enter a float or an integer.\n') FileFunctions.write_round_delay(seconds) print('\nThe new round delay has been saved.\n') elif yes_or_no == 'n': print('\nChanging of game speed has been cancelled.\n') else: print('\nPlease answer with \'y\' or \'n\'.\n') valid = False def delete_deck_menu(): valid = False while not valid: yes_or_no = input('Are you sure you want to delete a deck? (y/n)').lower() clear() if yes_or_no == 'y': valid = True elif yes_or_no == 'n': print('\nDeletion of deck has been cancelled.\n') return else: print('\nPlease answer with \'y\' or \'n\'.\n') deck_names = FileFunctions.load_deck_names() valid = False while not valid: print('\nDecks:\n') for name in deck_names: print(name) deck_name = input('\nEnter the name of the deck you want to delete: ') clear() if deck_name.strip() == '': print('\nThe deck name will contain at least one visible character.') elif ' ' in deck_name: print('\nThe deck name will not contain spaces.') elif '.' in deck_name: print('\nPlease only enter the name of the deck. The file extension will be added automatically.\n') else: try: with open(deck_name + '.txt', 'r'): valid = True os.remove(deck_name + '.txt') with open('deck_names.txt', 'r') as deck_names_file: current_deck_names = deck_names_file.read().split('\n') current_deck_names.remove(deck_name) except (FileNotFoundError, ValueError): valid = False print('\nDeck \'%s\' could not be found. Make sure you have spelt the name correctly.' % deck_name) with open('deck_names.txt', 'w') as deck_names_file: deck_names_file.write('\n'.join(current_deck_names)) deck_names_file.write('\n') print('\nDeck \'%s\' has been deleted.\n' % deck_name) class Game: def __init__(self): self.player1_name = '' self.player2_name = '' def play(self): round_delay = FileFunctions.load_round_delay() self.player1_name, self.player2_name = self._get_names() deck_name = FileFunctions.load_current_deck_name() if deck_name.strip() == '': print('Please load a deck with option of 3 the main menu.') return play_again = True while play_again: # Read the deck from the deck file. deck = FileFunctions.load_deck() player1_cards = [] player2_cards = [] shuffle(deck) game_round = 1 print('\n\n') while len(deck) &gt; 0: sleep(round_delay) try: player1_card = deck[-1] player2_card = deck[-2] except IndexError: # The deck is empty break deck.pop() deck.pop() print('ROUND', game_round, '\n') winner = self._compare_cards(player1_card, player2_card) self._display_cards(player1_card, player2_card) if winner == PLAYER1: print('\nWinner:', self.player1_name) elif winner == PLAYER2: print('\nWinner:', self.player2_name) else: print('\nWinner: draw') print('\n\n') if winner == PLAYER1: player1_cards.append(player1_card) player1_cards.append(player2_card) elif winner == PLAYER2: player2_cards.append(player1_card) player2_cards.append(player2_card) # If it is a draw, the players keep their own cards. else: player1_cards.append(player1_card) player2_cards.append(player2_card) game_round += 1 if len(player1_cards) &gt; len(player2_cards): winner = self.player1_name winning_cards = player1_cards elif len(player1_cards) &lt; len(player2_cards): winner = self.player2_name winning_cards = player2_cards else: winner = DRAW winning_cards = [] print('%s has %d cards.' % (self.player1_name, len(player1_cards))) print('%s has %d cards.\n' % (self.player2_name, len(player2_cards))) print('Winner of game:', winner) if winner != DRAW: FileFunctions.write_name_and_cards(winner, winning_cards) self._display_winning_cards(winner, winning_cards) valid = False while not valid: yes_or_no = input('\nWould you like to play again? (y/n)').lower() valid = True if yes_or_no == 'n': play_again = False elif yes_or_no != 'y': print('Please answer with \'y\' or \'n\'.') valid = False print('\n\n') def _get_names(self): print('\n\n') valid = False while not valid: player1_name = input('Enter player 1\'s name: ') if '_' in player1_name: print('Names cannot contain underscores.') elif player1_name.strip() == '': print('The name must contain at least one visible character.') elif len(player1_name) &gt; 15: print('The name cannot contain more than 15 characters.') else: valid = True valid = False while not valid: player2_name = input('Enter player 2\'s name: ') if '_' in player2_name: print('Names cannot contain underscores.') elif player2_name.strip() == '': print('The name must contain at least one visible character.') elif player2_name == player1_name: print('Player 1 and player 2 must have different names.') elif len(player2_name) &gt; 15: print('The name cannot contain more than 15 characters.') else: valid = True return (player1_name, player2_name) def _display_cards(self, card1, card2): card_size = 15 p1_bg_colour = card1[COLOUR] p2_bg_colour = card2[COLOUR] if p1_bg_colour == 'black': p1_bg_colour = 'grey' if p2_bg_colour == 'black': p2_bg_colour = 'grey' if p1_bg_colour in ('grey', 'red'): p1_fg_colour = 'white' elif p1_bg_colour == 'yellow': p1_fg_colour = 'grey' if p2_bg_colour in ('grey', 'red'): p2_fg_colour = 'white' elif p2_bg_colour == 'yellow': p2_fg_colour = 'grey' p1_bg_colour = 'on_' + p1_bg_colour p2_bg_colour = 'on_' + p2_bg_colour space_between_cards = ' ' * 15 space_length = card_size - len(self.player1_name) players_string = colored(self.player1_name.upper(), p1_fg_colour, p1_bg_colour) players_string += colored(' ' * space_length, p1_fg_colour, p1_bg_colour) players_string += space_between_cards players_string += colored(self.player2_name.upper(), p2_fg_colour, p2_bg_colour) space_length = card_size - len(self.player2_name) players_string += colored(' ' * space_length, p2_fg_colour, p2_bg_colour) line = colored('=' * card_size, p1_fg_colour, p1_bg_colour) line += space_between_cards line += colored('=' * card_size, p2_fg_colour, p2_bg_colour) print(line) print(players_string) print(line) p1_number_array = self._get_number_string(card1[NUMBER]).split('\n') p2_number_array = self._get_number_string(card2[NUMBER]).split('\n') length = len(p2_number_array) if len(p2_number_array) &gt; len(p1_number_array) else len(p1_number_array) for i in range(length): output_line = '' p1_line = p1_number_array[i] for j in range(len(p1_line)): if p1_line[j] == '1': output_line += colored(' ', p1_fg_colour, 'on_' + p1_fg_colour) else: output_line += colored(' ', p1_fg_colour, p1_bg_colour) space_length = card_size - len(p1_line) output_line += colored(' ' * space_length, p1_fg_colour, p1_bg_colour) output_line += space_between_cards p2_line = p2_number_array[i] for j in range(len(p2_line)): if p2_line[j] == '1': output_line += colored(' ', p2_fg_colour, 'on_' + p2_fg_colour) else: output_line += colored(' ', p2_fg_colour, p2_bg_colour) space_length = card_size - len(p2_line) output_line += colored(' ' * space_length, p2_fg_colour, p2_bg_colour) print(output_line) def _compare_cards(self, card1, card2): if card1[COLOUR] == card2[COLOUR]: if card1[NUMBER] &gt; card2[NUMBER]: return PLAYER1 elif card1[NUMBER] &lt; card2[NUMBER]: return PLAYER2 else: return DRAW else: if card1[COLOUR] == 'red': return PLAYER1 if card2[COLOUR] == 'black' else PLAYER2 elif card1[COLOUR] == 'black': return PLAYER1 if card2[COLOUR] == 'yellow' else PLAYER2 elif card1[COLOUR] == 'yellow': return PLAYER1 if card2[COLOUR] == 'red' else PLAYER2 def _display_winning_cards(self, winner, winning_cards): while winner[-1] == ' ': winner = winner[:-1] if winner[-1].lower() == 's': winner += '\'' else: winner += '\'s' print('\n%s CARDS:\n' % winner.upper()) space_const = 15 space_after_colour = '' length_of_largest_int = len( str( len(winning_cards) + 1 ) ) for i in range(len(winning_cards)): card = winning_cards[i] space_after_colour = ' ' * ( space_const - len(card[0]) ) space_after_number = length_of_largest_int - len(str(i+1)) card_string = str(i+1) card_string += ' ' * space_after_number card_string += ' | COLOUR: ' + card[0] + space_after_colour + 'NUMBER: ' + str(card[1]) print(card_string) def _get_number_string(self, number): if number &gt; 10 or number &lt; 0: print('Invalid card', end=' ') number_strings = ( ' 1\n 1\n 1\n 1\n 1', '1111\n 1\n1111\n1 \n1111', '1111\n 1\n1111\n 1\n1111', '1 1\n1 1\n1111\n 1\n 1', '1111\n1 \n1111\n 1\n1111', '1111\n1 \n1111\n1 1\n1111', '1111\n 1\n 1\n 1\n 1', '1111\n1 1\n1111\n1 1\n1111', '1111\n1 1\n1111\n 1\n 1', '1 1111\n1 1 1\n1 1 1\n1 1 1\n1 1111' ) return number_strings[number - 1] class FileFunctions: # Reads the current deck's name def load_current_deck_name(): with open('current_deck_name.txt', 'r') as cd_file: return cd_file.read() def change_current_deck_name(new_name): with open('current_deck_name.txt', 'w') as cd_file: cd_file.write(new_name) # Writes deck to a file def write_deck(name, deck_array): deck_string = '' for card in deck_array: deck_string += card[0] deck_string += ',' deck_string += str(card[1]) deck_string += '\n' with open(name + '.txt', 'w') as deck_file: deck_file.write(deck_string) with open('deck_names.txt', 'a') as deck_names_file: deck_names_file.write(name + '\n') # Reads deck from a file and returns it as an array def load_deck(): with open('current_deck_name.txt', 'r') as current_deck_name_file: name = current_deck_name_file.read() deck_array = [] with open(name + '.txt', 'r') as deck_file: deck_text = deck_file.read() deck_text = deck_text.split('\n') for card_string in deck_text: try: card = card_string.split(',') card[1] = int(card[1]) deck_array.append( (card[0], card[1]) ) except IndexError: # The line is empty continue return deck_array def get_password(): with open('password.txt', 'r') as password_file: return password_file.read() def clear_leaderboard(): with open('leaderboard.txt', 'w'): pass # Writes name and cards to win.bin def write_name_and_cards(name, cards): # Write the name and cards to the file try: with open('leaderboard.txt', 'r') as win_file: win_string = win_file.read() except EOFError: win_string = '' win_string += name for card in cards: win_string += '\n' win_string += card[0] win_string += ',' win_string += str(card[1]) win_string += '_' with open('leaderboard.txt', 'w') as win_file: win_file.write(win_string) # Delete any players not in the top 5 # Read all players from file. with open('leaderboard.txt', 'r') as win_file: players_string = win_file.read() # Convert the string into an array. players = players_string.split('_') # Convert the array into a 2D array. for i in range(len(players)): players[i] = players[i].split('\n') # Remove [''] while players[-1] == ['']: players.pop() top5 = [] while len(top5) &lt; 5: index_of_highest = 0 for i in range(len(players)): if len(players[i]) &gt; len(players[index_of_highest]): index_of_highest = i try: top5.append(players[index_of_highest]) players.pop(index_of_highest) except IndexError: break # The players array contains less than 5 players. top5_string = '' for player in top5: top5_string += '\n'.join(player) top5_string += '_' with open('leaderboard.txt', 'w') as win_file: win_file.write(top5_string) # Returns the top 5 players from win.txt as a tuple def read_top5(): with open('leaderboard.txt', 'r') as win_file: players = win_file.read() players = players.split('_') for i in range(len(players)): players[i] = players[i].split('\n') try: while players[-1] == ['']: players.pop() except IndexError: # The players array might be empty pass return players def write_round_delay(seconds): with open('round_delay.txt', 'w') as rd_file: rd_file.write(str(seconds)) def load_round_delay(): with open('round_delay.txt', 'r') as rd_file: return float(rd_file.read()) def load_deck_names(): with open('deck_names.txt', 'r') as deck_names_file: deck_names_string = deck_names_file.read() deck_names = deck_names_string.split('\n') return deck_names if __name__ == '__main__': main() </code></pre> <p>title.txt:</p> <pre><code>============================================== |00000000000000000000000000000000000000000000| |00001111110000111100000111111000011111110000| |00010000000001000010001000000100010000001000| |00100000000010000001001000000100010000000100| |00100000000011111111001111111000010000000100| |00100000000010000001001000001000010000000100| |00010000000010000001001000000100010000001000| |00001111110010000001001000000010011111110000| |00000000000000000000000000000000000000000000| |00000000000000000000000000000000000000000000| |00011111100000111100001100000110011111111000| |00100000010001000010001010001010010000000000| |01000000000010000001001001010010010000000000| |01000001110011111111001000100010011111110000| |01000000010010000001001000000010010000000000| |00100000010010000001001000000010010000000000| |00011111100010000001001000000010011111111000| |00000000000000000000000000000000000000000000| ============================================== </code></pre> <p>password.txt contains 'Python'</p> <p>round_delay.txt contains '1.0'</p> <p>leaderboard.txt, current_deck.txt and deck_names.txt are all empty.</p>
[]
[ { "body": "<ul>\n<li><p><strong>Make it modular</strong></p>\n\n<p>For example, use <code>ask()</code>/<code>prompt()</code> for yes/no</p>\n\n<p>and</p>\n\n<pre><code>printlne()\n</code></pre>\n\n<p>where</p>\n\n<pre><code>def printlne(msg) :\n print('\\n'+msg+'\\n')\n</code></pre>\n\n<p>Instead of</p>\n\n<...
{ "AcceptedAnswerId": "205949", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T14:09:25.293", "Id": "205944", "Score": "1", "Tags": [ "python", "python-3.x", "playing-cards" ], "Title": "Python Text-based Card Game" }
205944
<p>I have created a product landing page for a <a href="https://learn.freecodecamp.org/" rel="nofollow noreferrer" title="Curriculum here">freeCodeCamp</a> responsive web design project which requires me to create a &quot;<a href="https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-product-landing-page" rel="nofollow noreferrer" title="User stories here">Product Landing Page</a>&quot;.</p> <p>Requirements to keep in mind:</p> <pre class="lang-none prettyprint-override"><code>User Story #1: My product landing page should have a header element with a corresponding id=&quot;header&quot;. User Story #2: I can see an image within the header element with a corresponding id=&quot;header-img&quot;. A company logo would make a good image here. User Story #3: Within the #header element I can see a nav element with a corresponding id=&quot;nav-bar&quot;. User Story #4: I can see at least three clickable elements inside the nav element, each with the class nav-link. User Story #5: When I click a .nav-link button in the nav element, I am taken to the corresponding section of the landing page. User Story #6: I can watch an embedded product video with id=&quot;video&quot;. User Story #7: My landing page has a form element with a corresponding id=&quot;form&quot;. User Story #8: Within the form, there is an input field with id=&quot;email&quot; where I can enter an email address. User Story #9: The #email input field should have placeholder text to let the user know what the field is for. User Story #10: The #email input field uses HTML5 validation to confirm that the entered text is an email address. User Story #11: Within the form, there is a submit input with a corresponding id=&quot;submit&quot;. User Story #12: When I click the #submit element, the email is submitted to a static page (use this mock URL: https://www.freecodecamp.com/email-submit) that confirms the email address was entered and that it posted successfully. User Story #13: The navbar should always be at the top of the viewport. User Story #14: My product landing page should have at least one media query. User Story #15: My product landing page should utilize CSS flexbox at least once. </code></pre> <hr /> <p>Here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: whitesmoke; text-align: center; } body, input, button { font-family: 'Ubuntu', sans-serif; } h1, h2, h3, .nav-link { font-family: 'Trocchi', serif; } header { position: fixed; top: 0px; left: 0px; width: 100%; height: 50px; background: #3b3b3b; text-align: right; z-index: 1; } #header-img { max-width: 100%; position: fixed; top: 0; left: 0px; } #nav-bar a { float: right; display: block; color: white; transition-duration: 0.4s; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #nav-bar a:hover { background-color: #ddd; color: black; } #form { margin-top: 55px; } #email { height: 2em; width: 15em; border-radius: 1em; padding-left: 0.6em; } #submit { height: 3em; width: 7em; border-radius: 1em; cursor: pointer; } #features-container { display: flex; flex-direction: column; align-items: center; } #features { background-color: lightgray; width: 75%; border-radius: 4em; } #features, #working, #offers { margin-top: 0px; padding: 55px; } .material-icons { font-size: 5em; } #video-container { overflow: hidden; padding-top: 56.25%; position: relative; } #video { border: 0; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } #offers-container { display: flex; justify-content: center; } #offers { background-color: grey; width: 85%; border-radius: 4em; } .offer { background-color: lightgray; margin: 0.5em; padding: 0.5em; border-radius: 1em; } /*.specs { display: inline-flex; background-color: blanchedalmond; float: center; height: 3em; width: 6em; text-decoration: none; color: black; font-weight: bold; border-radius: 1.5em; }*/ button { height: 3em; width: 6em; border-radius: 1.5em; font-weight: bold; cursor: pointer; } footer { width: 100%; background-color: lightgray; padding: 0.3em; } footer a { text-decoration: none; color: black; margin-left: 0.5em; } footer p { color: #606060; } @media (max-width: 600px) { #nav-bar { display: none; } } @media (min-width: 700px) { #video-container { padding-top: initial; } #video { position: static; height: 315px; width: 560px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en" class=""&gt; &lt;head&gt; &lt;link href="https://fonts.googleapis.com/css?family=Trocchi|Ubuntu" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;!--learn.freecodecamp.org Responsive Web Design Projects - Build a Product Landing Page--&gt; &lt;header id="header"&gt; &lt;img id="header-img" src="https://lh3.googleusercontent.com/0ir39yY3qdd6tjpgZbSZ9DiLA8Vy2BZaR4YOPrDF9tfJTf7z2m2TzM0RICdDDvO0XQrsEuGBunq1tRTD4HSyASAGtQXAcaCfqYGLzDRWqFc2UcReYMfnsc03_6J_axINZfQXYj9bNXZkUmzi2hYgGzRb-HxT_45-z18ijDQtu0GvNCHk9hX34nLbzCnj-2uNc1F0fqX-lPZmcoHLQkXc2BjnB7IDB3h-xPL2l7NqFl8pa8-9QulpH_v2KS4uB_8cYuNMErEgUXFShExxKXTXWvTuTjvEUU6h24et4jz7Vpx9AygTm8IKJL8Wb3xDzgWSG_NHdmCoEitHnzf92ns3d_LSdMnaCabIAIPTydiTln-2T0zaS6Wq61OGC3UFV_fSOSV-r4Z6NTNSw9kr63TF-VCbkAcHRYxTSbWKh-Ug3970kDaikTagL-iqpJVhC-EDyMLMNQWwoWTa_stvcnFJjZ6FGF7uPQtbiTraiFAbF5S3Qqfp2daXXiB4zxGdsm6_TJp9LbmIZHRBUoGMsooi0NXkIVkweuZnRAFK1l_RPIHMAcYuk2Hn1tQEYhBD7u1UL7U0t9XtTFfDHFYKefBs1Lxo43FpD6CMr8DKJVeAZXG88-Ctn4b3ijVuLNn2FxACDP3rIzESqTplIThhMxb1MH3argwr73Nm3oWCuWVpfY6geOXiEQBtZDRP=w300-h50-no" alt="Logo"&gt; &lt;nav id="nav-bar"&gt; &lt;a class="nav-link" href="#offers"&gt;Offers&lt;/a&gt; &lt;a class="nav-link" href="#working"&gt;Working&lt;/a&gt; &lt;a class="nav-link" href="#features"&gt;Features&lt;/a&gt; &lt;/nav&gt; &lt;/header&gt; &lt;form id="form" action="https://www.freecodecamp.com/email-submit"&gt; &lt;p&gt;Let's get started. Remain updated about the latest tech from &lt;span style="font-family: 'Trocchi', serif;"&gt;Original Nukes&lt;/span&gt; with our email feed subscription.&lt;/p&gt; &lt;p&gt;&lt;input id="email" type="email" name="email" placeholder="Enter your email" required=""&gt;&lt;/p&gt; &lt;p&gt;&lt;input id="submit" type="submit" value="Subscribe"&gt;&lt;/p&gt; &lt;/form&gt; &lt;br&gt; &lt;div id="features-container"&gt; &lt;div id="features"&gt; &lt;div&gt; &lt;i class="material-icons"&gt;security&lt;/i&gt; &lt;h2&gt;Premium Materials&lt;/h2&gt; &lt;div&gt;Our nuclear explosives use the purest form of Uranium-365 which is sourced overseas. This ensures longer shelf life and a smoother destruction.&lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;div&gt; &lt;i class="material-icons"&gt;local_shipping&lt;/i&gt; &lt;h2&gt;Safest Shipping&lt;/h2&gt; &lt;div&gt;We make sure that the nuclear arsenals reach their destination in a safe and environment friendly way. We also provide insurance for any kind of environmental damage and transportation losses.&lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;div&gt; &lt;i class="material-icons"&gt;check_box&lt;/i&gt; &lt;h2&gt;Quality Assurance&lt;/h2&gt; &lt;div&gt;For every purchase you make, we will ensure there are no damages or faults. We check and verify that there do not remain faults of any kind in any model of our nukes.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;div id="working"&gt; &lt;h1&gt;Get an idea of how the nukes appear when they are in action.&lt;/h1&gt; &lt;div id="video-container"&gt;&lt;iframe id="video" src="https://www.youtube-nocookie.com/embed/ETag3issaSE?rel=0&amp;amp;showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen=""&gt;&lt;/iframe&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="offers-container"&gt; &lt;div id="offers"&gt; &lt;div class="offer"&gt; &lt;h2&gt;Alert series&lt;/h2&gt; &lt;i class="material-icons"&gt;battery_alert&lt;/i&gt; &lt;div&gt;$40 million&lt;/div&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a lacus euismod, interdum.&lt;/div&gt;&lt;br&gt; &lt;button&gt;Specs&lt;/button&gt; &lt;/div&gt; &lt;div class="offer"&gt; &lt;h2&gt;Full charge series&lt;/h2&gt; &lt;i class="material-icons"&gt;battery_charging_full&lt;/i&gt; &lt;div&gt;$ 60 million&lt;/div&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque facilisis est ut elit.&lt;/div&gt;&lt;br&gt; &lt;button&gt;Specs&lt;/button&gt; &lt;/div&gt; &lt;div class="offer"&gt; &lt;h2&gt;Unknown series&lt;/h2&gt; &lt;i class="material-icons"&gt;battery_unknown&lt;/i&gt; &lt;div&gt;$ 50 million&lt;/div&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi viverra neque a turpis.&lt;/div&gt;&lt;br&gt; &lt;button&gt;Specs&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;footer&gt; &lt;a href="#"&gt;Privacy&lt;/a&gt; &lt;a href="#"&gt;Terms&lt;/a&gt; &lt;a href="https://www.freecodecamp.org/ayudh-khajne"&gt;Contact&lt;/a&gt; &lt;p&gt;Copyright 2100, Original Nukes&lt;/p&gt; &lt;/footer&gt; &lt;script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <hr /> <h1>For review</h1> <p>I would like to receive &quot;code review&quot; &amp; suggestions on the following:</p> <ul> <li><strong>iframe &amp; related CSS</strong>: whether the code can be simplified. The video should be responsive, maximum 560 px wide, horizontally centred, and maintain its aspect ratio.</li> <li><strong>footer</strong>: there is some unwanted margin around footer.</li> <li><strong>design &amp; positioning etc.</strong>: some <strong>basic</strong> (nothing much difficult and more than the freeCodeCamp curriculum)</li> <li><strong>colour</strong>: suggestions for better colour combinations (without changing the overall theme), keeping in mind readability and accessibility like colour blindness, etc.</li> <li><strong>optimizations</strong>: code optimization, simplification, tidying, spotting duplicate code, etc.</li> <li><strong>grammar</strong>, maybe.</li> <li>And finally, <em><strong>review for entire code</strong></em> is welcome.</li> </ul> <hr /> <h2>Link to Web Page</h2> <p><a href="https://codepen.io/ayudh/full/WadaRm/" rel="nofollow noreferrer" title="Project here">Codepen</a> - This code may be updated anytime.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T17:44:12.683", "Id": "205947", "Score": "2", "Tags": [ "html", "css", "html5", "user-interface" ], "Title": "FCC: Product Landing Page - HTML & CSS only" }
205947
<p>I have a get route to show the data for a chat with another user. If an existing chat exists I want to return that, otherwise create a new chat and return it.</p> <pre><code>/chat/user/{contra_user_id} </code></pre> <p>Should my Service or my repository be adding chat members to the chat? Currently I have my service creating each member.</p> <pre><code>class ChatService { private $chatRepository; public function __construct(ChatRepository $chatRepository) { $this-&gt;chatRepository = $chatRepository; } public function findByUsers(User $user, User $contraUser) : Collection { $chat = $this-&gt;chatRepository-&gt;findByUsers($user, $contraUser); if ($chat = $chat-&gt;first()) { return $chat; } $chat = $this-&gt;chatRepository-&gt;create(); $member = $this-&gt;chatMemberRepository-&gt;create($chat, $user); $contraMember = $this-&gt;chatMemberRepository-&gt;create($chat, $user); $returnChat = $this-&gt;chatRepository-&gt;find($chat-&gt;id); return $returnChat; } } </code></pre>
[]
[ { "body": "<p>You can break the functionality in to 2 seperate methods to make it more reusable. Here, <code>findChatByUsers</code> could return a collection or null, so the type hint was removed.</p>\n\n<pre><code>public function findChatByUsers(User $user, User $contraUser)\n{\n $chat = $this-&gt;chatRepos...
{ "AcceptedAnswerId": "206096", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T20:01:51.830", "Id": "205952", "Score": "1", "Tags": [ "php", "mvc", "laravel", "repository" ], "Title": "Showing data for a chat with another user" }
205952
<p>I'm kinda new to programming, and as a solution to an exercise, I made a program to find prime numbers in a range. It runs just right for small ranges of numbers, but for this exercise we are given a high range of nums, and it just takes much time to finish examining. Any suggestions how can I make it faster?</p> <pre><code>#include &lt;stdio.h&gt; #define START 190000000 #define END 200000000 int main() { int primenum = 0, i = 0, j = 0, c = 0; for (i = START; i &lt;= END; i++) { printf("EXMINING %d\r\n", i); c = 2; for (j = 2; j &lt;= i-1; j++) { if (i%j == 0) { c=1; break; } } if (c == 2) primenum = primenum + 1; printf("Prime Numbers Found so far: %d\r\n", primenum); } printf("THE PRIME NUMBERS ARE %d", primenum); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T21:05:47.263", "Id": "397258", "Score": "4", "body": "You probably are after a sieve of eratosthenes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-19T14:25:06.900", "Id": "421307", "Score": "0...
[ { "body": "<p>I combine here all the above and look up tables.</p>\n\n<ol>\n<li>Use the threshold of sqrt(test_prime) to shrink the range to be tested, as said by @Gaurav.</li>\n<li>Increase the prime number to be tested by 2, as said by @1201ProgramAlarm.</li>\n<li>Use a look up tables to check only with the p...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T20:35:17.473", "Id": "205955", "Score": "3", "Tags": [ "beginner", "c", "time-limit-exceeded", "primes" ], "Title": "Program that finds prime numbers in a specific range" }
205955
<p>I'm working on a small open source project called CSV-simplified for a course I'm taking (Bloc), and I'm looking for some feedback and potential collaborators. I don't actually know an programmers, so I'm hoping someone here may be interested in helping out.</p> <p>The basic idea of CSV-simplified is a browser app capable of reading a CSV file and displaying it on the page. I would like to expand upon this by creating an intuitive user interface to allow the user to perform searches and queries on the uploaded file. I'm currently using JavaScript, jQuery, and PapaParse to just display an uploaded file.</p> <p>I'm looking for any help, suggestions, or feedback on improving and building upon this program. The first thing I'd like to see improved is how the file is displayed, I think editing the JS and adding some CSS could really spruce it up.</p> <p><a href="https://github.com/conkytom/CSV-simplified" rel="nofollow noreferrer">Here's</a> the GitHub repo of what's done so far. <a href="https://codepen.io/anon/pen/JmWygV" rel="nofollow noreferrer">Here's</a> a Codepen that shows the basic logic that's currently working on the app.</p> <p>HTML</p> <pre><code>&lt;input type="file" name="File Upload" id="txtFileUpload" accept=".csv" /&gt; &lt;div id="header"&gt;&lt;/div&gt; </code></pre> <p>JavaScript</p> <pre><code>document.getElementById('txtFileUpload').addEventListener('change', upload, false); function upload(evt) { var data = null; var file = evt.target.files[0]; var reader = new FileReader(); reader.readAsText(file); reader.onload = function(event) { var csvData = event.target.result; var data = Papa.parse(csvData, {header : false}); console.log(data.data); var arrayLength = data.data.length; console.log(arrayLength); for (var i = 0; i &lt; arrayLength; i++) { console.log(data.data[i]); $("#header").append("&lt;li&gt;" + JSON.stringify(data.data[i]) + "&lt;/li&gt;"); } }; reader.onerror = function() { alert('Unable to read ' + file.fileName); }; } </code></pre>
[]
[ { "body": "<h1>Review</h1>\n\n<p>Hi and welcome to code review.</p>\n\n<p>To help out I have numbered the lines of your code for reference.</p>\n\n<p>I will ignore the <code>console.log</code> calls as they represent debugging code.</p>\n\n<ul>\n<li><p><strong>Line 3</strong> Bad function name. You are not uplo...
{ "AcceptedAnswerId": "206024", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T20:37:00.440", "Id": "205956", "Score": "2", "Tags": [ "javascript", "html", "css", "csv", "angular.js" ], "Title": "CSV-simplified: A small open source project" }
205956
<p>This countdown timer is supposed to:</p> <ol> <li>be synced to the user's clock</li> <li>at every hour and half hour, will start a 25 minute countdown followed by a 5 minute break</li> </ol> <p>The code works but I question its efficiency.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function startTime() { var today = new Date(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); //makes the clock count DOWN instead of up if (minutes&lt;25 &amp;&amp; seconds&lt;60) { document.getElementById("message").innerHTML = "WORK TIME"; minutes=24-minutes; seconds=60-seconds; } else if (minutes&lt;30 &amp;&amp; seconds&lt;60){ document.getElementById("message").innerHTML = "BREAK TIME"; minutes=29-minutes; seconds=60-seconds; } else if (minutes&lt;55 &amp;&amp; seconds&lt;60){ document.getElementById("message").innerHTML = "WORK TIME"; minutes=54-minutes; seconds=60-seconds; } else { document.getElementById("message").innerHTML = "BREAK TIME"; minutes=59-minutes; seconds=60-seconds; } //to make clock show correct format, e.g., 2:59 instead of 03:60 if (seconds == 60){ seconds=0; minutes=minutes+1; } document.getElementById('txt').innerHTML= minutes+" min and "+seconds+" sec remaining"; } setInterval(startTime, 1000);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onload="startTime()"&gt; &lt;h1 id="message"&gt;&lt;h1&gt; &lt;div id="txt"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>Bug</h2>\n<ul>\n<li><p>There is an off chance that the interval event that you start at the bottom of the script with <code>setInterval(startTime, 1000);</code> will fire before the page has fully loaded, causing the first run to throw an error at <code>document.getElementById(&quot;message&quot;...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T23:07:43.290", "Id": "205962", "Score": "4", "Tags": [ "javascript", "timer" ], "Title": "Pomodoro countdown timer synced to the clock" }
205962
<p>This question was originally posted on <a href="https://stackoverflow.com/q/52908302/1014587">Stack Overflow</a>.</p> <p>You can see the before and after there, but here's the after that I'd like to bring for review here. </p> <p>The goal of this script is to polyfill any browsers I'm supporting that don't natively have position: sticky. Example: I'm thinking about detecting IE11 and running this script only there. </p> <h3>My questions then are:</h3> <ol> <li>Does structuring this code as a class makes sense here? </li> <li>Is there anything obvious about my class that's wrong?</li> <li>How should I export this as an ES6 module?</li> <li>Any other advice?</li> </ol> <p>Code structure is the one big thing I struggle with with JS, and so I'd greatly appreciate any feedback you have. </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 makeSticky { constructor(el) { this.element = el; this.fixedClass = 'is-fixed'; this.parent = this.element.parentNode; this.position = this.element.offsetTop; this.parentBottom = this.parent.clientHeight + this.parent.offsetTop; } init() { this.addEvents(); this.onScroll(); } addEvents() { window.addEventListener('scroll', this.onScroll.bind(this)); } onScroll(event) { if (this.aboveScroll() &amp;&amp; this.stillInsideParent()) { this.setFixed(); } else { this.setStatic(); } } aboveScroll() { return this.position &lt; window.scrollY; } stillInsideParent() { return this.parentBottom &gt; window.scrollY; } onScroll(event) { if (this.aboveScroll() &amp;&amp; this.stillInsideParent()) { this.setFixed(); } else { this.setStatic(); } } setFixed() { this.element.classList.add(this.fixedClass); } setStatic() { this.element.classList.remove(this.fixedClass); } } const children = document.querySelectorAll('.child'); children.forEach(child =&gt; { const sitck = new makeSticky(child); sitck.init(); });.</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code> .wrapper { max-width: 800px; margin: 60px auto; } .is-flex { display: flex; } .sidebar { width: 300px; flex: none; background: #eee; } .child { color: red; } .is-fixed { position: fixed; top: 20px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="app"&gt; &lt;div class="wrapper is-flex parent"&gt; &lt;div id="main" class="main"&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;/div&gt; &lt;div class="sidebar"&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;h2 class="child first"&gt;Title one should be sticky&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper is-flex parent"&gt; &lt;div class="main"&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;/div&gt; &lt;div class="sidebar"&gt; &lt;h2 class="child two"&gt;Title two should be sticky&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;h2&gt;A full width thing might go down here before another wrapper starts&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T07:58:44.173", "Id": "397273", "Score": "0", "body": "Welcome to Code Review! Please take a look at our FAQ on [How to get the best value out of Code Review - Asking Questions](https://codereview.meta.stackexchange.com/q/2436/52915)...
[ { "body": "<h1>Review</h1>\n<p>First up Welcome to code review :)</p>\n<p>A quick note that the posted code is broken, it throws an error when the snippet runs, and the object <code>makeSticky</code> has a duplicated property <code>onScroll</code></p>\n<p>As you are new I will say you don't have to accept the f...
{ "AcceptedAnswerId": "205975", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-20T23:49:23.593", "Id": "205964", "Score": "0", "Tags": [ "javascript" ], "Title": "A JavaScript-based fallback for position: sticky" }
205964
<p>I've published a new TypeScript library currently in beta, and was hoping to get feedback on certain aspects of it, particularly implementation details for improving the performance of deferred iteration in some specific methods.</p> <p>The library is called <a href="https://github.com/patrickroberts/enumerable-ts" rel="nofollow noreferrer"><code>enumerable-ts</code></a> and is available <a href="https://www.npmjs.com/package/enumerable-ts" rel="nofollow noreferrer">on npm</a>. I don't anticipate that it will be particularly impressive in any benchmarks but I'd at least like to refine some of the method implementations so that the asymptotic performance is better if possible, and also readability.</p> <p>Below are some of the methods I'd like to improve:</p> <p><a href="https://github.com/patrickroberts/enumerable-ts/blob/777d4480c1f8df33790b56be2ab4a11c9571fed8/src/enumerable.ts#L322-L352" rel="nofollow noreferrer"><code>Enumerable.prototype.distinct()</code></a> (modified but not yet committed)</p> <pre><code>distinct (this: IEnumerable&lt;TSource&gt;, equality: EqualityFunction&lt;TSource&gt; = equalityFn): Enumerable&lt;TSource&gt; { return new Enumerable(function * (this: IEnumerable&lt;TSource&gt;, equality: EqualityFunction&lt;TSource&gt;) { const set = equality === equalityFn ? new Set&lt;TSource&gt;() : [] as TSource[] const unique = (value: TSource) =&gt; { if (set.contains(value, equality)) { return false } if (set instanceof Set) set.add(value) else set.push(value) return true } yield * this.where(unique) }.bind(this, equality), Enumerable.isEnumerable(this) ? this.compare : undefined) } </code></pre> <p>The problem with <code>distinct()</code> was that it didn't seem very DRY, given that the implementation was essentially twice as long since it basically had analogous approaches for the general case and the optimized case when you can rely on the comparison behavior of the builtin <code>Set</code>, i.e. when the <code>equality</code> parameter uses the default behavior. Is this an acceptable way of making the method more succinct or is there an even better way?</p> <p><a href="https://github.com/patrickroberts/enumerable-ts/blob/777d4480c1f8df33790b56be2ab4a11c9571fed8/src/enumerable.ts#L437-L454" rel="nofollow noreferrer"><code>Enumerable.prototype.groupJoin()</code></a></p> <pre><code>groupJoin&lt;TInner, TKey&gt; (this: IEnumerable&lt;TSource&gt;, inner: IEnumerable&lt;TInner&gt;, selectOuterKey: IndexedSelectFunction&lt;TSource, TKey&gt;, selectInnerKey: IndexedSelectFunction&lt;TInner, TKey&gt;): Enumerable&lt;IGrouping&lt;TSource, TInner&gt;&gt; groupJoin&lt;TInner, TKey, TResult&gt; (this: IEnumerable&lt;TSource&gt;, inner: IEnumerable&lt;TInner&gt;, selectOuterKey: IndexedSelectFunction&lt;TSource, TKey&gt;, selectInnerKey: IndexedSelectFunction&lt;TInner, TKey&gt;, selectResult: ResultFunction&lt;TSource, IEnumerable&lt;TInner&gt;, TResult&gt;): Enumerable&lt;TResult&gt; groupJoin&lt;TInner, TKey, TResult&gt; (this: IEnumerable&lt;TSource&gt;, inner: IEnumerable&lt;TInner&gt;, selectOuterKey: IndexedSelectFunction&lt;TSource, TKey&gt;, selectInnerKey: IndexedSelectFunction&lt;TInner, TKey&gt;, selectResult?: ResultFunction&lt;TSource, IEnumerable&lt;TInner&gt;, TResult&gt;): Enumerable&lt;IGrouping&lt;TSource, TInner&gt;&gt; | Enumerable&lt;TResult&gt; { const outerEntries = this.select(selectEntry(selectOuterKey, selectFn as SelectFunction&lt;TSource, TSource&gt;)) const innerGroups = inner.groupBy(selectInnerKey) const groups = outerEntries.select( ([outerKey, outer]) =&gt; new Grouping&lt;TSource, TInner&gt;(function * (innerGroups: IEnumerable&lt;IGrouping&lt;TKey, TInner&gt;&gt;, outerKey: TKey) { yield * innerGroups.firstOrDefault( new Grouping(generatorFn as () =&gt; IterableIterator&lt;TInner&gt;, outerKey), ({ key }) =&gt; equalityFn(key, outerKey) ) }.bind(innerGroups, outerKey), outer) as IGrouping&lt;TSource, TInner&gt; ) return selectResult === undefined ? groups : groups.select((group, index) =&gt; selectResult(group.key, group.asEnumerable(), index)) } </code></pre> <p>While I'm fairly certain this implementation matches the expected behavior ported from <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupjoin" rel="nofollow noreferrer"><code>Enumerable.GroupJoin()</code></a> in .NET, I find the logic to be quite unfollow-able without several minutes spent studying the code. I'd like to improve this.</p> <p><a href="https://github.com/patrickroberts/enumerable-ts/blob/777d4480c1f8df33790b56be2ab4a11c9571fed8/src/enumerable.ts#L501-L518" rel="nofollow noreferrer"><code>Enumerable.prototype.memoize()</code></a></p> <pre><code>memoize (this: IEnumerable&lt;TSource&gt;): Enumerable&lt;TSource&gt; { const cache: TSource[] = [] const iterator = this[Symbol.iterator]() return new Enumerable(function * (this: IEnumerable&lt;TSource&gt;, cache: TSource[], iterator: IterableIterator&lt;TSource&gt;) { for (let index = 0; ; index++) { if (index === cache.length) { const { value, done } = iterator.next() if (done) return cache[index] = value } yield cache[index] } }.bind(this, cache, iterator), Enumerable.isEnumerable(this) ? this.compare : undefined) } </code></pre> <p>While I'm actually fairly proud of the simplicity of this implementation, I'm curious if this is actually the expected behavior. Do people expect multiple calls to <code>memoize()</code> with the same target <code>IEnumerable</code> to produce the same sequence? Or is it just multiple references to a return value of <code>memoize()</code> should always produce the same sequence (as is currently implemented)? It's based on the implementation from MoreLINQ's <a href="https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/Experimental/Memoize.cs" rel="nofollow noreferrer"><code>Memoize()</code></a>.</p> <p><a href="https://github.com/patrickroberts/enumerable-ts/blob/777d4480c1f8df33790b56be2ab4a11c9571fed8/src/enumerable.ts#L636-L646" rel="nofollow noreferrer"><code>Enumerable.prototype.skip()</code></a></p> <pre><code>skip (this: IEnumerable&lt;TSource&gt;, count: number): Enumerable&lt;TSource&gt; { if (Array.isArray(this)) { return new Enumerable(function * (this: TSource[], count: number) { for (let index = count; index &lt; this.length; index++) { yield this[index] } }.bind(this, count)) } return this.where((_, index) =&gt; index &gt;= count) } </code></pre> <p>The obvious problem with this one, is the lack of introspection available on the <code>Enumerable</code> class (and <code>Map</code> and <code>Set</code>) to be able to seek to specific indices of the iteration. Is there a way of making this introspection possible on the <code>Enumerable</code> class without too much bloat? This would actually improve the performance of a whole class of methods on <code>Enumerable</code>, not just <code>skip()</code>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T00:40:33.157", "Id": "205965", "Score": "1", "Tags": [ "performance", "object-oriented", "iterator", "typescript" ], "Title": "Deferred Iteration in TypeScript" }
205965
<p>I have recently started learning functional programming and Haskell. I have encountered this problem:</p> <blockquote> <p>Consider three two-dimensional points a, b, and c. If we look at the angle formed by the line segment from a to b and the line segment from b to c, it either turns left, turns right, or forms a straight line. Define a Direction data type that lets you represent these possibilities. Write a function that calculates the turn made by three 2D points and returns a Direction.</p> </blockquote> <p>I have heard that one of the goals of the Haskell language is to create elegant solutions.</p> <p>This is my solution:</p> <pre><code>data Direction = LeftTurn | RightTurn | Straight deriving Show findDirection (x, y) (x1, y1) (x2, y2) | (x, y) == (x1, y1) = Straight | (x1, y1) == (x2, y2) = Straight | (x, y) == (x2, y2) = Straight | x == x1 &amp;&amp; x1 == x2 = Straight | x1 == x &amp;&amp; y1 &gt; y &amp;&amp; x2 &gt; x = RightTurn | x1 == x &amp;&amp; y1 &gt; y &amp;&amp; x2 &lt; x = LeftTurn | x1 == x &amp;&amp; y1 &lt; y &amp;&amp; x2 &lt; x = RightTurn | x1 == x &amp;&amp; y1 &lt; y &amp;&amp; x2 &gt; x = LeftTurn | x1 &gt; x &amp;&amp; y2 &gt; y_on_line = LeftTurn | x1 &gt; x &amp;&amp; y2 &lt; y_on_line = RightTurn | x1 &gt; x &amp;&amp; y2 == y_on_line = Straight | x1 &lt; x &amp;&amp; y2 &gt; y_on_line = RightTurn | x1 &lt; x &amp;&amp; y2 &lt; y_on_line = LeftTurn | x1 &lt; x &amp;&amp; y2 == y_on_line = Straight where y_on_line = slope * x2 + y_intercept slope = (y1 - y) / (x1 - x) y_intercept = y - slope * x </code></pre> <p>This looks like it is too long to be considered an elegant solution.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T01:10:39.477", "Id": "397262", "Score": "1", "body": "Think about a planar [cross product](https://en.wikipedia.org/wiki/Cross_product) and its sign." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T07...
[ { "body": "<p>This is not a review, but an extended comment.</p>\n\n<blockquote>\n <p>I have heard that one of the goals of the Haskell language is to create elegant solutions.</p>\n</blockquote>\n\n<p>It seems like a major misconception. The elegance of the solution does not depend on the language. The langua...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T00:45:30.543", "Id": "205966", "Score": "4", "Tags": [ "beginner", "haskell", "computational-geometry" ], "Title": "Determine whether path A→B→C on a plane constitutes a left or right turn" }
205966
<p>Example image:</p> <p><a href="https://i.stack.imgur.com/CVOVU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CVOVU.png" alt="barcode"></a></p> <p>Code:</p> <pre><code>#get height and width of image height, width = possible_barcode_img.shape[:2] #prepare list for rows barcode_rows = [] for i in range(height): # set variables and list for beginning of row white_bar_width = 0 black_bar_width = 0 barcode_row = [] for j in range(width): if possible_barcode_img[i,j] == 0: #add to count black_bar_width = black_bar_width +1 #ensure last bar is gotten if there was one if white_bar_width &gt; 0: #add bar to row barcode_row.append(["white", white_bar_width]) white_bar_width = 0 elif possible_barcode_img[i,j] &gt; 0: #add to width white_bar_width = white_bar_width +1 #ensure last bar is gotten if there was one if black_bar_width &gt; 0: #add bar to row barcode_row.append(["black", black_bar_width]) black_bar_width = 0 #ensure last bar is gotten since a row just finished if white_bar_width &gt; 0: #add bar to row barcode_row.append(["white", white_bar_width]) elif black_bar_width &gt; 0: #add bar to row barcode_row.append(["black", black_bar_width]) #add entire row to rows barcode_rows.append(barcode_row) </code></pre> <p>Print row 50 of the picture in the question <code>print(barcode_rows[50])</code>:</p> <pre><code>[['black', 3], ['white', 7], ['black', 4], ['white', 6], ['black', 4], ['white', 6], ['black', 13], ['white', 5], ['black', 4], ['white', 15], ['black', 4], ['white', 5], ['black', 5], ['white', 5], ['black', 13], ['white', 15], ['black', 13], ['white', 5], ['black', 13], ['white', 6], ['black', 3], ['white', 15], ['black', 5], ['white', 4], ['black', 4], ['white', 14], ['black', 13], ['white', 6], ['black', 4], ['white', 14], ['black', 13], ['white', 14], ['black', 5], ['white', 5], ['black', 4], ['white', 5], ['black', 4], ['white', 14], ['black', 4], ['white', 5], ['black', 4], ['white', 5], ['black', 13], ['white', 14], ['black', 13], ['white', 5], ['black', 14], ['white', 4], ['black', 5], ['white', 4]] </code></pre> <p>50 bars found as in the picture, ready for decoding.</p> <p>This has quite an effect on fps when doing it with video. I know that I don't have to loop through the entire image, I will have it send to a decoder after each row of pixels and end the loop if successful.</p> <p>However I'm hoping there's a more optimized way to do this than using the Python loops on each individual pixel because I don't think the above will be fast enough for my needs.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T19:44:17.237", "Id": "397316", "Score": "0", "body": "With code bar type you use? I think it is `Interleaved 2 of 5`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T19:48:59.537", "Id": "397318...
[ { "body": "<p>You don't need a number of pixels, you need to detect narrow bars and wide bars. Use first black and white bar width as a pattern with 15% margin for next bars. The wide bar has 2.0 to 3.0 times the width of a narrow bar. Try to detect start or stop code at the begin of selected line, if it is cor...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T01:38:21.557", "Id": "205968", "Score": "4", "Tags": [ "python", "numpy", "opencv" ], "Title": "Loops through each row in a binary image and gets the width of each group of black or white pixels" }
205968
<h2>Purpose</h2> <p>I managed to get completely nerd-sniped earlier today <a href="https://stackoverflow.com/q/52907893/4088852">by a question over on SO</a> and decided to take a stab at adapting my numeric input wrapper for <code>TextBox</code>es into one that would handle numeric date input in various different formats and automatically add the delimiters.</p> <p>I usually do VBA user input handling into wrapper classes that handle the appropriate events for 2 main reasons: First, it takes a lot of superfluous clutter out of the form's code-behind - if I'm using several different input wrappers, it can get messy fast (evidenced by the size of this one). Second, it makes it a lot easier to import them into a project that will use them.</p> <p>Note that the second goal is driving the architecture somewhat - if this was implemented as a stand-alone ActiveX control that was referenced by the project, I would have split it up into several different classes to address specific areas of concern.</p> <hr> <h2>Other Design Considerations</h2> <p>There are a couple things that people commonly get wrong with using the UI events to limit data input into a <code>TextBox</code>. This implementation addresses the following:</p> <ul> <li>Keyboard input is <strong><em>not</em></strong> the only way that input needs to be handled. The MSForms <code>TextBox</code> also supports copy and paste, drag and drop, data binding, etc.</li> <li>The representation of the data in the <code>Text</code> property is not necessarily the value that you're looking for from the user. What is displayed should be treated as UX, not data.</li> <li>Validation feedback should not be performed by the control - it should expose a way to check for validity, but how that is handled (i.e. displaying a message box, setting focus back, etc.) should be up to the parent of the control.</li> </ul> <hr> <h2>Implementation</h2> <p>The following code all goes in a class module named DateInputWrapper.cls - it is split into sections below for readability on SE. The full class is available <a href="https://pastebin.com/NbdWCDDr" rel="nofollow noreferrer">on Pastebin</a> (no, that really is their VB syntax highlighting...).</p> <p><strong>Declarations Section</strong></p> <pre><code>Option Explicit Public Enum DateOrder MDY DMY YMD End Enum Private Type DateInputWrapperMembers Delimiter As String TwoDigitYear As Boolean Order As DateOrder NumericDate As String End Type Private Const DELETE_KEY As Integer = 46 Private Const BACKSPACE_KEY As Integer = 8 Private this As DateInputWrapperMembers Private WithEvents wrapped As MSForms.TextBox Private formatting As Boolean </code></pre> <p><strong>Public Members</strong></p> <pre><code>Private Sub Class_Initialize() this.Delimiter = "-" this.Order = DateOrder.YMD End Sub Public Property Set Wrapping(ByVal rhs As MSForms.TextBox) Set wrapped = rhs End Property Public Property Get Wrapping() As MSForms.TextBox Set Wrapping = wrapped End Property Public Property Let Delimiter(ByVal rhs As String) If Len(rhs) &gt; 1 Then Err.Raise 5 'invalid argument End If this.Delimiter = rhs End Property Public Property Get Delimiter() As String Delimiter = this.Delimiter End Property Public Property Let Order(ByVal rhs As DateOrder) this.Order = rhs End Property Public Property Get Order() As DateOrder Order = this.Order End Property Public Property Let TwoDigitYear(ByVal rhs As Boolean) this.TwoDigitYear = rhs End Property Public Property Get TwoDigitYear() As Boolean TwoDigitYear = this.TwoDigitYear End Property Public Property Let DateValue(ByVal Value As Variant) Dim valueType As VbVarType valueType = VarType(Value) Select Case True Case valueType = vbDate, IsNumeric(Value) LoadFromDate CDate(Value) SetTextFromInternal Case valueType = vbString wrapped.Text = CStr(Value) Case Else Err.Raise 5 'invalid argument End Select End Property 'Output value, returns Empty if invalid. Public Property Get DateValue() As Variant If Not IsValidDate Then Exit Property DateValue = DateSerial(CInt(YearValue), CInt(MonthValue), CInt(DayValue)) End Property 'Returns a string suitable for passing to Format$ that matches the TextBox setup. Public Property Get DateFormat() As String Dim yearFormat As String yearFormat = String$(IIf(TwoDigitYear, 2, 4), "y") Select Case Order Case DateOrder.MDY DateFormat = "mm" &amp; Delimiter &amp; "dd" &amp; Delimiter &amp; yearFormat Case DateOrder.DMY DateFormat = "dd" &amp; Delimiter &amp; "mm" &amp; Delimiter &amp; yearFormat Case DateOrder.YMD DateFormat = yearFormat &amp; Delimiter &amp; "mm" &amp; Delimiter &amp; "dd" End Select End Property Public Property Get FormattedDate() As String ReDim elements(2) As String Select Case Order Case DateOrder.MDY elements(0) = MonthValue elements(1) = DayValue elements(2) = YearValue Case DateOrder.DMY elements(0) = DayValue elements(1) = MonthValue elements(2) = YearValue Case DateOrder.YMD elements(0) = YearValue elements(1) = MonthValue elements(2) = DayValue End Select If elements(0) = vbNullString Then Exit Property Dim idx As Long For idx = 1 To 2 If elements(idx) = vbNullString Then ReDim Preserve elements(idx - 1) Exit For End If Next FormattedDate = Join(elements, this.Delimiter) End Property Public Property Get IsValidDate() As Boolean Select Case False Case Len(YearValue) &lt;&gt; IIf(this.TwoDigitYear, 2, 4) Case Len(DayValue) &lt;&gt; 2 Case Len(MonthValue) &lt;&gt; 2 Case Else Exit Property End Select Dim dayOfMonth As Long, valueOfYear As Long dayOfMonth = CLng(DayValue) valueOfYear = CLng(YearValue) If this.TwoDigitYear Then 'Note: This will break in the year 2100. valueOfYear = valueOfYear + IIf(valueOfYear &lt; CLng(Year(Date)) Mod 100, 2000, 1900) ElseIf valueOfYear &lt; 100 Then Exit Property End If Select Case CLng(MonthValue) Case 2 If IsLeapYear(valueOfYear) Then IsValidDate = dayOfMonth &gt; 0 And dayOfMonth &lt;= 29 Else IsValidDate = dayOfMonth &gt; 0 And dayOfMonth &lt;= 28 End If Case 4, 6, 9, 11 IsValidDate = dayOfMonth &gt; 0 And dayOfMonth &lt;= 30 Case 1, 3, 5, 7, 8, 10, 12 IsValidDate = dayOfMonth &gt; 0 And dayOfMonth &lt;= 31 End Select End Property </code></pre> <p><strong>Event Handlers</strong></p> <pre><code>Private Sub wrapped_Change() 'Prevent re-entry from SetTextFromInternal If formatting Then Exit Sub With Wrapping 'Handle pasting and drag-drop, and any other random input methods. If .Text Like "*[!0-9" &amp; Delimiter &amp; "]*" Then SetTextFromInternal Exit Sub End If 'Handle keyboard input. this.NumericDate = Left$(Replace$(.Text, Delimiter, vbNullString), IIf(this.TwoDigitYear, 6, 8)) SetTextFromInternal End With End Sub 'Accept only numbers, and limit digits. Private Sub wrapped_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) If Not Chr$(KeyAscii) Like "[0-9]" Or Len(this.NumericDate) = IIf(this.TwoDigitYear, 6, 8) Then KeyAscii.Value = 0 End If End Sub 'Delete and backspace are handled on key-down to keep the internal version in sync. Private Sub wrapped_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) With wrapped Dim caret As Long, characters As Long caret = .SelStart characters = .SelLength If KeyCode &lt;&gt; BACKSPACE_KEY And KeyCode &lt;&gt; DELETE_KEY Then If .SelLength &gt; 0 Then 'Over-typing selection. HandleSelectionDelete .SelStart, characters End If Exit Sub End If Dim newCaret As Long If KeyCode = BACKSPACE_KEY And characters = 0 Then newCaret = HandleBackspace(caret, characters) ElseIf characters = 0 Then newCaret = HandleDelete(caret) Else newCaret = HandleSelectionDelete(.SelStart, characters) End If End With SetTextFromInternal newCaret KeyCode.Value = 0 End Sub </code></pre> <p><strong>Private Members</strong></p> <pre><code>Private Property Get YearValue() As String If Order = DateOrder.YMD Then YearValue = Left$(this.NumericDate, IIf(this.TwoDigitYear, 2, 4)) Else Dim characters As Long characters = Len(this.NumericDate) If characters &lt;= 4 Then Exit Property YearValue = Right$(this.NumericDate, characters - 4) End If End Property Private Property Get MonthValue() As String Select Case Order Case DateOrder.DMY MonthValue = Mid$(this.NumericDate, 3, 2) Case DateOrder.MDY MonthValue = Left$(this.NumericDate, 2) Case DateOrder.YMD MonthValue = Mid$(this.NumericDate, IIf(this.TwoDigitYear, 3, 5), 2) End Select End Property Private Property Get DayValue() As String Select Case Order Case DateOrder.MDY DayValue = Mid$(this.NumericDate, 3, 2) Case DateOrder.DMY DayValue = Left$(this.NumericDate, 2) Case DateOrder.YMD Dim characters As Long characters = Len(this.NumericDate) - 2 - IIf(this.TwoDigitYear, 2, 4) If characters &lt;= 0 Then Exit Property DayValue = Right$(this.NumericDate, characters) End Select End Property Private Sub LoadFromDate(ByVal Value As Date) Dim formattedYear As String formattedYear = Right$(CStr(Year(Value)), IIf(this.TwoDigitYear, 2, 4)) Select Case Order Case DateOrder.MDY this.NumericDate = Format$(Month(Value), "00") &amp; Format$(Day(Value), "00") &amp; formattedYear Case DateOrder.DMY this.NumericDate = Format$(Day(Value), "00") &amp; Format$(Month(Value), "00") &amp; formattedYear Case DateOrder.YMD this.NumericDate = formattedYear &amp; Format$(Month(Value), "00") &amp; Format$(Day(Value), "00") End Select End Sub Private Sub SetTextFromInternal(Optional ByVal caret As Variant) 'Going to change the .Text, so set the re-entry flag. formatting = True With wrapped .Text = FormattedDate If Not IsMissing(caret) Then .SelStart = caret End If End With formatting = False End Sub Private Function HandleBackspace(ByVal caret As Long, ByVal characters As Long) As Long With wrapped If caret = 0 Then Exit Function If caret = characters Then this.NumericDate = Left$(this.NumericDate, Len(this.NumericDate) - 1) Else Dim adjustedCaret As Long adjustedCaret = caret - SpannedDelimiters(Left$(.Text, caret)) this.NumericDate = Left$(this.NumericDate, adjustedCaret - 1) &amp; _ Right$(this.NumericDate, Len(this.NumericDate) - adjustedCaret) End If HandleBackspace = caret - 1 End With End Function Private Function HandleDelete(ByVal caret As Long) As Long With wrapped Dim adjustedCaret As Long adjustedCaret = caret - SpannedDelimiters(Left$(.Text, caret)) Dim characters As Long characters = Len(this.NumericDate) If adjustedCaret = characters Then HandleDelete = caret Exit Function End If If caret = 0 Then this.NumericDate = Right$(this.NumericDate, characters - 1) Else this.NumericDate = Left$(this.NumericDate, adjustedCaret) &amp; _ Right$(this.NumericDate, characters - adjustedCaret - 1) HandleDelete = caret + SpannedDelimiters(.SelText) End If End With End Function Private Function HandleSelectionDelete(ByVal caret As Long, ByVal selected As Long) As Long With wrapped Dim characters As Long characters = .TextLength If characters = selected Then this.NumericDate = vbNullString ElseIf caret = 0 Then this.NumericDate = Right$(.Text, characters - selected) ElseIf caret + selected = characters Then this.NumericDate = Left$(.Text, caret) Else this.NumericDate = Left$(.Text, caret) &amp; Right$(.Text, characters - selected - caret) End If this.NumericDate = Replace$(this.NumericDate, Delimiter, vbNullString) End With HandleSelectionDelete = caret End Function Private Function SpannedDelimiters(ByVal testing As String) As Long If testing = vbNullString Then Exit Function End If SpannedDelimiters = UBound(Split(testing, Delimiter)) End Function Private Function IsLeapYear(ByVal test As Long) As Boolean Select Case True Case test Mod 400 IsLeapYear = True Case test Mod 100 Case test Mod 4 IsLeapYear = True End Select End Function </code></pre> <hr> <h2>Sample Usage</h2> <p>The following assumes a <code>UserForm</code> with a <code>TextBox</code> named <code>TextBox1</code>:</p> <pre><code>Option Explicit Private dateInput As DateInputWrapper Private Sub UserForm_Initialize() Set dateInput = New DateInputWrapper With dateInput Set .Wrapping = TextBox1 .Delimiter = "." .DateValue = Date .Order = DateOrder.YMD End With End Sub Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) If dateInput.IsValidDate Then Debug.Print dateInput.DateValue Else Debug.Print "Invalid date" End If End Sub </code></pre>
[]
[ { "body": "<h2>Constants</h2>\n\n<blockquote>\n<pre><code> Private Const DELETE_KEY As Integer = 46\n Private Const BACKSPACE_KEY As Integer = 8\n</code></pre>\n</blockquote>\n\n<p>Obviously these constants refer to to KeyCodes, right? Well yeah but I still had to check. I would prefer to use the built in con...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T02:42:18.303", "Id": "205970", "Score": "3", "Tags": [ "vba", "validation" ], "Title": "Date input wrapper for TextBox" }
205970
<p>I just started to use classes in Python, so I don't know all concepts, rules and conventions about it. I made a little program of a machine gun, which simulates firing by user's action. Here it is:</p> <pre><code>import random, pygame, sys class MachineGun(object): bullets = 200 def __init__(self): self._magazine = 50 def _get_magazine(self): return self._magazine def _set_magazine(self, val): self._magazine = val magazine = property(_get_magazine, _set_magazine) def fire(self): pygame.mixer.Sound("fire.wav").play() while pygame.mixer.get_busy(): pass fired = random.randint(1, 21) self.magazine = self.magazine-fired if self.magazine &lt;= 0 : print("Bullets remaining : 0") else : print("Bullets remaining : {}".format(self.magazine)) def reload(self): if self.magazine == 50 : print("Full") else : if MachineGun.bullets &gt;= 50 : if self.magazine == 0 : self.magazine = 50 MachineGun.bullets = MachineGun.bullets-50 else : tmp = 50-self.magazine self.magazine = self.magazine+tmp MachineGun.bullets = MachineGun.bullets-tmp else : if self.magazine == 0 : self.magazine = MachineGun.bullets MachineGun.bullets = 0 else : if self.magazine+MachineGun.bullets &gt; 50 : tmp = 50 - self.magazine self.magazine = self.magazine+tmp MachineGun.bullets = MachineGun.bullets-tmp else : self.magazine += MachineGun.bullets MachineGun.bullets = 0 pygame.mixer.Sound("reload.wav").play() while pygame.mixer.get_busy(): pass def action(self): a = "x" while a != "e" : if a == "" : if self.magazine &gt; 0 : self.fire() elif self.magazine &lt;= 0 and MachineGun.bullets &gt; 0 : self.magazine = 0 print("Reload") else : print("End") sys.exit() elif a == "r" : self.reload() a = input() M = MachineGun() M.action() </code></pre> <p>This is somehow my first "complete" implementation using classes. So I don't know if the form is correct. For exemple, I modified the attribute <code>bullets</code> without using a class method. Should I ? Like properties for object attributs ? Is it very necessary to use properties ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T09:21:37.803", "Id": "397280", "Score": "1", "body": "Added. `bullets` is somehow the stock, and `magazine`, bullets ready to fire, in the gun. When `magazine` is at 0, you reload it with `bullets`. I'm using python 3.7" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T08:21:47.740", "Id": "205977", "Score": "2", "Tags": [ "python", "beginner", "object-oriented", "python-3.x", "pygame" ], "Title": "Object-oriented model of a machine gun using Pygame" }
205977
<p>I'm going through the K&amp;R book (2nd edition, ANSI C ver.) and want to get the most from it. Note that, for the sake of exercise, I don't want to use techniques not introduced yet in the book and I'm compiling with the <code>-ansi</code> flag.</p> <h3>K&amp;R Exercise 1-16</h3> <p>Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.</p> <h3>Solution</h3> <p>Note the explicit requirement to revise the <strong>main routine</strong>. I'm assuming that the author expect us to find a way to use the 2 functions as they are to solve the problem. I've seen solutions which change the <code>getline</code> function, but I would say they're wrong even though the resulting program does what it should. Even the <a href="https://rads.stackoverflow.com/amzn/click/0131096532" rel="nofollow noreferrer">solution book</a> revised the <code>getline</code> function, how disappointing.</p> <pre><code>/* Exercise 1-16. Revise the main routine of the longest-line program so * it will correctly print the length of arbitrarily long input lines, * and as much as possible of the text. */ #include &lt;stdio.h&gt; #define MAXLINE 10 /* buffer size */ int getline(char line[], int maxline); void copy(char to[], char from[]); /* print the longest input line length and the line itself or the first * MAXLINE-1 characters if the line couldn't fit in the buffer */ main() { int len; /* current line length */ int lenx; /* extra length to add for too long lines */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* full line or beginning of line */ char linex[MAXLINE]; /* overflow buffer */ char longest[MAXLINE]; /* longest line saved here */ max = 0; while ((len = getline(line, MAXLINE)) &gt; 0) { /* If we didn't reach the endl, consume the input until * the end is reached while keeping track of the length */ if (len == MAXLINE-1 &amp;&amp; line[MAXLINE-2] != '\n') while ((lenx = getline(linex, MAXLINE)) &gt; 0 &amp;&amp; (len = len + lenx) &amp;&amp; linex[lenx-1] != '\n') ; if (len &gt; max) { max = len; copy(longest, line); } } if (max &gt; 0) { /* there was a line */ if (max &gt; MAXLINE-1) { printf("Longest line length: %d, first ", max); printf("%d characters: \n%s\n", MAXLINE-1, longest); } else printf("Longest line length: %d; longest line: \n%s\n", max, longest); } return 0; } /* getline: read a line into s, return length */ int getline(char s[], int lim) { int c, i; for (i=0; i&lt;lim-1 &amp;&amp; (c=getchar())!=EOF &amp;&amp; c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } /* copy: copy 'from' into 'to'; assume to is big enough */ void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; } </code></pre> <h3>Original program (from the book)</h3> <pre><code>#include &lt;stdio.h&gt; #define MAXLINE 1000 /* maximum input line length */ int getline(char line[], int maxline); void copy(char to[], char from[]); /* print longest input line */ main() { int len; /* current line length */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ char longest[MAXLINE]; /* longest line saved here */ max = 0; while ((len = getline(line, MAXLINE)) &gt; 0) if (len &gt; max) { max = len; copy(longest, line); } if (max &gt; 0) /* there was a line */ printf("%s", longest); return 0; } /* getline: read a line into s, return length */ int getline(char s[], int lim) { int c, i; for (i=0; i&lt;lim-1 &amp;&amp; (c=getchar())!=EOF &amp;&amp; c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } /* copy: copy 'from' into 'to'; assume to is big enough */ void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; } </code></pre>
[]
[ { "body": "<p>lets start with the book you are using is VERY obsolete. </p>\n\n<p>Regarding: <code>main()</code> there are only two valid signatures for <code>main()</code> they are <code>int main( void )</code> and <code>int main( int argc, char *argv[] )</code></p>\n\n<p>the header file: <code>stdio.h</code> ...
{ "AcceptedAnswerId": "205992", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T10:50:32.443", "Id": "205983", "Score": "1", "Tags": [ "beginner", "c", "io" ], "Title": "K&R Exercise 1-16. Find the longest line in the input and print its length and first N characters" }
205983
<p>I was curious as to how I'd be able to make this much clearer to read because from my perspective I understand what does what but how does it look to a third party? Also how are my object / method names doing?</p> <pre><code>//Program that stores units into a vector and compares / prints them back to the user. #include "../../std_lib_facilities.h" double unit_conversion(double input_value, string input_unit, string conversion); double vector_sum(vector&lt;double&gt; stored_values); void input_prompt(bool newline); void vector_print(vector&lt;double&gt; stored_values); int main() { //Variable and Vector Declartion double input_value = 0, smallest_value = 0, largest_value = 0; vector&lt;double&gt; stored_values; vector&lt;string&gt; accepted_unit{"cm", "m", "in", "ft"}; string input_unit; input_prompt(0); //First variable assignment and unit checking while(cin &gt;&gt; input_value &gt;&gt; input_unit) { if (find(accepted_unit.begin(), accepted_unit.end(), input_unit) != accepted_unit.end()) { break; } else { cout &lt;&lt; "You have entered an invalid unit type!\n"; input_prompt(1); } } //Assign smallest/largest value to first valid input stored_values.push_back(unit_conversion(input_value, input_unit, "convert_to_m")); string smallest_value_unit = input_unit, largest_value_unit = input_unit; input_prompt(1); while (cin &gt;&gt; input_value &gt;&gt; input_unit) { if (find(accepted_unit.begin(), accepted_unit.end(), input_unit) != accepted_unit.end()) { //Smaller or Larger if (unit_conversion(input_value, input_unit, "convert_to_m") &gt; stored_values[0]) { //New value is Larger cout &lt;&lt; "The new value " &lt;&lt; input_value &lt;&lt; input_unit &lt;&lt; " is the largest so far!\nThe last largest number being: " &lt;&lt; unit_conversion(stored_values[stored_values.size() - 1], largest_value_unit, "convert_from_m") &lt;&lt; largest_value_unit &lt;&lt; '\n'; largest_value_unit = input_unit; } else if (unit_conversion(input_value, input_unit, "convert_to_m") &lt; stored_values[stored_values.size() - 1]) { //New value is Smaller cout &lt;&lt; "The new value " &lt;&lt; input_value &lt;&lt; input_unit &lt;&lt; " is the smallest so far!\nThe last smallest number being: " &lt;&lt; unit_conversion(stored_values[0], smallest_value_unit, "convert_from_m") &lt;&lt; smallest_value_unit &lt;&lt; '\n'; smallest_value_unit = input_unit; } cout &lt;&lt; "Your last input was: " &lt;&lt; input_value &lt;&lt; input_unit &lt;&lt; '\n'; //Add input value into array and sort by size stored_values.push_back(unit_conversion(input_value, input_unit, "convert_to_m")); sort(stored_values); input_prompt(1); } else { //Bad unit type error cout &lt;&lt; "You have entered an invalid unit type!\n"; input_prompt(1); } } //Output for sum, total inputs, last input and range of inputs in cm cout &lt;&lt; "The final smallest value was: " &lt;&lt; stored_values[0] &lt;&lt; smallest_value_unit &lt;&lt; '\n'; cout &lt;&lt; "The last largest number being : " &lt;&lt; stored_values[stored_values.size() - 1] &lt;&lt; largest_value_unit &lt;&lt; '\n'; cout &lt;&lt; "Your total sum is now: (" &lt;&lt; vector_sum(stored_values) * 100 &lt;&lt; " cm) (" &lt;&lt; vector_sum(stored_values) &lt;&lt; " m) (" &lt;&lt; vector_sum(stored_values) * 39.37 &lt;&lt; " in) (" &lt;&lt; vector_sum(stored_values) * 3.28 &lt;&lt; " ft)\n"; cout &lt;&lt; "You have entered a total of: " &lt;&lt; stored_values.size() &lt;&lt; " values\n"; vector_print(stored_values); return 0; } void input_prompt(bool newline) { if (newline) cout &lt;&lt; "\nInput a new number and a unit (cm, m, in, ft) "; else cout &lt;&lt; "Input a new number and a unit (cm, m, in, ft) "; } //Converts units using the specified operator needed for conversion double unit_conversion(double input_value, string input_unit, string conversion) { //Converts all numbers to metres if (conversion == "convert_to_m") { if (input_unit == "cm") return input_value / 100; else if (input_unit == "m") return input_value; else if (input_unit == "in") return input_value / 39.37; else if (input_unit == "ft") return input_value / 3.28; } else if (conversion == "convert_from_m") { if (input_unit == "cm") return input_value * 100; else if (input_unit == "m") return input_value; else if (input_unit == "in") return input_value * 39.37; else if (input_unit == "ft") return input_value * 3.28; } else { cout &lt;&lt; "Type error, please revise!\n"; } } //Adds all of vector range and returns sum double vector_sum(vector&lt;double&gt; stored_values) { double temp_value = 0; for (int i = 0; i &lt; stored_values.size(); ++i) { temp_value += stored_values[i]; } return temp_value; } //Prints all vector values in cm void vector_print(vector&lt;double&gt; stored_values) { cout &lt;&lt; "Your range of values are (in m): "; for (int i = 0; i &lt; stored_values.size(); ++i) { cout &lt;&lt; stored_values[i] &lt;&lt; "m "; } cout &lt;&lt; '\n'; } </code></pre>
[]
[ { "body": "<h3>Clearer Method Parameters</h3>\n\n<p>In the line <code>input_prompt(0)</code>, it is not immediately obvious what the argument represents without first checking the method signature. Some alternatives are to define constants for each case, or to use an <code>enum</code> for the argument instead. ...
{ "AcceptedAnswerId": "205994", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T11:46:19.300", "Id": "205984", "Score": "7", "Tags": [ "c++", "c++11", "unit-conversion" ], "Title": "Unit conversion program into metre and stored input" }
205984
<p>I have recently started coding in Java and I had to do this assignment in college.</p> <blockquote> <p>Develop a menu driven application called <code>TestCarPartc</code> that allows the user to add, remove and list Car objects. For this use an <code>ArrayList</code> of <code>Car</code>. What are the advantages of using an <code>ArrayList</code> over an array? Place the answer in a comment at the end of your code.</p> </blockquote> <p>I am trying to wrap my head around the concept of OOP and I am not quite sure when should I make something a new class or if I should implement something as interface or make some classes inherit from the other.</p> <p>How does it look like in a real programming job? Would my code be considered "well written" for its purposes? What are the things I should look out for?</p> <p>Console Menu:</p> <pre><code>package CarPartsB; import java.util.InputMismatchException; import java.util.Scanner; public class CarPartsMenu { Scanner console = new Scanner(System.in); private CarsArray carsList = new CarsArray(); private boolean loopVariable = true; public void showMenu() { while (loopVariable) { try { System.out.println("1: Add car.\n2: Remove car.\n3: List cars.\n4: Exiting"); int userInput = console.nextInt(); switch (userInput) { case 1: addCar(); break; case 2: removeCar(); break; case 3: listCars(); break; case 4: loopVariable = false; break; } } catch (InputMismatchException e) { console.nextLine(); System.out.println("\n" + e + " \nhas happened, choose value from 1 o 4.\n Click enter to continue..."); console.nextLine(); } } } private void addCar() { String make, model; int year; double price; try { System.out.println("What's price of your car? "); price = console.nextDouble(); validateInput(price); System.out.println("What year was your car made?"); year = console.nextInt(); validateInputYear(year); System.out.println("What's the make of your car?"); make = console.next(); System.out.println("What's the model of your car?"); model = console.next(); Car car = new Car(price, year, make, model); carsList.addCar(car); } catch (InputMismatchException e) { console.nextLine(); System.out.println("\n" + e + "\nhas happened, make sure to input correct values.\n Click enter to continue..."); console.nextLine(); } } private void removeCar() { if (carsList.isEmpty()) { console.nextLine(); System.out.println("There are no cars in the list"); console.nextLine(); } else { try { System.out.println("Type id of the car you want to remove: "); int userInputID = console.nextInt(); carsList.removeCar(userInputID); System.out.println("Car with ID: " + userInputID + " has been removed.\n"); console.nextLine(); } catch (IndexOutOfBoundsException e) { console.nextLine(); System.out.println("\n" + e + "\nhas happened, you have to pick ID that EXISTS.\n Click enter to continue..."); console.nextLine(); } catch (InputMismatchException e) { console.nextLine(); System.out.println("\n" + e + "\nhas happened, input an integer.\n Click enter to continue..."); console.nextLine(); } } } private void listCars() { console.nextLine(); System.out.println("List of cars: "); carsList.printCars(); System.out.println("\nPress anything to continue..."); console.nextLine(); } private void validateInputYear(int number) { if (number &lt; 1900 || number &gt; 2018) { throw new InputMismatchException("\nYou can't add car that was made earlier than 1900\n or after 2018"); } } private void validateInput(double number) { if (number &lt;= 0) { throw new InputMismatchException("\nPrice can't be negative or zero."); } } } </code></pre> <p><code>Array</code> Class:</p> <pre><code>package CarPartsB; import java.util.ArrayList; public class CarsArray { private ArrayList&lt;Car&gt; carsArray; public CarsArray() { this.carsArray = new ArrayList(); } public ArrayList&lt;Car&gt; getCars() { return this.carsArray; } public int size() { return this.carsArray.size(); } public void addCar(Car element) { this.carsArray.add(element); } public void removeCar(int carId) { Car carToRemove = null; for (Car c : carsArray) { if (c.getCarID() == carId) { carToRemove = c; } } if (carToRemove != null) { carsArray.remove(carToRemove); } else { throw new IndexOutOfBoundsException(); } } public void printCars() { if (isEmpty()) { System.out.println("Empty.."); } else { for (Car c : carsArray) { c.printDetails(); } } } public boolean isEmpty() { return carsArray.isEmpty(); } } </code></pre> <p><code>Car</code> Class:</p> <pre><code>package CarPartsB; public class Car { private double price; private int year_of_production; private String make; private String model; private int yearsOld; private int carID; static int CAR_ID; public Car(double price, int year_of_production, String make, String model) { this.price = price; this.year_of_production = year_of_production; this.make = make; this.model = model; this.yearsOld = 2018 - this.year_of_production; this.carID = CAR_ID; CAR_ID++; } public int getCarID() { return this.carID; } public void setPrice(int price) { this.price = price; } public void setYear_of_production(int year_of_production) { this.year_of_production = year_of_production; } public void setMake(String make) { this.make = make; } public void setModel(String model) { this.model = model; } public double getPrice() { return price; } public int getYear_of_production() { return year_of_production; } public String getMake() { return make; } public String getModel() { return model; } public void printDetails() { System.out.println("ID:" + this.carID + " " + this.make + " " + this.model + " is " + this.yearsOld + " " + "years old and has price of " + this.price); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T20:09:04.433", "Id": "397661", "Score": "0", "body": "Do not change the code in the question after receiving an answer. Incorporating advice from an answer into the question violates the question-and-answer nature of this site. See...
[ { "body": "<h2><code>Car</code></h2>\n\n<p>Your <code>Car</code> class has what I would consider deficiencies. </p>\n\n<p>The <code>make</code>, <code>model</code>, <code>year_of_production</code> and <code>carId</code> shouldn’t change after creating a car. They should be <code>final</code>. Attributes like...
{ "AcceptedAnswerId": "206007", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T17:25:56.287", "Id": "205993", "Score": "2", "Tags": [ "java", "object-oriented", "homework" ], "Title": "Simple console based car array" }
205993
<p>I am a beginner at coding Java and am having a tough time understanding what is wrong with this code. This is an assignment I had posted about earlier and I also went to a Java tutor at my school for help after having issues communicating with my actual teacher (I am an online student). She gave me 10%. I will include instructions and the criteria she offered when she said I could "r&amp;r", revise &amp; resubmit. She seems to want something extremely specific and I'm not exactly sure what she wants.</p> <blockquote> <p>INSTRUCTIONS</p> <p>Create a Java file called CompoundInterestYourLastName. Write a method called <code>computeBalance( )</code> that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.</p> <p>You can use the standard calculator here to check your results (note that you'll have to change the dropdown to compound the interest yearly): <a href="http://www.thecalculatorsite.com/finance/calculators/compoundinterestcalculator.php" rel="nofollow noreferrer">http://www.thecalculatorsite.com/finance/calculators/compoundinterestcalculator.php</a></p> <p>Use a loop to control the iterations through the years in your method.</p> <p>Your method should return a double value.</p> <p>In your main method, run the following tests to verify your method is working correctly.</p> <pre><code>System.out.printf("Your total is $%.2f", computeBalance(1000, .045, 3)); // should return $1141.17 System.out.printf("\nYour total is $%.2f", computeBalance(2000, .03, 5)); // should return $2318.55 System.out.printf("\nYour total is $%.2f", computeBalance(3000, .01, 10)); // should return $3313.87 </code></pre> <p>Pay close attention to your parameters to make sure they match the test datat!</p> <p>*Note: Your methods should have this exact signature line, including the correct spelling, capitalization and parameter types. Otherwise, when I run the test to check the file, your methods will fail and you'll have to revise.</p> <p>When you are finished with your file, upload it to Blackboard. This program is worth 10 points.</p> </blockquote> <p>CRITERIA SHE OFFERED: Use a simple formula in your loop to return the results outlined in the assignment. You don't need to use Math.pow to get this to work. r&amp;r</p> <pre><code> // Tori Tidwell import java.util.Scanner; import java.lang.Math; public class CompoundInterestTidwell { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(" Inital Balance Amount: "); double P = sc.nextDouble(); System.out.print(" Interest rate: "); double r = sc.nextDouble(); System.out.print(" Number of years in account: "); int t = sc.nextInt(); double compInt = computeBalance(P, r, t); System.out.printf(" Your new balance is $%.2f", compInt); sc.close(); } public static double computeBalance(double P, double r, int t) { // Formula for compounding interest // A = P(1+(r/n))^(n(t)) // Java tutor in AAC told me to use c instead of n*t. Math worked after this. double compInt = 0; for(int c = 0; c &lt;= t; c++ ) { compInt = P*Math.pow((1+r/100), c); } return compInt; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T18:58:11.570", "Id": "397315", "Score": "1", "body": "Within your loop, you overwrite `compInt`, so only the last loop iteration is meaningful. Either remove the loop, or use a simple multiplication inside the loop," }, { "C...
[ { "body": "<p>First, to fix your formula:</p>\n\n<p><code>r</code> probably shouldn't be divided by 100, since the argument is <code>.045</code> in one of the examples, which I verified to mean 4.5% rather than 0.045%.</p>\n\n<p>Now, the loop logic:</p>\n\n<p>Your current code replaces <code>compInt</code> each...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T18:34:54.703", "Id": "205995", "Score": "-1", "Tags": [ "java", "beginner", "homework", "calculator", "finance" ], "Title": "Compound interest calculator homework" }
205995
<p>I have the following conditional flow and I'd like some comments about it:</p> <pre><code>bool IsPositive(object sender) { if (!(sender is SymbolIcon symbolIcon)) { if (sender is ContentControl content &amp;&amp; content.Content is SymbolIcon i) symbolIcon = i; else if (sender is Viewbox viewBox &amp;&amp; viewBox.Child is SymbolIcon si) symbolIcon = si; else throw new InvalidOperationException($"Could not extract icon from '{sender}'."); } return symbolIcon.Symbol == Symbol.Add; } </code></pre> <p>The purpose of this code is to determine if the <a href="https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.symbol" rel="nofollow noreferrer"><code>Symbol</code></a> of a <a href="https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.symbolicon" rel="nofollow noreferrer"><code>SymbolIcon</code></a> which can exist in the following 3 ways in <code>sender</code>, is <code>Symbol.Add</code>:</p> <ul> <li>Could be <code>sender</code> itself</li> <li><code>sender</code> is a <code>Button</code> with <code>SymbolIcon</code> as its content </li> <li><code>sender</code> is a <code>ViewBox</code> with <code>SymbolIcon</code> as its content</li> </ul> <p>But the question is not about <code>SymbolIcon</code> or any other technology, it's about C#. The question is if there would be a better way to write this code.</p> <p>P.S. C# version is 7.3.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T19:48:00.640", "Id": "397317", "Score": "1", "body": "Which framework is this? WPF, WinForms, asp.net...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T19:56:42.563", "Id": "397319", "Score"...
[ { "body": "<p>This can be heavily simplified using pattern matching:</p>\n\n<pre><code>bool IsPositive(object sender)\n{\n switch (sender)\n {\n case SymbolIcon icon:\n return icon.Symbol == Symbol.Add;\n case ContentControl c when c.Content is SymbolIcon icon:\n return icon.Symbol == Symbol.A...
{ "AcceptedAnswerId": "206004", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T19:36:56.433", "Id": "205998", "Score": "-1", "Tags": [ "c#" ], "Title": "Efficiently searching an instance or its children for a specific type" }
205998
<p><strong>This is a console application that generates the factorial of a given number. Is there any way I can improve my code ?</strong></p> <pre><code> int number = Convert.ToInt32(Console.ReadLine()); int digitFactorial = number; for (int counter = number - 1; counter &gt; 0; counter--) { digitFactorial *= counter; } Console.WriteLine(digitFactorial); Console.ReadLine(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T00:24:05.073", "Id": "397340", "Score": "3", "body": "First, try extracting the factorial calculation itself into its own method and call that method from your interactive part of the program. That's a pretty decent exercise in itse...
[ { "body": "<p>As Slicer wrote in his comment you should create a method/function for the algorithm.\nAnd you could make it as an extension method:</p>\n\n<pre><code>public static class NumberExtensions\n{\n public static ulong Factorial(this ulong number)\n {\n if (number &lt; 2) return 1;\n\n checked\n...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-21T23:36:44.733", "Id": "206006", "Score": "1", "Tags": [ "c#", "console" ], "Title": "Generate the Factorial of Given Number" }
206006
<p>I am learning Racket and implemented a BST insert function <code>(insert tree n)</code> where the format for a BST node is <code>(left-tree value right-tree)</code>.</p> <p><strong>Example</strong></p> <p>'((() 2 ()) 3 ()) is isomorphic to:</p> <pre><code> (3) (2) () () () </code></pre> <p>Therefore <code>(insert '((() 2 ()) 3 ()) 4)</code> yields <code>((() 2 ()) 3 (() 4 ()))</code>:</p> <pre><code> (3) (2) (4) () () () () </code></pre> <p><strong>Implementation</strong></p> <p>My implementation feels overly complicated. For example, I used <code>append</code> with <code>cons</code> so that the right-tree for 3, represented by <code>()</code>, would properly become <code>(() 4 ())</code> after inserting 4.</p> <p>How can I approach this problem more elegantly or more functionally?</p> <pre><code>#lang racket (define (left tree) (list-ref tree 0) ) (define (value tree) (list-ref tree 1) ) (define (right tree) (list-ref tree 2) ) (define (merge left value right) (append (cons left '()) (append (cons value '()) (cons right '()))) ) (define (insert tree n) (cond [(empty? tree) (append '(()) (cons n '()) '(()))] ; leaf [(&gt; (value tree) n) (merge (insert (left tree) n) (value tree)(right tree))] ; internal - go left [(&lt; (value tree) n) (merge (left tree) (value tree) (insert (right tree) n))] ; internal - go right [(eq? (value tree) n) tree] ; internal - n already in tree ) ) </code></pre> <p><strong>Update</strong></p> <p>Given the answer to the question, I updated my code:</p> <pre><code>(define (insert BST n) (cond [(empty? BST) ; leaf (list empty n empty)] [(&lt; n (cadr BST)) ; internal - go left (list (insert (car BST) n) (cadr BST) (caddr BST))] [(&gt; n (cadr BST)) ; internal - go right (list (car BST) (cadr BST) (insert (caddr BST) n))] [else BST] ) ) </code></pre>
[]
[ { "body": "<p>As you suspected, you don't need <code>append</code> for this problem. The trick is to notice that if, for example, your goal is to create the list <code>'(1 2 3)</code>, then writing <code>(list 1 2 3)</code> is more straight-forward and more efficient than writing <code>(append '(1) '(2) '(3))</...
{ "AcceptedAnswerId": "206090", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T00:13:24.197", "Id": "206009", "Score": "1", "Tags": [ "tree", "lisp", "scheme", "racket" ], "Title": "Binary search tree insertion in Racket" }
206009
<p>I want to check in my if and else if statement if the inputs form a square or a rectangle, now my if and else if statements seems to be unreadable, now I'm thinking of ways to improve it. </p> <pre><code> /* input are angles in degrees, 1st side is parallel to 3rd side, 2nd side is parallel to 4th side*/ static void Main(string[] args) { Console.Write("Input first: "); int first = int.Parse(Console.ReadLine()); Console.Write("Input second: "); int second = int.Parse(Console.ReadLine()); Console.Write("Input third: "); int third = int.Parse(Console.ReadLine()); Console.Write("Input fourth: "); int fourth = int.Parse(Console.ReadLine()); // all sides are equal // logic for if and else-if, needs codereview for improvement if (first == second &amp;&amp; first == third &amp;&amp; first == fourth &amp;&amp; second == third &amp;&amp; second == fourth &amp;&amp; third == fourth) { Console.WriteLine("Square"); } else if (first != second &amp;&amp; first == third &amp;&amp; first != fourth &amp;&amp; second != third &amp;&amp; second == fourth ) { Console.WriteLine("Rectangle"); } else { Console.WriteLine("Not a square nor a rectangle"); } Console.ReadKey(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T02:46:17.870", "Id": "397349", "Score": "3", "body": "Why have tags of linq and functional-programming? You aren't using either of them. As a side note you can simplify your square if statement no need to check the if 2nd = 3rd & 4...
[ { "body": "<p>Simplify the if by just doing</p>\n\n<pre><code>if (first == second &amp;&amp; second == third &amp;&amp; third == fourth)\n{....}\n</code></pre>\n\n<p>You said the inputs are degrees, now it’s been awhile since geometry but squares and rectangles are determined by length of side, not angle degree...
{ "AcceptedAnswerId": "206015", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T02:35:11.140", "Id": "206012", "Score": "1", "Tags": [ "c#" ], "Title": "Check if it's a square or rectangle" }
206012
<p>This is a Dockerfile which aims to create a complete environment for the <a href="https://github.com/bstarynk/bismon" rel="nofollow noreferrer">bismon</a> project. I have written it as an exercise and to make it easy for other users to begin with bismon. </p> <pre><code>FROM ubuntu:latest MAINTAINER Niklas Rosencrantz (niklasrosencrantz@xyz.com) ENV DEBIAN_FRONTEND noninteractive RUN apt-get update RUN apt-get install --yes software-properties-common RUN apt-add-repository --yes --update ppa:ubuntu-toolchain-r/test RUN apt-get update RUN apt-get install --yes git RUN apt-get install --yes gcc-snapshot RUN apt-get install --yes build-essential make gcc-8 cmake RUN apt-get install --yes ninja-build g++-8 gcc-8-plugin-dev libgccjit-8-dev libgtk-3-dev RUN apt-get install --yes markdown indent astyle tardy texlive texlive-full hevea RUN adduser --disabled-password --gecos '' newuser USER newuser WORKDIR /home/newuser RUN git clone https://github.com/ianlancetaylor/libbacktrace.git RUN cd libbacktrace; ./configure ; make USER root WORKDIR /home/newuser/libbacktrace RUN make install USER newuser RUN cd; git clone https://github.com/davidmoreno/onion.git; cd onion; mkdir build; cd build; cmake ..; make USER root WORKDIR /home/newuser/onion/build RUN make install; cp /usr/local/lib/libonion* /usr/lib; cp /usr/local/lib/libbacktrace* /usr/lib USER newuser RUN cd; git clone https://github.com/bstarynk/bismon.git; cd bismon; make; touch ~/passwords_BM; chmod u+rw,go-rwx ~/passwords_BM WORKDIR /home/newuser/bismon </code></pre>
[]
[ { "body": "<p>Combine as many <code>RUN</code> statements as possible to reduce the number of layers (and size of the image). Each <code>RUN</code> command makes a new layer.</p>\n\n<p>For example,</p>\n\n<pre><code>RUN apt-get update &amp;&amp; apt-get install --yes software-properties-common git gcc-snapshot\...
{ "AcceptedAnswerId": "206021", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T03:16:18.670", "Id": "206013", "Score": "1", "Tags": [ "dockerfile" ], "Title": "Dockerfile for C project" }
206013
<p>I've been reusing an error class in Excel VBA projects for a few years now and I'd like to see if there are ways to improve it. Any suggestions for style, code, etc. are all welcome. </p> <p>The 2 procedures I'd like to focus on are:</p> <ul> <li><code>Error_Handler.DisplayMessage</code></li> <li><code>Error_Handler.Log</code></li> </ul> <p>The log file is usually written to a file server so multiple users can access it. I have changed the log path to <code>C:\Temp\</code> for this example. I use <a href="https://www.baremetalsoft.com/baretail/" rel="nofollow noreferrer">BareTail</a> to read the log file.</p> <p>I use <a href="https://msdn.microsoft.com/en-us/vba/office-shared-vba/articles/documentproperties-add-method-office" rel="nofollow noreferrer">Custom Document Properties</a> to store settings for the file/Add-in</p> <blockquote> <p>An example of a project I use the Error Handler class and logging in is on <a href="https://github.com/Excel-projects/Excel-Timesheet" rel="nofollow noreferrer">GitHub</a>. For reference, I am using Excel 2016 on Windows 7.</p> </blockquote> <hr> <h3>Error_Handler Class</h3> <pre><code>Attribute VB_Name = "Error_Handler" '==================================================================================================================== ' Purpose: Error trapping class '==================================================================================================================== Option Explicit Public App As MyAppInfo Public Type MyAppInfo Name As String ReleaseDate As Date Version As String End Type Private Const MyModule As String = "Error_Handler" Public Sub Load() On Error GoTo ErrTrap App.Name = ThisWorkbook.CustomDocumentProperties("App_Name").Value App.ReleaseDate = ThisWorkbook.CustomDocumentProperties("App_ReleaseDate").Value App.Version = ThisWorkbook.CustomDocumentProperties("App_Version").Value ExitProcedure: On Error Resume Next Exit Sub ErrTrap: Select Case Err.number Case Is &lt;&gt; 0 Error_Handler.DisplayMessage "Load", MyModule, Err.number, Err.description Resume ExitProcedure Case Else Resume ExitProcedure End Select End Sub Public Sub DisplayMessage( _ ByVal procedure As String _ , ByVal module As String _ , ByVal number As Double _ , ByVal description As String _ , Optional ByVal line As Variant = 0 _ , Optional ByVal title As String = "Unexpected Error" _ , Optional ByVal createLog As Boolean = True) '==================================================================================================================== ' Purpose: Global error message for all procedures ' Example: Error_Handler.DisplayMessage "Assembly_Info", "Load", 404, "Error Message Here...", 1, "Error Description" '==================================================================================================================== On Error Resume Next Dim msg As String msg = "Contact your system administrator." msg = msg &amp; vbCrLf &amp; "Module: " &amp; module msg = msg &amp; vbCrLf &amp; "Procedure: " &amp; procedure msg = msg &amp; IIf(line = 0, "", vbCrLf &amp; "Error Line: " &amp; line) msg = msg &amp; vbCrLf &amp; "Error #: " &amp; number msg = msg &amp; vbCrLf &amp; "Error Description: " &amp; description If createLog Then Log module, procedure, number, description End If MsgBox msg, vbCritical, title End Sub Public Sub Log( _ ByVal module As String _ , ByVal procedure As String _ , ByVal number As Variant _ , ByVal description As String) '==================================================================================================================== ' Purpose: Creates a log file and record of the error ' Example: Error_Handler.Log "Assembly_Info", "Load", "404", "Error Message Here..." '==================================================================================================================== On Error GoTo ErrTrap Dim fileSizeMax As Double: fileSizeMax = 1024 ^ 2 'archive the file over 1mb Dim AppName As String: AppName = LCase(Replace(App.Name, " ", "_")) Dim fileName As String: fileName = "C:\temp\excel_addin." &amp; AppName &amp; ".log" Dim fileNumber As Variant: fileNumber = FreeFile Const dateFormat As String = "yyyy.mm.dd_hh.nn.ss" If Dir(fileName) &lt;&gt; "" Then If FileLen(fileName) &gt; fileSizeMax Then 'archive the file when it's too big FileCopy fileName, Replace(fileName, ".log", Format(Now, "_" &amp; dateFormat &amp; ".log")) Kill fileName End If End If Open fileName For Append As #fileNumber Print #fileNumber, CStr(Format(Now, dateFormat)) &amp; _ "," &amp; Environ("UserName") &amp; _ "," &amp; Environ("ComputerName") &amp; _ "," &amp; Application.OperatingSystem &amp; _ "," &amp; Application.Version &amp; _ "," &amp; App.Version &amp; _ "," &amp; Format(App.ReleaseDate, "yyyy.mm.dd_hh.nn.ss") &amp; _ "," &amp; ThisWorkbook.FullName &amp; _ "," &amp; module &amp; _ "," &amp; procedure &amp; _ "," &amp; number &amp; _ "," &amp; description ExitProcedure: On Error Resume Next Close #fileNumber Exit Sub ErrTrap: Select Case Err.number Case Is &lt;&gt; 0 Debug.Print "Module: " &amp; module &amp; " |Procedure: " &amp; procedure &amp; " |Error #: " &amp; number &amp; " |Error Description: " &amp; description Resume ExitProcedure Case Else Resume ExitProcedure End Select End Sub </code></pre> <h3>Usage Example:</h3> <pre><code>Public Function GetItem(ByVal col As Variant, ByVal key As Variant) As Variant On Error GoTo ErrTrap Set GetItem = col(key) ExitProcedure: On Error Resume Next Exit Function ErrTrap: Select Case Err.number Case Is = 9 'subscript out of range = this column does not exist in the active table Set GetItem = Nothing Resume ExitProcedure Case Is &lt;&gt; 0 Error_Handler.DisplayMessage "GetItem", "Example_Module", Err.number, Err.description Set GetItem = Nothing Resume ExitProcedure Case Else Resume ExitProcedure End Select End Function </code></pre>
[]
[ { "body": "<p><strong>Amount of boilerplate code</strong></p>\n\n<p>As it is, there are lot of boilerplate that we must provide to set up everything. At a minimum, we need the following code:</p>\n\n<pre><code>&lt;Procedure&gt; SomeProcedure\n On Error GoTo ErrTrap\n\n'Actual Code\n\nExitProcedure:\n On Err...
{ "AcceptedAnswerId": "206059", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T04:52:01.090", "Id": "206017", "Score": "6", "Tags": [ "vba", "excel", "error-handling", "logging" ], "Title": "Error-Handling Class and Logging for VBA" }
206017
<p>I have just begun learning functional programming and Haskell. </p> <p>This is my attempt to implement a solution to Graham Scan Algorithm in Haskell. Note that I am not even sure if this is indeed Graham Scan Algorithm, since I implemented this solution with only a few hints of the actual Graham Scan Algorithm. But I believe it to be correct and to have a <span class="math-container">\$\mathcal O\left(n \log(n)\right)\$</span> time complexity. However, I am still not quite there yet when it comes to understanding Lazy Evaluation, so not sure if it is indeed <span class="math-container">\$\mathcal O\left(n \log(n)\right)\$</span>.</p> <pre><code>data Direction = LeftTurn | RightTurn | Straight deriving (Show, Eq) findDirBetter (x, y) (x1, y1) (x2, y2) | cros_product == 0 = Straight | cros_product &gt; 0 = LeftTurn | cros_product &lt; 0 = RightTurn where cros_product = (x1 - x) * (y2 - y1) - (y1 - y) * (x2 - x1) convex_hull_find [] = [] convex_hull_find (x:[]) = x:[] convex_hull_find (x:x1:[]) = x:x1:[] convex_hull_find (x:x1:x2:[]) = x:x1:x2:[] convex_hull_find a = (find_half_hull (tail sorted_x) [head sorted_x]) ++ (find_half_hull (tail (reverse sorted_x)) [head (reverse sorted_x)]) where sorted_x = sortBy predicate a predicate (x, y) (x1, y1) = compare x x1 find_half_hull ([]) hull = tail hull find_half_hull l (x:[]) = find_half_hull (tail l) ((head l):x:[]) find_half_hull l hull = if findDirBetter (head (tail hull)) (head hull) (head l) /= RightTurn then find_half_hull (tail l) ((head l):hull) else find_half_hull l (tail hull) </code></pre> <p>Please critique everything from the algorithm to the code. </p> <ol> <li>Is this Graham Scan Algorithm?</li> <li>Is it <span class="math-container">\$\mathcal O\left(n \log(n)\right)\$</span>?</li> <li>Is this elegant, readable Haskell code?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T09:34:46.180", "Id": "397408", "Score": "0", "body": "Welcome to Code Review. Please keep in mind that we expect your code to work *as you intended*." } ]
[ { "body": "<blockquote>\n <p>Is this Graham Scan Algorithm? Is it O(n log n)?</p>\n</blockquote>\n\n<p>Yes, it is.</p>\n\n<blockquote>\n <p>Is this elegant, readable Haskell code?</p>\n</blockquote>\n\n<p>No. It's buggy and far from elegant. Let's start with the bugs in <code>convex_hull_find</code>:</p>\n\n<...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T05:11:00.987", "Id": "206019", "Score": "2", "Tags": [ "beginner", "haskell", "computational-geometry" ], "Title": "Graham Scan Algorithm in Haskell" }
206019
<p>I want to create a program that can print the number of movies that was watched by more than 3 people (data stored in a nested list as below ).</p> <pre><code>list_movies = [('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald']), ('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])] count2 = 0 for (movie,name) in list_movies: count = 0 for (name) in list_movies: if name != '': count += 1 if count &gt; 3: count2 += 1 print(count) print(count2) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T07:38:28.600", "Id": "397362", "Score": "4", "body": "What happens if you use `list_movies = [('Gravity',['james','jake','john','gerald']), ('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])]`? Can you understand why?" },...
[ { "body": "<ol>\n<li><p>Make it a function</p>\n\n<p>This should really be a function for test ability, reuse ability</p>\n\n<p>It would need to be a function which accepts 2 parameters (The list we want to query, the amount of people have had to watch it)</p>\n\n<p>And it will return the amount of times this h...
{ "AcceptedAnswerId": "206044", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T05:56:40.887", "Id": "206022", "Score": "0", "Tags": [ "python" ], "Title": "Print the number of movies that was watched by more than 3 people" }
206022
<p>I have a string like this:</p> <pre><code>char buffer[] = "blablabla$GPTXT-&gt;SOME CODES HERE&lt;-\r\n$GPRMCblablabla"; </code></pre> <p>It is sent from an external device and changes every 1 second.</p> <p>The string length is over 1000 bytes and consisted of some standard sentences beginning with "$GPXXX" and ending with CRLF. I've written the following function to extract a specific sentence:</p> <pre><code>int findString(char *src, char *dst, int desLen, char *what2find, char termChar) { char *temp; temp = strstr(src, what2find); ; if (temp == NULL) return 0; else temp += strlen(what2find); int j = 0; while (j&lt;(desLen-1)) { if (temp[j]==termChar) break; dst[j]= temp[j]; j++; } dst[j] = '\0'; return 1; } </code></pre> <p>So:</p> <pre><code> int main() { char buffer[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n $GPGSV,2,1,08,01,40,083,46,02,17,308,41,12,07,344,39,14,22,228,45*75\r\n $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\r\n $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48\r\n"; char dst[50]; findString(buffer,dst,50,"$GPTXT",'$'); } </code></pre> <p>finds and return the desired sentence.</p> <p>But this code has the following problems:</p> <ol> <li>It is very heuristic. I wonder if there exists some better solutions.</li> <li>It depends on a character (i.e. '$') for termination. It may terminate after finding a '$' but not "$GPXXX". The optimal solution may find the characters between two strings, e.g. "$GPTXT" and "$GPRMC". I don't know if it is optimally achievable.</li> </ol> <p>Note that the host processor is a 4Mhz ARM MCU!</p> <p>P.S: The above-mentioned function works fine in my project. I just want to widen my C programming knowledge!</p> <p>P.S. 2: Both answers from Lundin and David C. Rankin are nice. Unfortunately I can not accept both of them as answer!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T08:02:06.497", "Id": "397365", "Score": "0", "body": "1) More examples would help convey your goal. 2) Although `src` is 1000s long, provide details about pre-\"blablabla\", \"SOME CODES HERE<\", and post-\"blablabla\" lengths. Do ...
[ { "body": "<p>As far as performance goes, there isn't much you can improve without doing manual optimization tricks. Such things are already implemented in the library functions though.</p>\n\n<p>The main issue I see here is that you copy data into the destination before you know if the string actually contains...
{ "AcceptedAnswerId": "206029", "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T07:33:26.033", "Id": "206026", "Score": "5", "Tags": [ "c", "strings", "array" ], "Title": "Extracting a specific substring in C" }
206026
<p>I have an interesting problem to solve and despite having a running solution, I was wondering where I could improve it.</p> <p>In a range from 1 to 1000, I want to create an array with different increments according to the current interval. So, from 1.0 to 2.0, the increment should be 0.01, from 2.0 to 4.0 it should be 0.02, and so on. There are many intervals. The final result yields an array with 350 fields.</p> <p>I've come up with a super basic, easy to implement solution using ifs. So it goes something like:</p> <pre><code>// In one file I have: const grid = new Grid().buildGrid(); console.log(grid); // And expect a grid which respects the rules defined in the below class. // Grid Class: class Grid { constructor() { this.array = []; } buildGrid() { _createKeysWithTicks(this.array); } _createKeysWithTicks(array){ let i = 1.0; while (i &lt; 1000){ i = parseFloat((i + findStepSize(i)).toFixed(2)); array.push(i); } return array; } findStepSize(number) { let res; if (number &gt;= 1.0 &amp;&amp; number &lt; 2.0) { res = 0.01; } else if (number &gt;= 2.0 &amp;&amp; number &lt; 4.0) { res = 0.02; } else if (number &gt;= 4.0 &amp;&amp; number &lt; 5.0) { res = 0.1; } else if (number &gt;= 5.0 &amp;&amp; number &lt; 10.0) { res = 0.5; } else if (number &gt;= 10.0 &amp;&amp; number &lt; 50.0) { res = 1.0; } else if (number &gt;= 50.0 &amp;&amp; number &lt; 100.0) { res = 10; } return res; } </code></pre> <p>However, this is not elegant, at all because I get numerous if statements. I could swap for a switch statement, thus reducing the number of comparisons, which is nice. But does it improve performance?</p> <p>The suggestion is:</p> <pre><code>findStepSize(i) { let res; switch (number): case(number &gt;= 1.0 &amp;&amp; number &lt; 2.0) { res = 0.01; break; case(number &gt;= 2.0 &amp;&amp; number &lt; 4.0) { res = 0.02; break; case(number &gt;= 4.0 &amp;&amp; number &lt; 5.0) { res = 0.1; break; case(number &gt;= 5.0 &amp;&amp; number &lt; 10.0) { res = 0.5; break; case(number &gt;= 10.0 &amp;&amp; number &lt; 50.0) { res = 1.0; break; case(number &gt;= 50.0 &amp;&amp; number &lt; 100.0) { res = 10; break; } return res; } </code></pre> <p>The increments are not linear, otherwise the solution could be different.</p> <p>How would you optimize or clean this code?</p> <p><em>Note:</em> I understand and respect the rules of this community and I appreciate your feedback. Unfortunately, I cannot disclose much more details. If this is still not sufficient for you to think of how would you get rid of those If statements, I can't help much more because I can't simply provide more details. In fact, the data above is random and it's not the use case.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T10:47:03.783", "Id": "397429", "Score": "0", "body": "Is the real purpose of this for labelling the axes of a plot or chart? If that's the case, it might make a better basis for the question title, to give a high-level overview of ...
[ { "body": "<p>You can take advantage of the fact that you're iterating in increasing order, i.e. the trivial fact that if a number is greater than <code>n</code>, then it's also greater than any number below <code>n</code>; thus you can just keep track of the latest threshold you passed and only check if you've...
{ "AcceptedAnswerId": "206275", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T10:05:46.687", "Id": "206038", "Score": "0", "Tags": [ "javascript", "performance", "array" ], "Title": "Building an interval-based grid" }
206038
<p>I have a method that converts characters to numbers. It expects a single alphabetical character and returns the equivalent number. For example, if A is provided it returns 1, for B it returns 2. If an array is passed, it returns the message "array not accepted".</p> <pre><code>function characterToNumberCoverter(character) { if (Array.isArray(character)) { return { status: "failure", message: "array not accepted" };} character = character.toUpperCase(); let myRegExp = /[A-Z]/; if (myRegExp.test(character)) { return character.charCodeAt(0) - 64;}} </code></pre> <p>The method returns an object if the input is invalid and an integer if the input is valid. The method is invoked like this:</p> <pre><code>let intConvertedInt=characterToNumberCoverter('A'); </code></pre> <p>This works fine when the input is valid. What is a better way to handle the use case where an invalid input is passed? Example in which the result will be an object:</p> <pre><code> let intConvertedInt=characterToNumberCoverter({}); </code></pre> <p>Are there any other function design patterns that I should be following?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T14:03:41.360", "Id": "397462", "Score": "1", "body": "Please use JS formatting, not that of java. typical standards are that `{` are not on a new line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T...
[ { "body": "<p>Why not just compare directly to the charcode?</p>\n\n<pre><code>function characterToNumberCoverter(character) {\n let code = character.toUpperCase().charCodeAt(0);\n if (code &gt; 64 &amp;&amp; code &lt; 91) return code - 64\n return 0\n}\n</code></pre>\n", "comments": [ { "C...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T13:59:48.913", "Id": "206048", "Score": "1", "Tags": [ "javascript", "error-handling", "type-safety" ], "Title": "Function to map letters to numbers" }
206048
<p><strong>Background</strong><br> I have the below UDF that opens a workbook (this workbook has extracted data from a queue within another app). I get the used range from this workbook and assign it to an array (<code>aExtractedRange</code>). One of the elements in this array has the workbook name that I need to open and get Application Name for each element in the array. I open the second workbook and assign the used range to a second array (<code>aOPRange</code>) so that search is more efficient</p> <p><strong>Issue</strong><br> All of this works but as the first workbook can have 10K+ rows, it can take 30-40 seconds to perform this task. Is there anyway to make this faster? I have to work through few files a day so trying to see if I can improve the performance</p> <p><strong>UDF</strong></p> <pre><code>Sub GetAppName() Set oWB = ThisWorkbook Dim oFSO As New FileSystemObject Dim oExtractedFilesFolder As Folder: Set oExtractedFilesFolder = oFSO.GetFolder(oWB.Worksheets("Info").Range("C3")) Dim oFile As File Dim aExtractedRange As Variant Dim iC As Long Dim sLastFile As String Dim oOPFile As File Dim aOPRange As Variant Dim sCurEFile As String Dim iKeyValueCol As Long, iTagsCol As Long, iAccountIDCol As Long, iSystemNameCol As Long Dim aAppName As Variant Dim iAppRow As Long Dim iLCol As Long ' Loop through all files in the specified folder For Each oFile In oExtractedFilesFolder.Files ' Check if current workbook is one of the expected workbooks If InStr(1, oFile.Name, "Queue Report", vbTextCompare) &gt; 0 Then ' Get used range from file aExtractedRange = GetUsedRangeData(oFile, True, iKeyValueCol, iTagsCol) ' Did we get the range If IsArray(aExtractedRange) Then ' Get app name for all items in the array For iC = LBound(aExtractedRange) To UBound(aExtractedRange) ' Set current file name If InStr(1, aExtractedRange(iC, iTagsCol), ";") &gt; 0 Then sCurEFile = Left(Replace(aExtractedRange(iC, iTagsCol), "_IN", "_OP"), InStr(1, aExtractedRange(iC, 5), ";") - 1) Else sCurEFile = Replace(aExtractedRange(iC, iTagsCol), "_IN", "_OP") End If ' If current file is the same as last file, skip this section as we already have the correct details in the array If sLastFile &lt;&gt; sCurEFile Then Set oOPFile = FindFile(sCurEFile, oFSO.GetFolder(oWB.Worksheets("Info").Range("C2")).Path) ' Look for file in specified folder aOPRange = GetUsedRangeData(oOPFile, False, iAccountIDCol, iSystemNameCol) ' Get the used range from the file sLastFile = sCurEFile End If ' Add element to app name array If IsArray(aAppName) Then ReDim Preserve aAppName(UBound(aAppName) + 1) Else ReDim aAppName(0) End If ' Find row with specific account number iAppRow = 0 On Error Resume Next iAppRow = Application.WorksheetFunction.Match(aExtractedRange(iC, iKeyValueCol), Application.WorksheetFunction.Index(aOPRange, 0, iAccountIDCol), 0) On Error GoTo 0 ' Set app name based on row number If iAppRow &gt; 0 Then aAppName(UBound(aAppName)) = aOPRange(iAppRow, iSystemNameCol) Else aAppName(UBound(aAppName)) = "" End If Next End If End If Next With oWB.Worksheets("Sheet1") ' Copy extracted data to sheet .Range("A2").Resize(UBound(aExtractedRange, 1), UBound(aExtractedRange, 2)).Value = aExtractedRange ' Get last column iLCol = .Cells(1, .Columns.Count).End(xlToLeft).Column ' Copy app name to sheet .Range(ColLetter(iLCol + 1) &amp; "2").Resize(UBound(aAppName), 1).Value = aAppName End With ' Clear objects Set oExtractedFilesFolder = Nothing Set oFSO = Nothing Set oFile = Nothing End Sub </code></pre> <p><br><strong>P.S.</strong>: UDF sits in a module and makes calls to some other UDF's. Happy to explain what they are if needed<br><br></p> <p><strong>Edit</strong>: Adding <code>GetUsedRangeData</code> as requested</p> <pre><code>Function GetUsedRangeData(ByVal oFile As File, ByVal bExtractFile As Boolean, ByRef iCol1 As Long, ByRef iCol2 As Long) As Variant Dim oExtractWB As Workbook Dim iLRow As Long Dim iLCol As Long Dim sColName As String Application.ScreenUpdating = False Set oExtractWB = Application.Workbooks.Open(oFile) If bExtractFile Then iCol1 = FindColumn(oExtractWB.Worksheets(1), "KeyValue") iCol2 = FindColumn(oExtractWB.Worksheets(1), "Tags") Else iCol1 = FindColumn(oExtractWB.Worksheets(1), "Account ID") iCol2 = FindColumn(oExtractWB.Worksheets(1), "System Name") End If If iCol1 &gt;= 1 Or iCol2 &gt;= 1 Then With oExtractWB.Worksheets(1) iLRow = .Cells(.Rows.Count, 1).End(xlUp).Row iLCol = .Cells(1, .Columns.Count).End(xlToLeft).Column sColName = ColLetter(iLCol) GetUsedRangeData = .Range("A2:" &amp; sColName &amp; iLRow) End With End If oExtractWB.Close Application.ScreenUpdating = True Set oExtractWB = Nothing End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T15:16:46.007", "Id": "397472", "Score": "0", "body": "Try putting `aExtractedRange(iC, iTagsCol)` in a variable and more such repeated evaluations. That could make a difference. And the `aAppName` does not need a ReDim inside the lo...
[]
{ "AcceptedAnswerId": null, "CommentCount": "20", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T15:03:37.453", "Id": "206050", "Score": "2", "Tags": [ "array", "vba", "excel" ], "Title": "Use arrays to perform 'VLookUp' type activity between workbooks" }
206050
<p>I would like to know if there are ways to make this run faster. Not a big concern right now, but I would like to think long term, it might be important.</p> <p>This is C#, and I can not change the input parameters data types, but basically I have to make something like the SQL: <code>SELECT returnCol FROM dt WHERE ColName = ColValue</code></p> <p>As the datatable itself: it has more than 100 columns, but it should not too many rows, usually ~10 rows but it can spike up to 100 rows sometimes. This is part of a data parse that is happening once a minute, that is why I am trying to see if there are ways for enhancement.</p> <pre><code>private string FindInT(DataTable dt, string ColName, string ColValue, string returnCol) { foreach (DataRow row in dt.Rows) { if (row[ColName].ToString().ToLower().Trim() == ColValue.ToLower().Trim()) { return row[returnCol].ToString(); } } return ""; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T15:25:22.260", "Id": "397475", "Score": "2", "body": "There is absolutely nothing to worry about. With only 10 rows and 100 columns you will not even be able to measure the difference with a profiler." }, { "ContentLicense":...
[ { "body": "<p>I have two suggestions:</p>\n\n<ol>\n<li>Trim <code>ColValue</code> once rather than every iteration through the loop.</li>\n<li>Use a case-insensitive string compare rather than performing <code>.ToLower()</code> on two different strings on every loop iteration.</li>\n</ol>\n\n<p>Result:</p>\n\n<...
{ "AcceptedAnswerId": "206054", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T15:05:07.873", "Id": "206051", "Score": "0", "Tags": [ "c#", "performance", ".net-datatable" ], "Title": "Search DataTable by column for a specific row" }
206051
<p>Consider the following dummy dataset:</p> <pre><code>library(dplyr) set.seed(50) df &lt;- data.frame(PERSON_ID = sample(1:5, size = 32, replace = TRUE), YEAR = sample(2000:2001, size = 32, replace = TRUE), VALUES = sample(c("APPLE 50", "GRAPE 20", "ORANGE 50", "BANANA 80", "TOMATO 100", "PEACH 30", "CHOCOLATE 90"), size = 32, replace = TRUE), stringsAsFactors = FALSE) %&gt;% unique() person_ids &lt;- unique(df$PERSON_ID) </code></pre> <p>The data frame, in reality, is approximately 280,000-300,000 rows. Here is how the dataset looks:</p> <pre><code>df PERSON_ID YEAR VALUES 1 4 2000 APPLE 50 2 3 2001 APPLE 50 3 2 2000 PEACH 30 4 4 2001 APPLE 50 5 3 2000 APPLE 50 6 1 2001 CHOCOLATE 90 7 4 2000 BANANA 80 8 4 2000 CHOCOLATE 90 9 1 2000 TOMATO 100 10 1 2001 APPLE 50 11 2 2000 CHOCOLATE 90 12 2 2000 GRAPE 20 13 4 2000 TOMATO 100 15 2 2001 TOMATO 100 17 5 2001 BANANA 80 18 2 2001 APPLE 50 19 1 2001 ORANGE 50 20 1 2001 BANANA 80 21 4 2001 BANANA 80 22 1 2000 APPLE 50 24 5 2000 TOMATO 100 25 2 2001 BANANA 80 26 4 2001 TOMATO 100 27 3 2001 TOMATO 100 28 2 2000 TOMATO 100 29 2 2001 PEACH 30 31 2 2000 APPLE 50 32 3 2001 ORANGE 50 </code></pre> <p>I would like to execute the following code in a more efficient manner, which generates all possible <strong>pairs, triplets, and quadruplets of VALUES</strong> given a <strong>PERSON_ID</strong> and a <strong>YEAR</strong>.</p> <pre><code>generate_value_combinations &lt;- function(df, k){ for (i in 1:length(person_ids)){ temp_person_id &lt;- person_ids[i] temp &lt;- df %&gt;% filter(PERSON_ID == temp_person_id) years &lt;- unique(temp$YEAR) years_with_pairs &lt;- 0 for (j in 1:length(years)){ temp_year &lt;- temp %&gt;% filter(YEAR == years[j]) if (nrow(temp_year) &gt;= k){ years_with_pairs &lt;- years_with_pairs + 1 temp_year_pairs &lt;- data.frame(t(combn(temp_year$VALUES, m = k)), stringsAsFactors = FALSE) colnames(temp_year_pairs) &lt;- paste0("VALUE_", 1:ncol(temp_year_pairs)) rm(temp_year) temp_year_pairs$YEAR &lt;- years[j] temp_year_pairs$PERSON_ID &lt;- person_ids[i] if (years_with_pairs == 1){ temp_year_out &lt;- temp_year_pairs rm(temp_year_pairs) } else if (years_with_pairs &gt; 1) { temp_year_out &lt;- rbind(temp_year_out, temp_year_pairs) rm(temp_year_pairs) } } } rm(years, temp) if (i == 1 &amp; exists("temp_year_out")){ out &lt;- temp_year_out rm(temp_year_out) } else if(i &gt; 1 &amp; exists("temp_year_out")) { out &lt;- rbind(out, temp_year_out) rm(temp_year_out) } rm(temp_person_id) } return(out) } pairs &lt;- generate_value_combinations(df, k = 2) triples &lt;- generate_value_combinations(df, k = 3) quadruplets &lt;- generate_value_combinations(df, k = 4) </code></pre> <p>The code above takes approximately 1-2 hours to execute on the data set of 280,000-300,000 rows.</p> <p>For example, this is how <code>pairs</code> looks:</p> <pre><code>&gt; pairs VALUE_1 VALUE_2 YEAR PERSON_ID 1 APPLE 50 BANANA 80 2000 4 2 APPLE 50 CHOCOLATE 90 2000 4 3 APPLE 50 TOMATO 100 2000 4 4 BANANA 80 CHOCOLATE 90 2000 4 5 BANANA 80 TOMATO 100 2000 4 6 CHOCOLATE 90 TOMATO 100 2000 4 7 APPLE 50 BANANA 80 2001 4 8 APPLE 50 TOMATO 100 2001 4 9 BANANA 80 TOMATO 100 2001 4 10 APPLE 50 TOMATO 100 2001 3 11 APPLE 50 ORANGE 50 2001 3 12 TOMATO 100 ORANGE 50 2001 3 13 PEACH 30 CHOCOLATE 90 2000 2 14 PEACH 30 GRAPE 20 2000 2 15 PEACH 30 TOMATO 100 2000 2 16 PEACH 30 APPLE 50 2000 2 17 CHOCOLATE 90 GRAPE 20 2000 2 18 CHOCOLATE 90 TOMATO 100 2000 2 19 CHOCOLATE 90 APPLE 50 2000 2 20 GRAPE 20 TOMATO 100 2000 2 21 GRAPE 20 APPLE 50 2000 2 22 TOMATO 100 APPLE 50 2000 2 23 TOMATO 100 APPLE 50 2001 2 24 TOMATO 100 BANANA 80 2001 2 25 TOMATO 100 PEACH 30 2001 2 26 APPLE 50 BANANA 80 2001 2 27 APPLE 50 PEACH 30 2001 2 28 BANANA 80 PEACH 30 2001 2 29 CHOCOLATE 90 APPLE 50 2001 1 30 CHOCOLATE 90 ORANGE 50 2001 1 31 CHOCOLATE 90 BANANA 80 2001 1 32 APPLE 50 ORANGE 50 2001 1 33 APPLE 50 BANANA 80 2001 1 34 ORANGE 50 BANANA 80 2001 1 35 TOMATO 100 APPLE 50 2000 1 </code></pre> <p>To make these pairs/triplets/quadruplets consistent among different <code>PERSON_ID</code> and <code>YEAR</code> combination, we must sort the value columns. The case of pairs has already been covered at <a href="https://codereview.stackexchange.com/a/205923/69157">https://codereview.stackexchange.com/a/205923/69157</a>:</p> <pre><code>pairs[c('VALUE_1', 'VALUE_2')] &lt;- list(pmin(pairs$VALUE_1, pairs$VALUE_2), pmax(pairs$VALUE_1, pairs$VALUE_2)) &gt; pairs VALUE_1 VALUE_2 YEAR PERSON_ID 1 APPLE 50 BANANA 80 2000 4 2 APPLE 50 CHOCOLATE 90 2000 4 3 APPLE 50 TOMATO 100 2000 4 4 BANANA 80 CHOCOLATE 90 2000 4 5 BANANA 80 TOMATO 100 2000 4 6 CHOCOLATE 90 TOMATO 100 2000 4 7 APPLE 50 BANANA 80 2001 4 8 APPLE 50 TOMATO 100 2001 4 9 BANANA 80 TOMATO 100 2001 4 10 APPLE 50 TOMATO 100 2001 3 11 APPLE 50 ORANGE 50 2001 3 12 ORANGE 50 TOMATO 100 2001 3 13 CHOCOLATE 90 PEACH 30 2000 2 14 GRAPE 20 PEACH 30 2000 2 15 PEACH 30 TOMATO 100 2000 2 16 APPLE 50 PEACH 30 2000 2 17 CHOCOLATE 90 GRAPE 20 2000 2 18 CHOCOLATE 90 TOMATO 100 2000 2 19 APPLE 50 CHOCOLATE 90 2000 2 20 GRAPE 20 TOMATO 100 2000 2 21 APPLE 50 GRAPE 20 2000 2 22 APPLE 50 TOMATO 100 2000 2 23 APPLE 50 TOMATO 100 2001 2 24 BANANA 80 TOMATO 100 2001 2 25 PEACH 30 TOMATO 100 2001 2 26 APPLE 50 BANANA 80 2001 2 27 APPLE 50 PEACH 30 2001 2 28 BANANA 80 PEACH 30 2001 2 29 APPLE 50 CHOCOLATE 90 2001 1 30 CHOCOLATE 90 ORANGE 50 2001 1 31 BANANA 80 CHOCOLATE 90 2001 1 32 APPLE 50 ORANGE 50 2001 1 33 APPLE 50 BANANA 80 2001 1 34 BANANA 80 ORANGE 50 2001 1 35 APPLE 50 TOMATO 100 2000 1 </code></pre> <p>For triples and quadruplets, we have:</p> <pre><code>sort_df &lt;- function(df){ value_idx &lt;- max(as.numeric(sub("VALUE_", "", colnames(df)[grepl("VALUE_", colnames(df))]))) for (i in 1:nrow(df)){ if (value_idx == 3){ values &lt;- sort(c(df$VALUE_1[i], df$VALUE_2[i], df$VALUE_3[i])) } if (value_idx == 4){ values &lt;- sort(c(df$VALUE_1[i], df$VALUE_2[i], df$VALUE_3[i], df$VALUE_4[i])) } df$VALUE_1[i] &lt;- values[1] df$VALUE_2[i] &lt;- values[2] if (value_idx == 3){ df$VALUE_3[i] &lt;- values[3] } if (value_idx == 4){ df$VALUE_4[i] &lt;- values[4] } } return(df) } triples &lt;- sort_df(triples) quadruplets &lt;- sort_df(quadruplets) </code></pre> <p>How can this code be made more efficient?</p> <p><em>Edit</em>: I would like to mention that I know that "growing" data frames - which I do plenty of here - is considered bad practice in <code>R</code>, but I am unaware of how to alternatively code this.</p>
[]
[ { "body": "<p>That you know to use <code>dplyr</code> is a good start; I'd recommend you read a good tutorial to grasp the important concepts. For example, instead of looping on the PERSON_ID and YEAR, you should use <code>group_by</code>. Then, within each PERSON_ID/YEAR, you should apply a same function via <...
{ "AcceptedAnswerId": "206084", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T16:32:43.933", "Id": "206057", "Score": "1", "Tags": [ "performance", "sorting", "r" ], "Title": "Return a data frame with all possible pairs/triplets/quadruplets of a value column based on two identifiers, and order the value columns" }
206057
<p>I have the following method:</p> <pre><code>public void test() { List&lt;Integer&gt; slopeChanges = new ArrayList&lt;Integer&gt;(); slopeChanges.add(0); slopeChanges.add(0); slopeChanges.add(1); slopeChanges.add(0); slopeChanges.add(1); List&lt;Double&gt; sixProbabilites = new ArrayList&lt;Double&gt;(); int count_neg10 = 0, count_neg11 = 0, count_10 = 0, count_1neg1 = 0, count_0neg1 = 0, count_01 = 0; for(int i=0; i&lt;slopeChanges.size(); i++) { if(i+1 != slopeChanges.size()) { if((slopeChanges.get(i) == -1) &amp;&amp; (slopeChanges.get(i+1) == 0)) {count_neg10++;} else if((slopeChanges.get(i) == -1) &amp;&amp; (slopeChanges.get(i+1) == 1)) {count_neg11++;} else if((slopeChanges.get(i) == 1) &amp;&amp; (slopeChanges.get(i+1) == 0)) {count_10++;} else if((slopeChanges.get(i) == 1) &amp;&amp; (slopeChanges.get(i+1) == -1)) {count_1neg1++;} else if((slopeChanges.get(i) == 0) &amp;&amp; (slopeChanges.get(i+1) == -1)) {count_0neg1++;} else if((slopeChanges.get(i) == 0) &amp;&amp; (slopeChanges.get(i+1) == 1)) {count_01++;} }else { if((slopeChanges.get(i) == -1) &amp;&amp; (slopeChanges.get(0) == 0)) {count_neg10++;} else if((slopeChanges.get(i) == -1) &amp;&amp; (slopeChanges.get(0) == 1)) {count_neg11++;} else if((slopeChanges.get(i) == 1) &amp;&amp; (slopeChanges.get(0) == 0)) {count_10++;} else if((slopeChanges.get(i) == 1) &amp;&amp; (slopeChanges.get(0) == -1)) {count_1neg1++;} else if((slopeChanges.get(i) == 0) &amp;&amp; (slopeChanges.get(0) == -1)) {count_0neg1++;} else if((slopeChanges.get(i) == 0) &amp;&amp; (slopeChanges.get(0) == 1)) {count_01++;} } } System.out.println(slopeChanges); if(count_neg10 != 0) {System.out.println("count_neg10 = " + count_neg10);} if(count_neg11 != 0) {System.out.println("count_neg11 = " + count_neg11);} if(count_10 != 0) {System.out.println("count_10 = " + count_10);} if(count_1neg1 != 0) {System.out.println("count_1neg1 = " + count_1neg1);} if(count_0neg1 != 0) {System.out.println("count_0neg1 = " + count_0neg1);} if(count_01 != 0) {System.out.println("count_01 = " + count_01);} if(count_neg10 != 0) {sixProbabilites.add((double)count_neg10 / ((double)slopeChanges.size()));} if(count_neg11 != 0) {sixProbabilites.add((double)count_neg11 / ((double)slopeChanges.size()));} if(count_10 != 0) {sixProbabilites.add((double)count_10 / ((double)slopeChanges.size()));} if(count_1neg1 != 0) {sixProbabilites.add((double)count_1neg1 / ((double)slopeChanges.size()));} if(count_0neg1 != 0) {sixProbabilites.add((double)count_0neg1 / ((double)slopeChanges.size()));} if(count_01 != 0) {sixProbabilites.add((double)count_01 / ((double)slopeChanges.size()));} } </code></pre> <p>The <code>slopeChanges</code> list contains symbols that are either 0, 1, or -1. I would like to count frequencies of sub-blocks that are either <code>01, 10, -11, 1-1, -10, 0-1</code>. The method that I showed does what I want, for example, this block of symbols <code>00101</code> should result in <code>count_10 = 2</code> which means <code>10</code> sub-block occurs twice while <code>01</code> (i.e., <code>count_01 = 2</code>) occurs twice. Please note that the we consider the first symbol is also last.</p> <p>As you can see, there are lot of duplication in the code in order to perform what I want. Is there a better way to re-write this function in a very elegant style?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T17:03:13.243", "Id": "397485", "Score": "0", "body": "are you sure of this: _this block of symbols `00101` should result in `count_10 = 2` which means 10 sub-block occurs twice_" }, { "ContentLicense": "CC BY-SA 4.0", "C...
[ { "body": "<p>You can remove some <code>else</code> using two indexes, and aggregate <code>if</code>.</p>\n\n<pre><code>public void test() {\n\n List&lt;Integer&gt; slopeChanges = new ArrayList&lt;Integer&gt;();\n slopeChanges.add(0);\n slopeChanges.add(0);\n slopeChanges.add(1);\n slopeChanges.a...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T16:46:54.920", "Id": "206060", "Score": "4", "Tags": [ "java" ], "Title": "Counting pairs of elements in a circular ArrayList containing -1, 0, and 1" }
206060
<h2>Intro</h2> <p>I'm going through the K&amp;R book (2nd edition, ANSI C ver.) and want to get the most from it: learn (outdated) C and practice problem-solving at the same time. For that reason, I'm trying to solve the exercises "hardcore" - without using any knowledge from the "future". I'll catch-up with it after I finish the book.</p> <p>I believe that the author's intention was to give the reader a good exercise, to make the reader think hard about what he can do with the tools introduced, and not to skip ahead to find an easier way. For that reason, I'm only using language features introduced up to this point in the book. That also means I'm using an old C standard.</p> <p>Compiling with <code>gcc -Wall -Wextra -Wconversion -pedantic -ansi</code>.</p> <h2>K&amp;R Exercise 1-19</h2> <p>Write a function <code>reverse(s)</code> that reverses the character string <code>s</code>. Use it to write a program that reverses its input a line at a time.</p> <h2>Solution</h2> <p>The task explicitly states how the function should look like. For that reason, I've coded it similarly to how the author made his <code>copy</code> function.</p> <p>The 2nd part of the challenge is to reverse the program input <strong>a line at a time</strong>, but how long can the line be? It would be too easy to set a hard limit for line length, just loop line by line and return an error if it's exceeded. I can't use dynamic memory allocation to deal with arbitrary long lines since it hasn't been introduced yet so what's left? The book already introduced all the building blocks I need for recursion, so at this point it the only solution.</p> <h2>Code</h2> <pre><code>/* Exercise 1-19. Write a function `reverse(s)` that reverses the * character string `s`. Use it to write a program that reverses its * input a line at a time. */ #include &lt;stdio.h&gt; #define BUFSIZE 10 /* line buffer size */ int getline(char line[], int maxline); void copy(char to[], char from[]); void reverse(char s[]); int reverseinput(char lastchar[]); main() { char lastchar[1]; while (reverseinput(lastchar) != 0) if (lastchar[0] == '\n') putchar('\n'); return 0; } /* reverseinput: read from input until end of line is reached and then * print the line in reverse */ int reverseinput(char lastchar[]) { int len; char line[BUFSIZE]; int retval; if ((len = getline(line, BUFSIZE)) &gt; 0) { if ((lastchar[0] = line[len-1]) == '\n') { line[len-1] = '\0'; retval = 1; } else retval = reverseinput(lastchar); reverse(line); printf("%s", line); } else retval = 0; return retval; } /* getline: read a line into s, return length */ int getline(char s[],int lim) { int c, i; for (i=0; i &lt; lim-1 &amp;&amp; (c=getchar())!=EOF &amp;&amp; c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } /* copy: copy 'from' into 'to'; assume to is big enough */ void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; } /* reverse: reverse a '\0' terminated string */ void reverse(char s[]) { int tail; int head; char c; /* find the last character index */ tail = 0; while (s[tail] != '\0') ++tail; if (tail &gt; 0) --tail; /* reverse the string by swapping first and last elements */ for (head = 0; head &lt; tail; ++head &amp;&amp; --tail) { c = s[head]; s[head] = s[tail]; s[tail] = c; } } </code></pre> <h2>Test</h2> <p>Running <code>$ ./ch1-ex-1-19-01 &lt;ch1-ex-1-19-01.c | ./ch1-ex-1-19-01</code> prints the program code :)</p>
[]
[ { "body": "<p>It's good practice to use prototypes for all functions, including <code>main()</code>. Don't rely on unspecified argument lists and on return type defaulting to <code>int</code> - which goes away in later standards:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<hr>\n\n<p>It seems odd to use...
{ "AcceptedAnswerId": "206111", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T17:56:04.020", "Id": "206064", "Score": "3", "Tags": [ "beginner", "c", "strings", "recursion", "io" ], "Title": "K&R Exercise 1-19. Reverse program input one line at a time" }
206064
<p>I have a huge <em>Google Photos</em> directory that is difficult to navigate - there are just too many files so I thougt I need to sort them somehow. I decided to make it simple and group them by date-taken. As I always wanted to learn python I thought I'll give it a try so this is my first take on it. </p> <p>There is no rocket-science here (yet). It looks for files in the <code>pictures_path</code>, groups them by their modified date, enumerates this iterator, creates directories and moves or copies files according to the <code>whatif</code> option. This is measured by the <code>perf_counter()</code>.</p> <p>I'd be great if you could take a look at it and tell me whether I did something terribly wrong as a beginner before I let it work with my actual collection.</p> <pre><code>import os import time import itertools import shutil from pprint import pprint def format_filemtime(path): filemtime = os.path.getmtime(path) return time.strftime('%Y-%m-%d', time.gmtime(filemtime)) def group_pictures(whatif=False): pictures_path = "C:\\temp\\picturepy\\pictures\\" galleries_path = "C:\\temp\\picturepy\\galleries\\" start = time.perf_counter() picture_names = os.listdir(pictures_path) print(f"picture count: {len(picture_names)}") pictures_by_mtime = itertools.groupby(picture_names, lambda name: format_filemtime(os.path.join(pictures_path,name))) for (dir, picture_names) in pictures_by_mtime: path_dir = os.path.join(galleries_path, dir) if not os.path.exists(path_dir): os.makedirs(path_dir) print(f"'{dir}' created.") else: print(f"'{dir}' already exists.") do = shutil.copyfile if whatif else shutil.move verb = "copied" if whatif else "moved" for file in picture_names: do( src=os.path.join(pictures_path, file), dst=os.path.join(path_dir, file)) print(f"\t'{file}' {verb}.") end = time.perf_counter() elapsed = round(end - start,2) print(f"elapsed: {elapsed} sec") # --- --- --- def main(): group_pictures(whatif=True) #group_pictures() if __name__ == '__main__': main() </code></pre> <p>I tested it with <code>VSCode</code> and it's doing its job pretty well.</p>
[]
[ { "body": "<p>This looks pretty decent for a first Python program, so good job on that.</p>\n\n<p>I only have a few small nitpicks</p>\n\n<ul>\n<li><p>Some <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> violations, but nothing major</p>\n\n<ol>\n<li><p>There should be...
{ "AcceptedAnswerId": "206185", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T17:59:15.323", "Id": "206065", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "file-system" ], "Title": "Moving or copying images from a flat directory to subdirectories" }
206065
<p>So I'm currently working on sort of an SDL engine (may be too ambitious I know). I'm seeking that it would be my first actual project and it's also the first time I'm seriously using classes. So I would like to know if there are any significant improvements I can make to this class to make it as good as it can be (having a class that randomly fails is kind of suicide). The one thing that bugs me at the moment is that the copy constructor and the copy assignment operator is exactly the same. If that's not fixable, are there any underlying problems I could fix? Thanks in advance.</p> <pre><code>#ifndef TEXT_H #define TEXT_H #define TEXTSIZE 50 #define FONTPATHSIZE 50 #define DEFAULTFONTSIZE 24 #define DEFAULTFONTCOLOR {255, 255, 255} #define DEFAULTFONT "Fonts/Ubuntu.ttf" class Text { public: Text(){ loaderFunction = TTF_RenderText_Blended; good = false; visable = true; numerical = false; renderer = NULL; sprite = NULL; number = NULL; font = NULL; oldNumber = 0; fontSize = DEFAULTFONTSIZE; textColor = DEFAULTFONTCOLOR; strcpy(this-&gt;fontPath, DEFAULTFONT); strcpy(this-&gt;text, ""); ZeroMemory(&amp;srcRect, sizeof(srcRect)); ZeroMemory(&amp;dstRect, sizeof(srcRect)); } Text(const Text&amp; passedObject){ strcpy(this-&gt;text, passedObject.text); strcpy(this-&gt;fontPath, passedObject.fontPath); this-&gt;loaderFunction = passedObject.loaderFunction; this-&gt;numerical = passedObject.numerical; this-&gt;textColor = passedObject.textColor; this-&gt;oldNumber = passedObject.oldNumber; this-&gt;fontSize = passedObject.fontSize; this-&gt;renderer = passedObject.renderer; this-&gt;srcRect = passedObject.srcRect; this-&gt;dstRect = passedObject.dstRect; this-&gt;visable = passedObject.visable; this-&gt;number = passedObject.number; this-&gt;good = passedObject.good; this-&gt;font = TTF_OpenFont(this-&gt;fontPath, this-&gt;fontSize); Load(); // Sets the sprite } ~Text(){ SDL_DestroyTexture(this-&gt;sprite); TTF_CloseFont(this-&gt;font); } Text&amp; operator=(const Text&amp; passedObject){ strcpy(this-&gt;text, passedObject.text); strcpy(this-&gt;fontPath, passedObject.fontPath); this-&gt;loaderFunction = passedObject.loaderFunction; this-&gt;numerical = passedObject.numerical; this-&gt;textColor = passedObject.textColor; this-&gt;oldNumber = passedObject.oldNumber; this-&gt;fontSize = passedObject.fontSize; this-&gt;renderer = passedObject.renderer; this-&gt;srcRect = passedObject.srcRect; this-&gt;dstRect = passedObject.dstRect; this-&gt;visable = passedObject.visable; this-&gt;number = passedObject.number; this-&gt;good = passedObject.good; this-&gt;font = TTF_OpenFont(this-&gt;fontPath, this-&gt;fontSize); Load(); // Sets the sprite return *this; } Text&amp; operator=(const char* text){ ChangeText(text); return *this; } // Functionality functions void Initialize(SDL_Renderer* renderer, const char* text, const char* fontPath, int fontSize, SDL_Color textColor, int x, int y, bool numerical, int* number = NULL){ strcpy(this-&gt;fontPath, fontPath); strcpy(this-&gt;text, text); this-&gt;renderer = renderer; this-&gt;fontSize = fontSize; this-&gt;textColor = textColor; this-&gt;numerical = numerical; this-&gt;number = number; this-&gt;dstRect.x = x; this-&gt;dstRect.y = y; this-&gt;font = TTF_OpenFont(this-&gt;fontPath, this-&gt;fontSize); this-&gt;good = true; Load(); } void Initialize(SDL_Renderer* renderer, const char* text, int x, int y){ strcpy(this-&gt;text, text); this-&gt;renderer = renderer; this-&gt;dstRect.x = x; this-&gt;dstRect.y = y; this-&gt;font = TTF_OpenFont(this-&gt;fontPath, this-&gt;fontSize); this-&gt;good = true; Load(); } void Draw(){ if(visable &amp;&amp; good) SDL_RenderCopy(renderer, sprite, &amp;srcRect, &amp;dstRect); } void Load(){ if(sprite != NULL) SDL_DestroyTexture(sprite); if(this-&gt;font == NULL) return; SDL_Surface* loader = loaderFunction(this-&gt;font, this-&gt;text, this-&gt;textColor); sprite = SDL_CreateTextureFromSurface(this-&gt;renderer, loader); srcRect.w = loader-&gt;w; srcRect.h = loader-&gt;h; dstRect.w = loader-&gt;w; dstRect.h = loader-&gt;h; SDL_FreeSurface(loader); } void Update(){ if(!numerical || oldNumber == *number) return; if(sprite != NULL) SDL_DestroyTexture(sprite); // Create a temporary string static char temp[TEXTSIZE]; strcpy(temp, this-&gt;text); sprintf(temp, "%s%d", temp, *number); SDL_Surface* loader = loaderFunction(this-&gt;font, temp, this-&gt;textColor); sprite = SDL_CreateTextureFromSurface(this-&gt;renderer, loader); //Resize the text srcRect.w = loader-&gt;w; dstRect.w = loader-&gt;w; srcRect.h = loader-&gt;h; dstRect.h = loader-&gt;h; oldNumber = *number; SDL_FreeSurface(loader); } // Manipulation functions void ChangeText(const char* text){ if(!strcmp(this-&gt;text, text)) return; strcpy(this-&gt;text, text); // Reload the sprite Load(); } void ChangeTextColor(SDL_Color textColor){ this-&gt;textColor = textColor; // Reload the sprite Load(); } void ChangeFont(const char* fontPath){ if(!strcmp(this-&gt;fontPath, fontPath)) return; strcpy(this-&gt;fontPath, fontPath); if(this-&gt;font != NULL) TTF_CloseFont(font); // Load the new font font = TTF_OpenFont(this-&gt;fontPath, this-&gt;fontSize); // Reload the sprite Load(); } void ChangeFontSize(int fontSize){ if(this-&gt;fontSize == fontSize) return; if(this-&gt;font != NULL) TTF_CloseFont(font); this-&gt;fontSize = fontSize; // Load the new font font = TTF_OpenFont(this-&gt;fontPath, this-&gt;fontSize); // Reload the sprite Load(); } void ChangeRenderer(SDL_Renderer* renderer){ this-&gt;renderer = renderer; } void ChangeVisability(bool visable){ this-&gt;visable = visable; } void ChangeLoaderFunction(SDL_Surface* (*loaderFunction)(TTF_Font*, const char*, SDL_Color)){ this-&gt;loaderFunction = loaderFunction; } void ChangeNumber(int* number){ this-&gt;number = number; } void SetNumericality(bool numerical){ this-&gt;numerical = numerical; } void SetX(int x){ this-&gt;dstRect.x = x; } void SetY(int y){ this-&gt;dstRect.y = y; } // Variables SDL_Surface* (*loaderFunction)(TTF_Font*, const char*, SDL_Color); char text[TEXTSIZE], fontPath[FONTPATHSIZE]; bool good, visable, numerical; int fontSize, *number, oldNumber; SDL_Color textColor; TTF_Font* font; SDL_Rect srcRect, dstRect; SDL_Renderer* renderer; SDL_Texture* sprite; }; #endif </code></pre>
[]
[ { "body": "<p><strong>Code:</strong></p>\n\n<ul>\n<li><p>Prefix the header guard with something unique (at least to the project) to prevent possible collisions. (e.g. <code>MYPROJNAME_TEXT_H</code> ).</p>\n\n<pre><code>#ifndef PROJECTNAME_TEXT_H\n#define PROJECTNAME_TEXT_H\n\n...\n\n#endif // PROJECTNAME_TEXT_H...
{ "AcceptedAnswerId": "206112", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T18:14:38.653", "Id": "206067", "Score": "4", "Tags": [ "c++", "sdl" ], "Title": "TTF/SDL based class for text handling" }
206067
<p><a href="https://projecteuler.net/problem=378" rel="nofollow noreferrer">Project Euler problem 378</a> says:</p> <blockquote> <p>Let <span class="math-container">\$T(n)\$</span> be the <span class="math-container">\$n\$</span>th triangle number, so <span class="math-container">\$T(n) = {n (n+1) \over 2}\$</span>.</p> <p>Let <span class="math-container">\$\mathit{dT}(n)\$</span> be the number of divisors of <span class="math-container">\$T(n)\$</span>.<br> E.g.: <span class="math-container">\$T(7) = 28\$</span> and <span class="math-container">\$\mathit{dT}(7) = 6\$</span>.</p> <p>Let <span class="math-container">\$\mathit{Tr}(n)\$</span> be the number of triples <span class="math-container">\$(i, j, k)\$</span> such that <span class="math-container">\$1 ≤ i &lt; j &lt; k ≤ n\$</span> and <span class="math-container">\$\mathit{dT}(i) &gt; \mathit{dT}(j) &gt; \mathit{dT}(k)\$</span>.<br> <span class="math-container">\$\mathit{Tr}(20) = 14\$</span>, <span class="math-container">\$\mathit{Tr}(100) = 5772\$</span> and <span class="math-container">\$\mathit{Tr}(1000) = 11174776\$</span>.</p> <p>Find <span class="math-container">\$\mathit{Tr}(60\,000\,000)\$</span>.<br> Give the last 18 digits of your answer.</p> </blockquote> <p>This is my attempt at solving it:</p> <pre><code>def t(n): tri_num = (n * (n+1))//2 return tri_num #finding nth triangle numbers def dt(n): count = 0 for i in range(1,t(n)+1): if t(n)%i == 0: count += 1 return count #finding nth triangle numbers' total number of dividers def factors(n): factors = [] for i in range(1,t(n)+1): if t(n)%i == 0: factors.append(i) return factors #finding nth triangle number's dividers def tr(n): triplesnum = 0 triples = [(i, j, k) for i in range(n) for j in range(n) for k in range(n) if 1 &lt;= i &lt; j &lt; k &lt;= n and dt(i) &gt; dt(j) &gt; dt(k)] for i in triples: triplesnum += 1 return triplesnum while True: n = int(input("N =???")) print("triples number",tr(n)) #solution </code></pre> <p>I am new to python; I only know at most the loops,list comprehension, functions, and some class. I am sure this problem can be solved more simply.</p> <p>Although I see this code as a success considering my knowledge, it works too slowly for me after 3-digit values of <code>n</code>.</p> <p>Is there an improvement I can make with my current knowledge? If not, what should I be learning about next?</p> <p>Note: I know some of the code is not necessary, but I used them as a testing material in the further functions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T20:01:56.803", "Id": "397502", "Score": "2", "body": "Have you solved Project Euler #12?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T20:13:39.493", "Id": "397503", "Score": "4", "body"...
[ { "body": "<p>We can improve your code in many areas.</p>\n\n<p>First, a baseline on my laptop. Run time for <code>N=70</code> is 16.4 seconds.</p>\n\n<p><code>t(n)</code> is only called inside <code>dt(n)</code>, so we can avoid the extra function call and remove <code>t(n)</code> and move the calculation ins...
{ "AcceptedAnswerId": "206091", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T18:50:43.330", "Id": "206070", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Project Euler 378: Count ordered triplets whose triangular numbers have decreasing number of factors" }
206070
<p>I am looking to hide an email id name, by only showing first 4 letters of the email. The code works fine. Looking for opinion if I could make it better, more readable and maybe even more efficient if possible. I am using Commons lang library for this and wondering if that is an unnecessary overhead. </p> <p>Please look for the comment <code>&lt;-- HERE --&gt;</code>. I am looking for opinion in this region. I am using Java 7, no way around that.</p> <pre><code>import org.apache.commons.lang.StringUtils; import java.util.HashMap; import java.util.Map; public class App { public static void main(String[] args) { //all these prints out as expected. String newEmail1 = getEmail("sample1"); System.out.println("Expected: some**@gmail.com | actual: " + newEmail1); String newEmail2 = getEmail("sample2"); System.out.println("Expected: null | actual: " + newEmail2); String newEmail3 = getEmail("short"); System.out.println("Expected: q**@gmail.com | actual: " + newEmail3); String newEmail4 = getEmail("noname"); System.out.println("Expected: null | actual: " + newEmail4); } private static String getEmail(String param){ //added these solely for testing to show Map&lt;String, String&gt; emails = new HashMap&lt;&gt;(); emails.put("sample1", "someone@gmail.com"); emails.put("short", "qw@gmail.com"); emails.put("noname", "@gmail.com"); //added these solely for testing to show //I am looking for opinions from here onwards. &lt;-- HERE --&gt; String emailAddress = emails.get(param); if(emailAddress != null){ String emailAddressFront = StringUtils.substringBefore(emailAddress, "@"); String emailAddressBack = StringUtils.substringAfter(emailAddress, "@"); // i need to hide emails by only revealing first 4 characters. // but also need to check in case email name is shorter than 4. if(emailAddressFront.isEmpty()){ return null; } int shortenedLength = 4; int emailNameLength = emailAddressFront.length(); if(emailNameLength &lt; 4){ shortenedLength = emailNameLength - 1; } emailAddress = emailAddressFront.substring(0, shortenedLength) + "**@" + emailAddressBack; } return emailAddress; //I am looking for opinions till here. &lt;-- HERE --&gt; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T22:05:51.783", "Id": "397513", "Score": "0", "body": "Looks like there's a `java.mail.internet.InternetAddress` class that may do the email parsing you want (ie can return just the front). I found [the documentation](https://docs.or...
[ { "body": "<p>Guard clauses are easier to read than nested blocks.</p>\n\n<p>It will be somewhat more efficient to track the index of the <code>@</code> sign rather than using substrings. You definitely don’t need Apache commons.</p>\n\n<p>Try not to reassign variables if you can help it. In this case, you can ...
{ "AcceptedAnswerId": "206088", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T19:22:17.413", "Id": "206071", "Score": "2", "Tags": [ "java", "strings", "email" ], "Title": "Trimming email address to hide the name" }
206071
<p>I recently updated Pandas and noticed that it is no longer possible to merge DataFrames with mismatched dtypes. I have a script which relied on merging and seemed to work in the past despite having mismatched dtypes. I need to display to the user which columns in two dataframes are causing problems, so the user can then adjust the types accordingly. (Specifically, one dataframe is read in from a database and represents what is currently in the DB, while the second dataframe includes any changes/new data to be applied to the database. Once the the user finds the problem columns they can determine if the DataFrame that contains the changes was meant to change the database's type or whether there is an error in the changes). The following code appears to work, but I feel like pandas must have a built in better way to deal with this problem. </p> <pre><code>def get_mismatched_dtypes(self, df1, df2): mismatch = {} for key, val in df1.dtypes.iteritems(): if key in df2.dtypes and df2.dtypes[key] != val: mismatch[key] = (f"df1:{val}, df2: {df2.dtypes[key]}") print(mismatch) return mismatch </code></pre>
[]
[ { "body": "<h1><code>self</code></h1>\n\n<p>Why put this method on a class? the lack of use of <code>self</code> in the method should act as a flag</p>\n\n<h1>string result</h1>\n\n<p>you format the mismatch as a string (<code>f\"df1:{val}, df2: {df2.dtypes[key]}\"</code>). This way you can not do anything abou...
{ "AcceptedAnswerId": "206101", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-22T22:42:21.540", "Id": "206081", "Score": "1", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Display the difference between DataFrames' dtypes?" }
206081
<p>I have been studying graphs/BFS/DFS. working on wrapping my head around the following problem</p> <blockquote> <p>Given a grid [m,n] where each cell has a value denotes a color, find the longest connected region that shares the same color (color is an int)</p> </blockquote> <p>I was able to come up with the following algorithm that uses a (BFS) Breadth Search First mechanism. I would appreciate your feedback.</p> <p>I also wanted to try and craft a solution using DFS. I know I might run into a stack overflow issues if the graph is too big. However, I would appreciate any feedback on how to construct my algo using DFS ( I couldn't wrap my head around DFS with different colors at play)</p> <p>The initialization method:</p> <pre><code>/// &lt;summary&gt; /// Finds the longest connect region per color. /// &lt;/summary&gt; /// &lt;returns&gt;Returns a pair that has the color and the count of the connected cells&lt;/returns&gt; public static Tuple&lt;int,int&gt; FindLongestConnectedColor() { int[,] graph = { {1, 1, 1, 2,2,3}, {1, 1, 1, 2,2,3}, {1, 1, 1, 2,2,3} }; var graphRowsCount = graph.GetLength(0); var graphColumnsCount = graph.GetLength(1); var visitedCellsPerColor = new Dictionary&lt;int, HashSet&lt;Tuple&lt;int, int&gt;&gt;&gt;(); // first int represents the color, second int represents the region cells' count var longestRegion = new Tuple&lt;int, int&gt;(-1, -1); for (int row = 0; row &lt; graphRowsCount; row++) { for (int column = 0; column &lt; graphColumnsCount; column++) { var color = graph[row, column]; if (!visitedCellsPerColor.ContainsKey(color)) { visitedCellsPerColor.Add(color, new HashSet&lt;Tuple&lt;int, int&gt;&gt;()); } if (!visitedCellsPerColor[color].Contains(new Tuple&lt;int, int&gt;(row, column))) { var length = GetConnectedRegionLength(row, column, graph, visitedCellsPerColor); if (longestRegion.Item2 &lt; length) { longestRegion = new Tuple&lt;int, int&gt;(color, length); } } } } return longestRegion; } </code></pre> <p>My BFS logic</p> <ul> <li>I am using two queues to avoid boxing/unboxing performance hit</li> <li>I only consider cells that are of the same color </li> <li>I only consider unvisited cells if they belong to the same color</li> </ul> <p>Code:</p> <pre><code>private static int GetConnectedRegionLength(int row, int column, int[,] graph, Dictionary&lt;int, HashSet&lt;Tuple&lt;int, int&gt;&gt;&gt; visited) { var directionRow = new List&lt;int&gt; { -1, +1, 0, 0 }; var directionColumn = new List&lt;int&gt; { 0, 0, +1, -1 }; var graphRowsCount = graph.GetLength(0); var graphColumnsCount = graph.GetLength(1); var connectedCellsCount = 0; var color = graph[row, column]; var q1 = new Queue&lt;int&gt;(); var q2 = new Queue&lt;int&gt;(); q1.Enqueue(row); q2.Enqueue(column); visited[color].Add(new Tuple&lt;int, int&gt;(row, column)); connectedCellsCount++; while (q1.Any()) { // current Row var cr = q1.Dequeue(); // Current Column var cc = q2.Dequeue(); for (int a = 0; a &lt; directionRow.Count; a++) { var newRow = cr + directionRow[a]; var newColumn = cc + directionColumn[a]; if (newRow &lt; 0 || newColumn &lt; 0) continue; if (newRow &gt;= graphRowsCount || newColumn &gt;= graphColumnsCount ) continue; if (graph[newRow, newColumn] != color) continue; if (visited[color].Contains(new Tuple&lt;int, int&gt;(newRow, newColumn))) continue; q1.Enqueue(newRow); q2.Enqueue(newColumn); visited[color].Add(new Tuple&lt;int, int&gt;(newRow, newColumn)); connectedCellsCount++; } } return connectedCellsCount; } </code></pre>
[]
[ { "body": "<p>Looks fine overall, but there are a few oddities here and there, and there are some opportunities for significant performance improvements:</p>\n\n<ul>\n<li>Since you're going to visit every node in the given <code>int[,]</code> graph you might as well use a <code>bool[,]</code> instead of a <code...
{ "AcceptedAnswerId": "206100", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T01:47:03.290", "Id": "206086", "Score": "4", "Tags": [ "c#", "graph", "breadth-first-search", "depth-first-search" ], "Title": "Find the longest connect cells region per color" }
206086
<p>The functions below are from a class of slave function which interact with my mongo database. The purpose is to serve a Flask based API by responding with the appropriate data required along with the status code. The following 5 functions are </p> <ol> <li>Init</li> <li>Add Data</li> <li>Return/Fetch Data</li> <li>Search Data </li> <li>Delete Data</li> </ol> <p>The request is to optimize each function so that it abides the best prctices and becomes as error free as possible.</p> <p><strong>1. Init</strong> The init method initializes an object for the class which forms a connection to the Mongo Database. The database has 2 collections which are to be used by this class, the same are made into the <code>list_client</code> and <code>dets_client</code> object. </p> <pre><code>def __init__(self, app): URI = "mongodb://127.0.0.1:27017/source" mongo = PyMongo(app, URI) self.list_client = mongo.db['subjects.list'] self.dets_client = mongo.db['subjects.dets'] </code></pre> <p><strong>2. Add Data</strong> The <code>add_sub_list</code> function is used to add a new subject to the database. This is done when a user sends a POST request to the appropriate route with the data in <code>{col_code:code, title:name, sub_code:code}</code> format. The <code>link</code> is a parameter to be made by the data the function recieves from the API and has to be consumed by in the project later. The initail try expect statements are there to prevent wrong data being added. ex- College does not exist or parameters sent are wrong. The if condition is to prevent duplication of data. The function adds new data to the first collection(sub_list) while making an instance of the same subject in the second collection(sub-data).</p> <pre><code>def add_sub_list(self, sub_data): # NOTE: Function data col_code, {"title": name, "sub_code": code} try: if not self.list_client.find_one({"sub.sub_code": sub_data['sub_code'], "col_code": sub_data['col_code']}): if not self.list_client.find_one({"sub.title": sub_data['title'], "col_code": sub_data['col_code']}): self.dets_client.insert_one(sub_data) col_code = sub_data.pop("col_code") link = '/{}/{}'.format(self.list_client.find_one({"col_code": col_code}) ["college"], sub_data["sub_code"]) sub_data['link'] = link self.list_client.find_one_and_update( {"col_code": col_code}, {'$push': {'sub': sub_data}}, upsert=True) return {"status": 200, "data": "Success"} else: return {"status": 403, "data": "Subject already Exists"} else: return {"status": 403, "data": "Subject already Exists"} except KeyError: return {"status": 404, "data": "Wrong Parameters"} except TypeError: return {"status": 404, "data": "No such College"} </code></pre> <p><strong>3. Fetch Data</strong> The <code>get_all</code> function fetches the complete data in the list collection the <code>{_id: 0}</code> has to be added as the data is further converted into JSON format by the API method which called it.</p> <pre><code> def get_all(self): print([colls for colls in self.list_client.find({}, {'_id': 0})]) return {"status": 200, "data": [colls for colls in self.list_client.find({}, {'_id': 0, 'sub._id':0})]} </code></pre> <p><strong>4. Search Data</strong> The <code>search</code> function is used to search for relevent subjects from the details collection as the user sends a term which can be a substring of the title of a subject. The results are further optimized by the user sending the college code along with the data, but that is optional, thus the if condition. This Function has the most potental to be optimized and improved.</p> <pre><code>def search(self, data): term = re.compile('{}'.format(data['term']), re.IGNORECASE) if data['col_code']: return {"status": 200, "data": [x for x in self.dets_client.find( {"title": term, "col_code": data["col_code"]}, {"_id": 0, "title": 1, "sub_code": 1, "col_code": 1})]} else: return {"status": 200, "data": [x for x in self.dets_client.find( {"title": term}, {"_id": 0, "title": 1, "sub_code": 1, "col_code": 1})]} </code></pre> <p><strong>5. Delete Data</strong> The <code>rem_sub</code> function is used to remove a subject from the list as well as the details collection. Update is used in list removal as the subject is actually a subdocument in an array. </p> <pre><code> def rem_sub(self, sub_data): try: if self.list_client.find_one({"sub.sub_code": sub_data['sub_code'], "col_code": sub_data['col_code']}): self.dets_client.remove({'sub_code': sub_data}) col_code = sub_data.pop("col_code") self.list_client.update( {"col_code": col_code}, {'$pull': {'sub': sub_data}}) return {"status": 200, "data": "Success"} else: return {"status": 403, "data": "Subject Does not Exists in the given college"} except KeyError: return {"status": 404, "data": "Wrong Parameters"} except TypeError: return {"status": 404, "data": "No such College"} </code></pre> <p>I feel that this code is not at all optimized and can be improved greatly and would really need best practices to be implimented. Any suggestions are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T05:58:35.097", "Id": "397533", "Score": "0", "body": "Welcome to Code Review. This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what yo...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T02:01:51.080", "Id": "206087", "Score": "2", "Tags": [ "python", "python-3.x", "mongodb", "flask", "pymongo" ], "Title": "Flask-PyMongo best practices to manage a mongodb database using python" }
206087
<p>I am working on the MAXSPPROD problem on interviewBit</p> <blockquote> <p>You are given an array A containing N integers. The special product of each ith integer in this array is defined as the product of the following:</p> <p>LeftSpecialValue: For an index i, it is defined as the index j such that A[j]>A[i] (i>j). If multiple A[j]’s are present in multiple positions, the LeftSpecialValue is the maximum value of j.</p> <p>RightSpecialValue: For an index i, it is defined as the index j such that A[j]>A[i] (j>i). If multiple A[j]s are present in multiple positions, the RightSpecialValue is the minimum value of j.</p> <p>Write a program to find the maximum special product of any integer in the array.</p> <p>Input: You will receive array of integers as argument to function.</p> <p>Return: Maximum special product of any integer in the array modulo 1000000007.</p> <p>Note: If j does not exist, the LeftSpecialValue and RightSpecialValue are considered to be 0.</p> <p>Constraints 1 &lt;= N &lt;= 10^5 1 &lt;= A[i] &lt;= 10^9</p> </blockquote> <p>Basically if you see the vector as a chart LeftSpecialValue and RightSpecialValue are values around local minima.</p> <p>Here is the algorithm I came up with </p> <pre><code>#include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;stack&gt; #include &lt;iostream&gt; int mult_mod(int i, int j) { return ((i%1000000007) * (j%1000000007)) % 1000000007; } int next_bigger(std::vector&lt;int&gt;&amp; v, std::stack&lt;int&gt;&amp; stack, int i){ while(!stack.empty()){ int j = stack.top(); if (v[j] &lt;= v[i]){ stack.pop(); } else{ stack.push(i); return j; } } stack.push(i); return 0; } void right( std::vector&lt;int&gt;&amp; v, std::vector&lt;int&gt;&amp; r ){ std::stack&lt;int&gt; stack; for(int i = v.size() - 1; i &gt;= 0; --i){ r[i] = next_bigger(v, stack, i); stack.push(i); } } int maxProd( std::vector&lt;int&gt;&amp;&amp; v){ std::vector&lt;int&gt; r(v.size()); right(v, r); int mp = 0; std::stack&lt;int&gt; stack; for(int i = 0; i &lt; v.size(); ++i){ int j = next_bigger(v, stack, i ); int mp_i = mult_mod(j, r[i]); if (mp &lt; mp_i){ mp = mp_i; } } return mp; } int main(){ std::cout &lt;&lt; maxProd({3,2,1,2,3}) &lt;&lt; std::endl; std::cout &lt;&lt; maxProd({1,2,3, 2, 1}) &lt;&lt; std::endl; std::cout &lt;&lt; maxProd({1,2,3, 4, 5}) &lt;&lt; std::endl; std::cout &lt;&lt; maxProd({0, 5, 1, 1, 1, 5}) &lt;&lt; std::endl; std::cout &lt;&lt; maxProd({5, 9, 6, 8, 6, 4, 6, 9, 5, 4, 9}) &lt;&lt; std::endl; std::cout &lt;&lt; maxProd({6, 7, 9, 5, 5, 8 }) &lt;&lt; std::endl; std::cout &lt;&lt; maxProd({1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,0,1}) &lt;&lt; std::endl; //20 } </code></pre> <p>This code is intended to be O(n) in time and space. The algorithm passes all test but </p> <blockquote> <p>might be failing for larger test-cases</p> </blockquote> <p>I believe it is because I am using an additional vector for <code>RightSpecialValue</code>, which means in worst case twice the size of the input memory.</p> <p>Can it be improved to use less space?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T06:44:37.603", "Id": "397546", "Score": "0", "body": "If it fails because it takes too long to compute the right answer, then please add a [tag:time-limit-exceeded] tag. However, if it is computing the wrong answer, then this questi...
[ { "body": "<p>I finally spotted the error in my submission : I was computing the maximum of <code>left-most * right-most mod 1000000007</code> while I should have been computing the maximum of <code>left-most * right-most</code>, then returning its value modulo 1000000007.</p>\n\n<p>In other terms </p>\n\n<pre...
{ "AcceptedAnswerId": "206912", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T06:37:29.047", "Id": "206093", "Score": "1", "Tags": [ "c++", "algorithm", "array", "time-limit-exceeded" ], "Title": "MAXSPPROD linear algorithm" }
206093
<p>I have a notification system. If someone posts a new comment to the topic you commented, then you get a notification. The problem is, that the code is looking awful. First I count how many notifications you have, so I can write it into the "notification bell", then I write the same code again, but this time to output the result (xy commented x hours ago...)</p> <p>My main concern is that the same queries are running twice (or even more), and I'm asking if there is a way to run them only once?</p> <p>So here's my code (well, my queries are bad too, because it's sorted by last comment date from me, instead of the last time someone commented, so the notifications area time order is also bad (it can happen, that a comment from 1 day ago is the first notification, when a comment from 1 hour ago is behind it)):</p> <pre><code>$sql = "SELECT p1.* FROM comment p1 INNER JOIN (SELECT max(date) MaxPostDate, user_id FROM comment WHERE user_id='$me' and deleted=0 GROUP BY topic_id, picture_id, news_id) p2 ON p1.user_id = p2.user_id AND p1.date = p2.MaxPostDate WHERE p1.user_id='$me' and deleted=0 ORDER BY p1.date DESC " $comment_query = sql_query($conn, $sql); if(sql_num($comment_query)!=0) { while ($comment = sql_fetch($comment_query)) { if($comment['topic_id']!=0) { $current_forum = sql_fetch(sql_query($conn, "SELECT url, name FROM forum WHERE id='".$comment['topic_id']."' and deleted=0")); $current_comments = sql_fetch(sql_query($conn, "SELECT count(id) as count, date FROM comment WHERE deleted=0 and topic_id='".$comment['topic_id']."'")); $comment_topic_id = $comment['topic_id']; $comment_id = $comment['id']; $comment2_query = sql_fetch(sql_query($conn,"SELECT count(id) AS cid FROM comment WHERE topic_id=".$comment_topic_id ." and id&lt;".$comment_id ." and deleted=0 ")); $result = $comment2_query['cid'] + 1; if($comment['seen']=='0000-00-00 00:00:00') { $unread = $current_comments[0] - $result; if($unread!=0) { if((!empty($_GET['p'])) and $_GET['p']=='forum' and $_GET['x']==$current_forum['url']) //If I'm at the specific url (I'm watching the new comments, so update it) { $now = date('Y-m-d H:i:s'); sql_query($conn,"UPDATE comment SET seen='$now' WHERE user_id='$me' AND id='$comment_id' AND topic_id='.$comment_topic_id.' "); } else //increase number to add it to noficiation bell { $count++; $forum_notif++; } } else { $last_time_seen = $comment['seen']; $count_comments = sql_fetch(sql_query($conn,"SELECT count(id) AS cid FROM comment WHERE topic_id=".$comment_topic_id." and deleted=0 and date&gt;'.$last_time_seen.' ")); if($count_comments['cid']!=0) { if((!empty($_GET['p'])) and $_GET['p']=='forum' and $_GET['x']==$current_forum['url']) { $now = date('Y-m-d H:i:s'); sql_query($conn,"UPDATE comment SET seen='$now' WHERE user_id='$me' AND id='$comment_id' AND topic_id='.$comment_topic_id.' "); } else { $count++; $forum_notif++; } } } } elseif($comment['picture_id']!=0) { //same thing again for a different type of forum... </code></pre> <p>Here's the one for outputting the "xy commented x hours ago..." part:</p> <pre><code>$sql = "SELECT p1.* FROM comment p1 INNER JOIN (SELECT max(date) MaxPostDate, user_id FROM comment WHERE user_id='$me' and deleted=0 GROUP BY topic_id, picture_id, news_id) p2 ON p1.user_id = p2.user_id AND p1.date = p2.MaxPostDate WHERE p1.user_id='$me' and deleted=0 ORDER BY p1.date DESC " $comment_query = sql_query($conn, $sql); if(sql_num($comment_query)!=0) { while ($comment = sql_fetch($comment_query)) { if($comment['topic_id']!=0) { $current_forum = sql_fetch(sql_query($conn, "SELECT url, name FROM forum WHERE id='".$comment['topic_id']."' and deleted=0")); $current_comments = sql_fetch(sql_query($conn, "SELECT count(id) as count, date FROM comment WHERE deleted=0 and topic_id='".$comment['topic_id']."'")); $comment_topic_id = $comment['topic_id']; $comment_id = $comment['id']; $comment2_query = sql_fetch(sql_query($conn,"SELECT count(id) AS cid FROM comment WHERE topic_id=".$comment_topic_id ." and id&lt;".$comment_id ." and deleted=0 ")); $result = $comment2_query['cid'] + 1; $get_date = sql_fetch(sql_query($conn,"SELECT date FROM comment WHERE topic_id=".$comment_topic_id." ORDER BY id DESC")); if($comment['seen']=='0000-00-00 00:00:00') { $unread = $current_comments[0] - $result; if($unread!=0) { $new_number = $current_comments[0] - ($unread-1); if($current_comments[0]&lt;=20) //20 comment appears on a page { ?&gt; &lt;p class="notif"&gt; &lt;a class="comments" href="/forum/ &lt;?php print $current_forum['url']; ?&gt;#&lt;?php print $new_number; ?&gt;"&gt; &lt;?php print $unread; ?&gt; new comments at &lt;?php print ''.$current_forum['name'].' forum topic! &lt;span class="when_notif"&gt;'.since_time($get_date['date']).'&lt;/span&gt; &lt;/a&gt; &lt;/p&gt;'; //x hours ago } else { $limitation = 20; $maxpage_comment = ceil($new_number / $limitation);//get page number ?&gt; &lt;p class="notif"&gt; &lt;a class="comments" href="/forum/&lt;?php print $current_forum['url']; ?&gt; /&lt;?php print $maxpage_comment; ?&gt;#&lt;?php print $new_number; ?&gt;"&gt; &lt;?php print $unread; ?&gt; new comments at &lt;?php print ''.$current_forum['name'].' forum topic! &lt;span class="when_notif"&gt;'.since_time($get_date['date']).'&lt;/span&gt; &lt;/a&gt; &lt;/p&gt;'; } } } else { $last_time_seen = $comment['seen']; $count_comments = sql_fetch(sql_query($conn,"SELECT count(id) AS cid FROM comment WHERE topic_id=".$comment_topic_id." and deleted=0 and date&gt;'.$last_time_seen.' ")); if($count_comments['cid']!=0) { $new_number = $current_comments[0] - ($count_comments['cid']-1); if($current_comments[0]&lt;=20) { ?&gt; &lt;p class="notif"&gt; &lt;a class="comments" href="/forum/ &lt;?php print $current_forum['url']; ?&gt;#&lt;?php print $new_number; ?&gt;"&gt; &lt;?php print $count_comments['cid']; ?&gt; new comments at &lt;?php print ''.$current_forum['name'].' forum topic! &lt;span class="when_notif"&gt;'.since_time($get_date['date']).'&lt;/span&gt; &lt;/a&gt; &lt;/p&gt;'; } else { $limitation = 20; $maxpage_comment = ceil($new_number / $limitation); ?&gt; &lt;p class="notif"&gt; &lt;a class="comments" href="/forum/&lt;?php print $current_forum['url']; ?&gt; /&lt;?php print $maxpage_comment; ?&gt;#&lt;?php print $new_number; ?&gt;"&gt; &lt;?php print $count_comments['cid']; ?&gt; newcomments at &lt;?php print ''.$current_forum['name'].' forum topic! &lt;span class="when_notif"&gt;'.since_time($get_date['date']).'&lt;/span&gt; &lt;/a&gt; &lt;/p&gt;'; } } } } elseif($comment['picture_id']!=0) { //same thing again for a different type of forum... </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T08:25:59.257", "Id": "397556", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply stat...
[ { "body": "<p>I'd start by splitting out the logic into multiple functions so that the query result loop isn't also responsible for defining all the execution logic that happens within. It instead will call functions where that is defined.</p>\n\n<p>E.g. \n </p>\n\n<pre><code>$current_forum = sql_fetch(sql_q...
{ "AcceptedAnswerId": "206186", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T08:14:50.257", "Id": "206095", "Score": "1", "Tags": [ "php" ], "Title": "Notification system same code running twice, simplify it" }
206095
<p>Can random string generation be faster in Java?</p> <p>Here is my current code</p> <pre><code>import java.util.ArrayList; import java.util.List; public class FastestStringGeneration { private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final char[] ch = ALPHA_NUMERIC_STRING.toCharArray(); private static final java.util.concurrent.ThreadLocalRandom random = java.util.concurrent.ThreadLocalRandom.current(); public static void main(String[] java) { // warmup code String[] warmUp = new String[10000]; for (int j=0; j&lt;10000; j++){ warmUp[j] = getAlphaNumeric(1024); } // real code begins int numIterations = 1000000; String[] randomStrings = new String[numIterations]; long start = System.currentTimeMillis(); for(int i=0; i&lt;numIterations; i++){ randomStrings[i] = getAlphaNumeric(1024); } System.out.println(System.currentTimeMillis()-start); System.out.println(randomStrings.length); } public static String getAlphaNumeric(int len) { char[] c = new char[len]; for (int i = 0; i &lt; len; i++) { c[i] = ch[random.nextInt(ch.length)]; } return new String(c); } } </code></pre> <p>The total time it takes to generate 1 million random strings is about ~ 5.9 seconds. Can it be faster? </p> <p>I was using <code>java.util.Random</code> but when I changed to <code>java.util.concurrent.ThreadLocalRandom</code> according to comments below I got the most performance improvement!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T08:45:31.693", "Id": "397560", "Score": "0", "body": "I was trying in other languages and was able to accomplish in ~5 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T08:45:46.040", "Id":...
[ { "body": "<p>If the length is always identical you can save 1000000 calls to new().</p>\n\n<p>Because <code>new String(char[])</code> uses <code>Arrays.copyOf()</code>, you don't need a new char[] in every loop.</p>\n\n<pre><code>private static int ourlen = 1024;\nprivate static char[] chars = new char[ourlen]...
{ "AcceptedAnswerId": null, "CommentCount": "22", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T08:41:00.413", "Id": "206097", "Score": "2", "Tags": [ "java", "performance", "strings", "random" ], "Title": "Random string generation in Java" }
206097
<p>After I couldn't find any matching algorithm that would Interlace arrays I wrote this generic static function to combine arrays with variable segment sizes with n number of arrays. The theory of this algorithm is that one would specify the indices in order of the params arrays with a number to indicate the segment lengths. So for example:</p> <pre><code>indices = {2,3} arrayA = {a,b,c,d,e,f} arrayB = {1,2,3,4,5,6,7,8,9} result = {a,b,1,2,3, c,d,4,5,6, e,f,7,8,9} </code></pre> <p>The reason behind this Interlace algorithm is so that I could create vertex buffer objects friendly for opengl where segments of an array can mean different things, for example first three values of an element are x,y,z and the second three values are r,g,b.</p> <pre><code> public static T[] Interlace&lt;T&gt;(uint[] indices, params T[][] arrays) { if (arrays.Length == 0) throw new ArgumentException("No arrays"); if (arrays.Length == 1) return arrays[0]; if(indices.Length != arrays.Length) throw new ArgumentException("Index count is not same as array count"); uint componentSize = 0; foreach (uint i in indices) { componentSize += i; } uint elements = (uint)arrays[0].Length / indices[0]; for (int i = 1; i &lt; arrays.Length; ++i) { uint numElements = (uint)arrays[i].Length / indices[i]; if (numElements != elements) throw new ArgumentException("Specified arrays are not consistent sizes"); elements = numElements; } T[] result = new T[elements * componentSize]; for (uint i = 0; i &lt; elements; ++i) { uint offset = 0; for (uint j = 0; j &lt; indices.Length; ++j) { offset += j == 0 ? (i * componentSize) : indices[j-1]; for (uint k = 0; k &lt; indices[j]; ++k) { result[k + offset] = arrays[j][k + (i * indices[j])]; } } } return result; } </code></pre> <p>Does this algoryithm seam over-complicated to achieve this goal?</p> <p>Have I oversighted a simpler and more obvious approach?</p> <p>Is there a better name I could use for the indices parameter?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T09:26:44.533", "Id": "397568", "Score": "0", "body": "Consider where you can use standard algorithms. For example componentSize is just an array sum: does this work? https://stackoverflow.com/a/2419351/1688786" }, { "Content...
[ { "body": "<p>Note that your code for checking that the inputs are 'consistent' involves rounding, so you might ignore the last few elements, and could obscure an insidious bug (e.g. off-by-one) somewhere else:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>uint numElements = (uint)arrays[i].Lengt...
{ "AcceptedAnswerId": "206103", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T09:07:55.157", "Id": "206099", "Score": "10", "Tags": [ "c#", "array" ], "Title": "Array Interlacing" }
206099
<p>I have a function that adds to a <code>std::wstring</code> some filler characters. The user gives a single filler character. They can also optionally given an initial filler sequence (<code>std::wstring</code>) and an optional final filler sequence (<code>std::wstring</code>) that start and end the padding. These will only be added however if they fit inside the padded length specified by the user.</p> <pre><code>static std::wstring fillWString( const std::wstring &amp;stringToFill, size_t fillLength, const wchar_t fillChar = L' ', const std::wstring &amp;initialFill = L"", const std::wstring &amp;endFill = L"") { const size_t originalStringLength = stringToFill.size(); if (fillLength &lt;= originalStringLength) { return stringToFill; } std::wstring result(stringToFill); result.resize(fillLength, fillChar); if (originalStringLength + initialFill.size() &lt;= fillLength) { result.replace(originalStringLength, initialFill.size(), initialFill, 0u); if (originalStringLength + initialFill.size() + endFill.size() &lt;= fillLength) { result.replace(fillLength - endFill.size(), endFill.size(), endFill, 0u); } } return result; } </code></pre> <p>Here is some output:</p> <pre class="lang-none prettyprint-override"><code>Analyzed folder: .... \Path\To\Some\Folder\ Time step: .......... 0.007045000 Out Flow: ........... 1.2460679423999952 In Flow: ............ -1.2461052960000008 </code></pre> <p>where each line was generated using</p> <pre><code>fillWString(L"string", 22, '.', L" ", L" ") &lt;&lt; value; </code></pre> <p>Specifically, I was wondering what sort of tips you guys might give to improve this. Also, I was just wondering if copy-elision is guaranteed to occur here if the string is indeed padded?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T11:35:22.523", "Id": "397585", "Score": "0", "body": "Named-value return elision isn't *required* by the standard, but it would be a poor implementation that didn't bother, at least when optimizing." }, { "ContentLicense": "...
[ { "body": "<p>The point where the parameters stop and the function-body begins isn't easy to see.<br>\nEither indent more, or better consider changing to <a href=\"http://wiki.c2.com/?IndentationOfParameters\" rel=\"noreferrer\">what c2-wiki calls form 6</a>.</p>\n\n<p>You are allocating way too much when passi...
{ "AcceptedAnswerId": "206106", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T09:54:25.887", "Id": "206102", "Score": "4", "Tags": [ "c++", "strings", "formatting" ], "Title": "Fancy padding of wide strings" }
206102
<p>Problem: Given a vector of about 40 values <code>m</code> with normal error <code>sd</code> compute the weighted average of the values weighted by the chance that they are the maximum.</p> <p>I have come up with 2 different approaches to solve this. The first is numerical integration, the second is monte-carlo sampling.</p> <pre><code>import numpy as np from scipy import integrate from scipy.stats import norm m = np.arange(-1,1,.03) sd = np.ones(len(m))*.12 def integ(): n = len(m) dx = .05 ts = np.arange(-2, 2, dx) cdfs = np.ones(len(ts)) for i in range(n): cdfs *= norm.cdf(ts, m[i], sd[i]) def func(i, x): return norm.pdf(x, m[i], sd[i]) / norm.cdf(x, m[i] , sd[i]) * cdfs ans = np.zeros(n) for i in range(n): ys = func(i, ts) ans[i] = integrate.simps(ys, dx=dx) ans *= m return ans def monte(): nn=10000 a = np.random.normal(size=(len(m),nn))*sd[:,None]+m[:,None] vals = (a==a.max(axis=0)).sum(axis=1)/nn vals *= m return vals </code></pre> <p>Both of these solutions work, but they are in the range of <code>1/1_000</code> of a second rather than the <code>1/1_000_000</code> of a second I am looking for.</p> <p>This code is a prototype that I will eventually be writing in c++, but I want to make sure that this function is possible to calculate quickly enough for the change to be worth it, so I really don't care about formatting or readability, just performance.</p>
[]
[ { "body": "<p>Possible improvements:</p>\n\n<ol>\n<li><p>Calculate for less than 40 variables. Take top 5 and calculate the probabilities for them. The Monte-Carlo shows that the probabilities go down fast. And reducing the number of variables will significantly reduce complexity.</p></li>\n<li><p>Only take var...
{ "AcceptedAnswerId": "206446", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T11:50:37.873", "Id": "206105", "Score": "2", "Tags": [ "python", "performance", "comparative-review", "numpy", "statistics" ], "Title": "Speed up weighted average for Leela Chess Zero" }
206105
<p>I'm building a script where I pass in a text file of hostnames, and a text file of commands and each command will then be run against each host.</p> <p>To prevent this getting out of hand I'm also passing in a maximum thread count and trying to manage a maximum number of workers at any one time.</p> <p>The code I would like feedback on is as follows:</p> <h1>main.py</h1> <pre><code>#!/usr/bin/python3 import sys from lib.core.input import InputParser, InputHelper from lib.core.output import OutputHelper, Level from lib.core.threader import Pool def build_queue(arguments, output): queue = list() for target in InputHelper.process_targets(arguments): for command in InputHelper.process_commands(arguments): output.terminal(Level.VERBOSE, target, command, "Added to Queue") queue.append(command) return queue def main(): parser = InputParser() arguments = parser.parse(sys.argv[1:]) output = OutputHelper(arguments) output.print_banner() pool = Pool(arguments.threads, build_queue(arguments, output), arguments.timeout, output) pool.run() if __name__ == "__main__": main() </code></pre> <h1>threader.py</h1> <pre><code>import threading import os class Worker(object): def __init__(self, pool): self.pool = pool def __call__(self, task, output, timeout): self.run_task(task) self.pool.workers.append(self) @staticmethod def run_task(task): os.system(task) class Pool(object): def __init__(self, max_workers, queue, timeout, output): self.queue = queue self.workers = [Worker(self) for w in range(max_workers)] self.timeout = timeout self.output = output def run(self): while True: # make sure resources are available if not self.workers: continue # check if the queue is empty if not self.queue: break # get a worker worker = self.workers.pop(0) # get task from queue task = self.queue.pop(0) # run thread = threading.Thread(target=worker, args=(task, self.output, self.timeout)) thread.start() </code></pre> <p>Essentially, I don't know what I don't know. There's likely some basic gaps in my knowledge here, and I'd love feedback and examples that help me to bridge those gaps. Any and all help is very welcome, and very appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T15:46:27.397", "Id": "397625", "Score": "0", "body": "Are you doing this for the fun of learning things or are you planning on using this on real systems to automate executing the same commands on several hosts?" }, { "Conte...
[ { "body": "<h3>Prefer generators instead of lists</h3>\n\n<p><code>build_queue</code> creates a list of tasks up front.\nIt's unnecessary to store all task details in memory up front.\nYou could use a generator instead, and <code>yield</code> the task parameters.\nThat will minimize the memory use,\nby generati...
{ "AcceptedAnswerId": "206537", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T13:25:47.293", "Id": "206109", "Score": "9", "Tags": [ "python", "python-3.x", "multiprocessing" ], "Title": "Python worker pattern for multithreading" }
206109
<p>I have a set of 1 million points in 128-dimensional space. Among all trillion pairs of the points in the set, I need to get a subset of 100 million pairs whose cosine distances are less than that of every pair outside the subset.</p> <p>I tried measuring cosine distances of all trillion pairs, sort them and get first 100 million of sorted pairs. But this program is estimated to take few years in single thread.</p> <pre><code>from scipy.spatial.distance import cosine points = load_points_list() # List of points, where each point is tuple of 128 floats M = len(points) # 1 million points cosine_distances, pairs = [], [] for i in range(M): for j in range(M): cosine_distances.append(cosine(points[i], points[j])) pairs.append((i, j)) # Sort pairs based on cosine distances cosine_distances, pairs = (list(s) for s in zip(*sorted(zip(cosine_similarities, pairs_indices)))) top_100_million_closest_pairs = pairs[:100000000] </code></pre> <p>Is there a more efficient algorithm or GPU-enabled acceleration for a problem at this scale?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T15:54:55.250", "Id": "397626", "Score": "0", "body": "Didn´t find anything implemented, but there are several [papers](https://pdfs.semanticscholar.org/e968/38bde759b9dfa1f27436fb8cbe14ddf29b61.pdf) on the subject" }, { "Con...
[ { "body": "<p>First, cut your work load in half. You only need to consider pairs where <code>i &lt; j</code>, so:</p>\n\n<pre><code>for i in range(M-1):\n for j in range(i+1, M):\n # ...\n</code></pre>\n\n<p>If you actually need both <code>(i, j)</code> and <code>(j, i)</code>, then you only need the...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T15:17:27.233", "Id": "206117", "Score": "2", "Tags": [ "python", "algorithm", "time-limit-exceeded", "clustering" ], "Title": "Top k closest pairs in a set of million 128-dimensional points" }
206117
<p>To learn the low-level API of Tensorflow I am trying to implement some traditional machine learning algorithms. The following Python script implements <a href="https://en.wikipedia.org/wiki/Principal_component_analysis" rel="nofollow noreferrer">Principal Component Analysis</a> using gradient descent. It finds component weights that maximize the variance of each component. The weights are constrained to be orthonormal, as required by the PCA definition.</p> <p>The results are consistent with Scikit-Learn's PCA implementation, so I assume the code works correctly.</p> <p>Since these are my first baby steps with Tensorflow, I doubt that I used the API in an idiomatic way. How can my use of Tensorflow be improved?</p> <pre><code>import numpy as np import tensorflow as tf import matplotlib.pyplot as plt x_data = np.random.randn(100, 3) @ [[0, 0, 1], [1, -2, 0], [0, 1, 0]] # data set n_components = 3 # number of desired components def proj(v, u): '''project vector v on vector u''' return u * (tf.reduce_sum(u * v) / tf.reduce_sum(u**2)) def orthonormalize(w): '''orthonormalize vectors basis w''' n = w.shape[1] ortho_vecs = [] for i in range(n): next_vector = w[:, i] for vec in ortho_vecs: next_vector -= proj(w[:, i], vec) ortho_vecs.append(next_vector) u = tf.stack(ortho_vecs, axis=-1) return u / tf.reduce_sum(u**2, axis=-2)**0.5 # normalize basis vectors # reset tensorflow (because I run this in a persisting Jupyter kernel) tf.reset_default_graph() # placeholder tensor for input data x = tf.placeholder(tf.float32, shape=[None, x_data.shape[-1]]) # PCA is one densely connected layer with no biases and linear activation function. # Each unit corresponds to one component, and components are constrained to be # orthonormal. y = tf.layers.dense(x, units=n_components, use_bias=False, kernel_constraint=orthonormalize) # mean and variance of the resulting components mean_y = tf.reduce_mean(y, axis=-2) var_y = tf.reduce_mean((y - mean_y)**2, axis=-2) # minimize the sum of component variances # This seems not only to converge to the correct components, but even sorts # the components from largest to smallest. I don't know why... possibly has to # do with the orthogonalization where the first component is unconstrained and # each successive component is more and more constrained... optimizer = tf.train.GradientDescentOptimizer(0.001) train = optimizer.minimize(-tf.reduce_sum(var_y)) with tf.Session() as sess: # initialize weights init = tf.global_variables_initializer() sess.run(init) # iterate training train_var = [] train_weights = [] for _ in range(1000): # stochastic gradient descent (need at least two samples for computing # the variance... call it micro-batch?) x_batch = x_data[np.random.randint(x_data.shape[0], size=2)] #x_batch = x_data # full data set _, v, w = sess.run([train, var_y] + tf.trainable_variables(), feed_dict={x: x_batch}) train_weights.append(w.ravel()) train_var.append(np.var(x_data @ w, axis=0)) # plot convergence of weights and variances plt.subplot(2, 1, 1) plt.plot(train_var) plt.subplot(2, 1, 2) plt.plot(train_weights) writer = tf.summary.FileWriter("test", sess.graph) # print final component weights print(sess.run(tf.trainable_variables())) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T15:25:53.747", "Id": "206118", "Score": "2", "Tags": [ "python", "machine-learning", "tensorflow" ], "Title": "Principal Component Analysis in Tensorflow" }
206118
<p>I wrote this snippet:</p> <pre><code>template &lt;typename ContainerT&gt; class ReverseIterator { public: ReverseIterator(ContainerT&amp; iContainer) : m_container{iContainer} { } typename ContainerT::reverse_iterator begin() { return m_container.rbegin(); } typename ContainerT::reverse_iterator end() { return m_container.rend(); } private: ContainerT&amp; m_container; }; template &lt;typename ContainerT&gt; auto Reverse(ContainerT&amp; iContainer) { return ReverseIterator&lt;ContainerT&gt;(iContainer); } </code></pre> <p>To be able to do something like this:</p> <pre><code>std::vector&lt;int&gt; myList{1, 2, 3}; for (auto&amp; itr : Reverse(myList)) { ++itr; } </code></pre> <p>First I'd like a feedback up to this point.</p> <p>Then, I'd like to be able to write something like this:</p> <pre><code>for (auto itr : Reverse(std::vector&lt;int&gt;{1, 2, 3})) { std::cout &lt;&lt; itr &lt;&lt; " "; } </code></pre> <p>Without having a separate and near identical implementation of <code>ConstReverse</code>.</p> <p>I thought about making everything with forwarding references but for some reason that didn't work out very well and I'm not exactly sure where I was mistaken. Could someone show me how it could be done?</p>
[]
[ { "body": "<p>Good clear template code - well done!</p>\n\n<p>I'd consider changing the name, as the class itself isn't an iterator, it's an iterator pair, or <em>range</em>, that wraps a <em>container</em> and provides a reversed <em>view</em> of it.</p>\n\n<p>Constructor should be <code>explicit</code>.</p>\n...
{ "AcceptedAnswerId": "206122", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T15:41:11.517", "Id": "206119", "Score": "4", "Tags": [ "c++", "c++11", "iterator" ], "Title": "Reverse C++11 range-based for loop" }
206119
<p>I'm a beginner with Rails and am trying to figure out how to keep my controllers clean and thin, and how to work with service objects. I am building an internal tool to manage our SaaS customers, and the specific feature I'm building is to allow admins to change a customer's plan.</p> <p>In accounts_controller.rb, I have the following method:</p> <pre><code>def change_plan account = Account.find(params[:id]) old_plan = account.plan new_plan = Plan.find(params[:account][:plan_id]) account.change_plan!(params[:account][:plan_id]) SlackService.new.plan_change(current_user, account, old_plan, new_plan).deliver redirect_to action: "show", id: params[:id] end </code></pre> <p>My first question is around the lines 2 and 3 of the method. Is there some place I should be moving this logic? Some sort of SlackService container object? Or should the SlackService method itself be handling the retrieval of the old_plan and new_plan? I realize this is fairly trivial but would love to build it properly.</p> <p>Here's the code for the SlackService itself, heavily inspired by <a href="https://neil.bar/a-really-simple-slack-integration-in-rails-eeae365d5f38" rel="nofollow noreferrer">this article</a>:</p> <pre><code>require 'net/http' class SlackService NAME_AND_ICON = { username: 'Dashboard', icon_emoji: ':bat:' } SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/###/###/###" SLACK_WEBHOOK_CHANNEL = Rails.env.production? ? "###" : "###" def initialize(channel = SLACK_WEBHOOK_CHANNEL) @uri = URI(SLACK_WEBHOOK_URL) @channel = channel end def plan_change(user, account, old_plan, new_plan) params = { attachments: [ { author_name: "#{user.first_name} #{user.last_name}", text: "Account: #{account.name} (#{account.id})", title: 'Dashboard Plan Change', fields: [ { title: 'Old Plan', value: "#{old_plan.name} (#{ActionController::Base.helpers.number_to_currency(old_plan.price)})", short: true }, { title: 'New Plan', value: "#{new_plan.name} ($#{ActionController::Base.helpers.number_to_currency(new_plan.price)})", short: true }, ] } ] } @params = generate_payload(params) self end def deliver begin Net::HTTP.post_form(@uri, @params) rescue =&gt; e Rails.logger.error("SlackService: Error when sending: #{e.message}") end end private def generate_payload(params) { payload: NAME_AND_ICON .merge(channel: @channel) .merge(params).to_json } end end </code></pre> <ol> <li>It seemed that I had to <code>require net/http</code> here in the service, but wasn't sure if that was the proper place for it.</li> <li>I think the <code>SLACK_WEBHOOK_URL</code> and <code>SLACK_WEBHOOK_CHANNEL</code> constants should be defined here.</li> <li>I see many examples of services where the methods are class level, but it seemed to make sense to keep it instance level so you can define the channel on instantiation.</li> <li>Tying in with the above, the plan_change method accepts 4 params, but not sure if there's a cleaner way.</li> <li>Wasn't sure if my approach to loading the NumberHelper is correct.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T22:05:32.307", "Id": "397670", "Score": "0", "body": "Welcome to Code Review, your post looks good, hope you get some good reviews!" } ]
[ { "body": "<pre><code>def change_plan\n account = Account.find(params[:id])\n\n old_plan = account.plan\n new_plan = Plan.find(params[:account][:plan_id])\n\n # maybe this method ought to return the new_plan, since it's basically repeating the line above\n account.change_plan!(params[:account][:plan_id])\n...
{ "AcceptedAnswerId": "206141", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T18:18:03.040", "Id": "206126", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "api", "controller" ], "Title": "Rails thin controller method to change account plan and fire slack message via a service object" }
206126
<p>I'm programming on an 8-bit Z80 embedded system, and encountered a problem. The program needs to render some pixels to the screen. The color is stored as RGB565 format as a 16-bit unsigned integer, but the system color is encoded as BGR565, so I've devised the following code to swap the first and last 5 bits in a <code>uint16_t</code>.</p> <p>Note that <code>flash</code> is <code>uint8_t *</code>, pointed to the flash memory, and each cell is seen as <code>uint8_t</code>.</p> <pre><code>/* read lower 8-bit */ uint16_t color = flash[idx]; /* read higher 8 bits */ color |= ((flash[idx + 1]) &lt;&lt; 8); /* * This converts RGB565 to BGR565 by swapping the first/last five bits. * For the last five bits, we extract and bitshift it to the beginning, * and for the first five bits, we extract and bitstift it to the end. * Then, we clear the original first and last five bits, and apply the * bitshifted version on it to swap them. */ uint16_t tmp = (color &amp; 0x001F) &lt;&lt; 11; tmp |= (color &amp; 0xF800) &gt;&gt; 11; color &amp;= 0xFFE0 &amp; 0x07FF; /* at least the compiler can optimize this as 0x07e0 */ color |= tmp; </code></pre> <p>If I'm programming with a standard compiler, like GCC or Clang, I would be just happy about my solution. But this embedded platform only supports <a href="https://retrocomputing.stackexchange.com/questions/6095/why-do-c-to-z80-compilers-produce-poor-code">relatively primitive compilers without advanced optimization</a> techniques to remove duplicate computations.</p> <p>In fact, the best code optimization to this problem is "no code", just make the stored format to be consistent with the system format. But using it as a chance of learning, I'm curious to know if there is a faster way to do the computation above in pure C, especially when we're dealing with a particularly slow machine, like a Z80.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T19:18:07.043", "Id": "397656", "Score": "0", "body": "Which compiler do you use? SDCC?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T19:27:28.253", "Id": "397658", "Score": "1", "body": ...
[ { "body": "<p>Bit shifting and masking is annoying. I'm counting 9 and/or/shift-operations in your implementation.</p>\n\n<p>If you've got 1024 bytes of free space available, here is an implementation with only 1 or-operation, but with 2 extra memory lookups:</p>\n\n<p>First, construct the conversion tables. ...
{ "AcceptedAnswerId": "206170", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T18:38:17.970", "Id": "206127", "Score": "6", "Tags": [ "performance", "c", "bitwise", "embedded" ], "Title": "Efficiently swapping the first and last five bits in an unsigned 16-bit integer in C" }
206127
<p>I got a word count assignment and the requirements are shown below:</p> <blockquote> <h3>INPUT</h3> <p>The input contains words in several lines and in each line there could be more than one word. The input only contains English words, separated by space or line breaks. Words are case-sensitive.</p> <h3>OUTPUT</h3> <p>Print the words in alphabetic order with the corresponding appearance count in the text. For each word, please print the result in a single line (separate the word and the number with space).</p> </blockquote> <h3>Sample Input:</h3> <pre class="lang-none prettyprint-override"><code>Computer system computer design algorithm design and analysis quantum computer computer science Department </code></pre> <h3>Sample Output:</h3> <pre class="lang-none prettyprint-override"><code>Computer 1 algorithm 1 analysis 1 and 1 computer 3 department 1 design 2 quantum 1 science 1 system 1 </code></pre> <p>I tried something shown below and actually got the same output as the sample but still got marked as wrong answer by the assignment judge system.<br> Is there anything I did wrong?</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; using namespace std; int main() { string whole; string line; string word; do { getline(cin, line); whole += line + ' '; } while (!line.empty()); if (!whole.empty()) { istringstream iss(whole); vector&lt;string&gt; results((istream_iterator&lt;string&gt;(iss)), istream_iterator&lt;string&gt;()); int count = 1; int size = results.size(); if (size == 1) cout &lt;&lt; results[0] &lt;&lt; ' ' &lt;&lt; count; else { sort(results.begin(), results.end()); for (int j = 0; j &lt; size; j++) { if (j != size - 1) { if (results[j] != results[j + 1]) { string word = results[j]; cout &lt;&lt; word &lt;&lt; ' ' &lt;&lt; count &lt;&lt; endl; count = 1; } else if (results[j] == results[j + 1]) count++; } else if (j == size - 1) { if (results[j] != results[j - 1]) { string word = results[j]; cout &lt;&lt; word &lt;&lt; ' ' &lt;&lt; count &lt;&lt; endl; } else if (results[j] == results[j - 1]) cout &lt;&lt; results[j] &lt;&lt; ' ' &lt;&lt; count &lt;&lt; endl; } } } } return 0; } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Kudos for proper formatting. And for including the headers you use, but no more.</p></li>\n<li><p>Don't use <code>using namespace std;</code>. That namespace is <strong>not</strong> designed to be imported wholesale, thus doing so can have surprising and unpredictable results, which aren...
{ "AcceptedAnswerId": "206139", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T20:56:10.537", "Id": "206134", "Score": "5", "Tags": [ "c++", "strings", "sorting" ], "Title": "Computing word-frequency-table" }
206134
<p>I made this little game to test if my Nokia 5110 screen can handle games. As in handle many frames per second/game loops.</p> <p>I am using a library made for this screen called <strong>Adafruit_Nokia_LCD</strong></p> <p>These are the imports for some context, if needed:</p> <pre><code>import Adafruit_Nokia_LCD as LCD import Adafruit_GPIO.SPI as SPI import threading from PIL import Image from PIL import ImageDraw from PIL import ImageFont </code></pre> <p>This is how I load images. I have some black and white images, use a binary converter to turn them into a multiline string. These are some tamagotchi sprites for example:</p> <pre><code>tam1 = """00000000000000111100000 00001111000000111110000 00001111100001111110000 00011111100001111110000 00011111111111111111000 00011111111111111111000 00011111111111111111000 00111111111111111111000 00111111111111111111100 01001111000000011111110 01100000011110000000010 10110000111101000000001 10110000111110100000001 10110000111110100000001 10110000111110100000001 01110000011100100000001 01100000001111000000010 00100101000000000000010 00010011000000000000100 00001100000000000011110 00000011111111111100001 00000100000000000000001 00001000000000000011110 00001001000000000010000 00000111000000000010000 00000001000000000011100 00000010000000000100010 00000100000111111000010 00000100011000000111100 00000011100000000000000""" </code></pre> <p>There are two more sprites, for a walking animation called tam2 and tam3</p> <p>I split them into lines:</p> <pre><code>tam1a = tam1.split('\n') tam2a = tam2.split('\n') tam3a = tam3.split('\n') </code></pre> <p>I have a different thread running to capture key input, in which case is spacebar to jump:</p> <pre><code>key = "lol" #uhh this is the keyword for no input pretty much idk i just left it in getch = _Getch() def thread1(): global key lock = threading.Lock() while True: with lock: key = getch() #this is some code that works just like the msvcrt version threading.Thread(target = thread1).start() </code></pre> <p>This is the game loop, after setting some variables:</p> <pre><code>#jump variables dist = 0 #distance off the ground gup = False #isjumping #obstacle variables xx = 0 #x position of the obstacle that loops through the screen #other variables score = 0; ind = 0; #current frame of player, there is 3 extraspeed = 0; #makes the pillar go faster as your score rises while True: #gameloop start draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=255, fill=255) #clears the screen --^ draw.text((0,0),str(score),font=font) #draw score extraspeed = floor(score / 100) #set extraspeed based on score if extraspeed &gt; 10: extraspeed = 10 score += 3 draw.rectangle((xx,32,xx+3,42),outline=0,fill=0) xx = xx + 4 +extraspeed #move the pillar if xx &gt;= 84: xx = -4; if key == ' ': if dist == 0: gup = True key = "lol" #if dist = 0 means its on the ground #the "lol" thing is something I left over for some reason, it means no key pressed else: key = "lol" if gup == True: if dist != 12: #jumps up to 12 pixels off the ground dist += 3 else: gup = False #start falling if reached top else: if dist &gt; 0: dist -= 3 else: dist = 0 #ind is the current animation sprite to draw if ind == 1: i = 12-dist #top left corner of drawn sprite y j = 60 #top left corner of drawn sprite x for line in tam1a: for c in line: if c == '1': draw.point((j,i),fill=0) j+=1 i+=1 j=60 #make same as j at start if ind == 2: i = 12-dist #top left corner of drawn sprite y j = 60 #top left corner of drawn sprite x for line in tam2a: for c in line: if c == '1': draw.point((j,i),fill=0) j+=1 i+=1 j=60 #make same as j at start if ind == 3: i = 12-dist #top left corner of drawn sprite y j = 60 #top left corner of drawn sprite x for line in tam3a: for c in line: if c == '1': draw.point((j,i),fill=0) j+=1 i+=1 j=60 #make same as j at start ind += 1 if ind == 4: ind = 1 #restart the animation draw.line((0,43,83,43),fill=0) draw.line((0,44,83,44),fill=0) #draw some ground if xx &gt;= float(67) and xx&lt;= float(80) and dist &lt;= 7: break #Some simple collision detection # Display image. disp.image(image) #draw everything disp.display() #display everything time.sleep(0.2) #5 frames per second draw.text((40,10),'Hit',font=font) #got here if 'break' occurs disp.image(image) #displays hit, which means game over and loop is broken disp.display() </code></pre> <h2>My problem:</h2> <hr> <p>First of all: This screen is connected through GPIO pins to my Raspberry-Pi. </p> <p>What do you think of this method to load sprites?</p> <p>How about drawing the sprites? I iterate through the string, line by line then character by character and draw the pixels respectively (0 means dont draw, 1 means draw black)</p> <p>Now while this code works, I experience ghosting and image burn in my lcd screen. While I know the nokia 5110 screen wasn't designed to be for a gaming system, can my code be optimized to a point of reducing this ghosting ?</p> <p>What do you think of my key input getting method, is a seperate thread fine for this job?</p> <p><strong>Lastly</strong>, would a different drawing method allow me to reach 60 frames per second or is it just impossible due to the way this screen is manufactured?</p> <hr> <p>Here's a pic. Notice how there is image burn from the last frame? There is only one pillar, and only one frame of the player, but two appear. Is this fixable, or is it because of the screen only?</p> <p><a href="https://i.stack.imgur.com/eET97.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eET97.jpg" alt="Image burn and ghosting"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-29T05:36:49.907", "Id": "398287", "Score": "1", "body": "Although I don't have too much hardware knowledge at this level, I suspect you may be trying to update the screen too frequently. As I recall from using screens like this long ag...
[ { "body": "<p>I noticed that you are updating <code>extraspeed</code> every frame.</p>\n\n<p>An alternative to this could be:</p>\n\n<pre><code>if extraspeed &lt; 10:\n desired_boost = floor(score / 100)\n if desired_boost &lt;= 10:\n extraspeed = desired_boost\n else:\n extraspeed = 10\n...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T21:09:32.640", "Id": "206135", "Score": "8", "Tags": [ "python", "game", "animation", "raspberry-pi" ], "Title": "Runner 1-bit game in Python like the offline chrome dino" }
206135
<p>I am trying to fetch a group of images within a place in Firebase database ref. I then loop through each image adding it to an array which is then supposed to be added to a tableview cell. I was wondering if it could be more concise? am i doing anything unnecessary?</p> <pre><code> func fetchAllUserFristImage() { Database.database().reference().child(“Posts”).observe(.childAdded, with: {(snapshot) in if snapshot.value as? [String: AnyObject] != nil { let user = snapshot.key self.databaseRef = Database.database().reference() let usersPostRef2 = self.databaseRef.child(“Posts”).child(user) usersPostRef2.observe(.value, with: {(postXSnapshots) in if let postDictionary2 = postXSnapshots.value as? [String:AnyObject] { for (p) in postDictionary2 { if let posts = p.value as? [String:AnyObject] { //to get back to where i was delete the below for i for (i) in posts { if let imageUrlString = i.value as? [String:AnyObject], let postUrl = imageUrlString[“image1”] as? String { self.feedArray.append(Post(fetchedImageURL: postUrl)) let imageUrl = URL(string: “\(postUrl)“) do { print(try Data(contentsOf: imageUrl!)) } catch { print(error) } if let imageDataL = try? Data(contentsOf: imageUrl!) { let image = UIImage(data: imageDataL) self.tableData.append(UserImage(image: image!, postNum: p.key, userID: user)) self.tableView.reloadData() } else {print(“users had no posts, was nil”)} } } } } } }) //below shud stay same DispatchQueue.main.async { self.tableView.reloadData() } } }) } </code></pre> <p>Edit: Posibly I could do somthing wit this <code>postsSnap.childSnapshot(forPath: "ImageUrl").childSnapshot(forPath: "image1")</code> to make it more consise Thanks!</p>
[]
[ { "body": "<p>I would start by investigating the cases where you are performing if lets and basic unwrapping. Cases like <code>if snapshot.value as? [String: AnyObject] != nil</code> can be turned into guard statements and provide routes for early termination. This reduces the pyramid by one level for each earl...
{ "AcceptedAnswerId": "206196", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T22:42:28.257", "Id": "206140", "Score": "2", "Tags": [ "swift", "ios", "firebase" ], "Title": "How can this swift, firebase image fetching, function be made more concise?" }
206140
<p>The purpose of this program is to have one thread (main thread) working on I/O reading lines from a file and feeding it to a pool of worker threads whose job is to perform some processing on each line provided. In this case, the processing is running the String.contains() method.</p> <p>Please note that as test input, I used a giant .txt file of English dictionary words found here:</p> <p>Also note that you need to specify the file name of the file to be scanned as the sole command line argument to the program. <em>I am mostly concerned with the threading model and multithreading implementation</em> but welcome other feedback as well; new Rust programmer.</p> <p>spmc crate ver is "0.2.2" for your cargo.toml</p> <pre><code>extern crate spmc; use spmc::channel; use std::thread; use std::io::BufReader; use std::fs::File; use std::io::BufRead; use std::u32::MAX; use std::env; use std::sync::Arc; fn main() -&gt; Result&lt;(), std::io::Error&gt; { let args: Vec&lt;String&gt; = env::args().collect(); match args.len() { 2 =&gt; {}, _ =&gt; return Err(std::io::Error::new(std::io::ErrorKind::Other, "Incorrect number of args")) } let filename = &amp;args[1] as &amp;str; let f1 = File::open(filename)?; let mut br = BufReader::new(f1); let mut vecData: Vec&lt;String&gt; = Vec::new(); let (tx, rx) = spmc::channel(); let mut handles = Vec::new(); for n in 0..5 { let rx = rx.clone(); handles.push(thread::spawn(move || { loop { let mut line_to_check: Arc&lt;String&gt; = rx.recv().unwrap(); if line_to_check.contains("test") { println!("HIT: {}", line_to_check); } } })); } let mut input_str = String::new(); let mut bytes_read: usize = 1; while bytes_read != 0 { let mut is_copy = input_str.clone(); bytes_read = match br.read_line(&amp;mut is_copy) { Ok(num) =&gt; num, Err(err) =&gt; return Err(std::io::Error::new(std::io::ErrorKind::Other, "read_line failed...\n")) }; let str_arc : Arc&lt;String&gt; = Arc::new(is_copy); tx.send(str_arc); } Ok(()) } </code></pre>
[]
[ { "body": "<p>Your code has a number of warnings when compiled under rustc. Those are free code review hints, listen to them!</p>\n\n<p>You use <code>std::io::Error</code> for all your errors. This is dubious since many of your errors are not I/O related. Personally, I like to use <code>Error</code> from the <c...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-23T23:29:12.757", "Id": "206142", "Score": "3", "Tags": [ "multithreading", "concurrency", "queue", "rust" ], "Title": "Rust Task Queue" }
206142
<p>I'm trying to add a new TabItem to a TabControl. The TabItem's content will be set to a new Frame, and the frame holds the actual Page. A new Tabitem is added each time the button is clicked, this is the code I've come up with. </p> <pre><code> // initiates the tab item ang assign dumby values (REMOVE BEFORE RELEASE) TabItem NewSupportTabItem = new TabItem { Header = "Support #123-98A", ToolTip = "New support ticket #123-98A", Name = "NewSupportTabItem"}; // Creates the Frame Frame NewSupportFrame = new Frame(); // Initializes the main Ticket Page SupportTicketDataShell TicketShell = new SupportTicketDataShell(); // Set the content of the Frame to the Page NewSupportFrame.Content = TicketShell; // Sets the content of the TabItem to the Frame NewSupportTabItem.Content = NewSupportFrame; // Adds the TabItem to the TabControl now MainTabControl.Items.Add(NewSupportTabItem); // Focuses the tab NewSupportTabItem.Focus(); </code></pre> <p>As with everything in programming, there's an efficient way, a good way and a bad way, and I think I'm leaning more on the latter side.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T08:30:19.270", "Id": "397693", "Score": "1", "body": "**Lacks concrete context:** Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, h...
[ { "body": "<p>I would suggest learning about <code>Custom Controls</code>. You can take an existing control add whatever properties, etc. you want to the control and every time you initialize a new one, all your defaults will be present. Here's a reasonably good tutorial for <a href=\"https://www.tutorialspoi...
{ "AcceptedAnswerId": "206150", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T01:22:19.560", "Id": "206149", "Score": "-2", "Tags": [ "c#", ".net", "xaml" ], "Title": "Add new TabItem to a TabControl using Click Event" }
206149
<p>This is a question about some code I've written that works, but I'm not sure it's <em>good</em> code.</p> <p>I would like to get some comments on this or if possible hints to build a better solution.</p> <p><strong>Background:</strong></p> <p>This is a small program to calculate some data, connect these to a participant and store it in a JSON file.</p> <p>Here the already working solution:</p> <pre><code>menu_entries = ( ('Order Pizza', order_pizza), ('Order Burger', order_burger), ('Order Coke', order_coke, '0.5') ) def menu(menu_title, menu_entries): while True: mpoint = 0 print(menu_title) # Build the menu entries plus one to close for entry in menu_entries: mpoint += 1 print(str(mpoint) + '.', entry[0]) print(str(mpoint + 1) + '.', 'Ende') # Get value and validate try: task = int(input('&gt; ')) except ValueError: task = None if task is None or task &gt; mpoint + 1: task = None continue if task == mpoint + 1: print('Done') break # Build a function call get_task = menu_entries[task - 1][1] try: get_task(menu_entries[task - 1][2]) except IndexError: get_task() def order_pizza(size=None): if size is None: size = '' print('Bring me a Pizza!') def order_burger(size=None): if size is None: size = '' print('One {} Burger please.'.format(size)) def order_coke(size=None): if size is None: size = '' print('A {} Coke please.'.format(size)) menu('Main menu', menu_entries) </code></pre> <p>As you can see the menu function gets a main title and a tuple of menu entries.</p> <p>In these menu entries I could define the menu point title, a function name and <em>one</em> parameter.</p> <p>All these other functions are only examples and are of no interest (they are ugly, I know).</p> <p>Please have a look, criticize and if possible show me a better solution.</p>
[]
[ { "body": "<p>You have an actual error in your code:</p>\n\n<pre><code>$ python test.py \nTraceback (most recent call last):\n File \"test.py\", line 2, in &lt;module&gt;\n ('Order Pizza', order_pizza),\nNameError: name 'order_pizza' is not defined\n</code></pre>\n\n<p>You need to define <code>menu_entries<...
{ "AcceptedAnswerId": "206167", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T04:40:26.760", "Id": "206155", "Score": "0", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "A flexible menu function in python" }
206155
<p>The logic of the code to build was as follows, two logical conditions; If the value of dictionary element matches in the list of dictionaries return the particular dictionary, and if no element matches in the list of dictionaries; append this new dictionary element. I have written in the below form for example. </p> <pre><code>say_element = {'origin': 10} say_list_two = [{'origin': 8}, {'origin': 9}] if not any(each['origin'] == say_element['origin'] for each in say_list_two): say_list_two.append(say_element) print('not matched') #logic is to append this new dictionary element to the list of dicts for each in say_list_two: if each['origin'] == say_element['origin']: #return each['origin'] #for example print('Matched') #logic is to return that particular dictionary element from the list </code></pre> <p>Could I improve the code in a single for loop statement? Is it O(N^2) + O(N^2) as it is going through two for statements? One in the boolean 'if not any.. for items in list' line of code and another. Could I use itertools/generator method to iterate over list of dictionaries one by one, reduces space complexity alone? Any suggestions please?</p> <p>Edit 1: I have commented out the return statement as it misdirects. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T07:26:25.693", "Id": "397686", "Score": "4", "body": "`SyntaxError: 'return' outside function`. Please provide a working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T08:29:10.827", "Id": ...
[ { "body": "<p>You can use the <code>for else</code> in python to done it in one <code>for</code> loop</p>\n\n<pre><code>for each in say_list_two:\n if each['origin'] == say_element['origin']:\n print('Matched')\n break\nelse:\n say_list_two.append(say_element)\n print('not matched')\n</co...
{ "AcceptedAnswerId": "206162", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T05:12:12.087", "Id": "206156", "Score": "-1", "Tags": [ "python", "performance", "algorithm", "iterator" ], "Title": "Check if an element exists in a list of dictionaries" }
206156
<p>Here is my problem <a href="https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=arrays" rel="noreferrer">statement</a>. An excerpt:</p> <blockquote> <p>You are given an unordered array consisting of consecutive integers <code>∈ [1, 2, 3, ..., n]</code> without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.</p> <p>For example, given the array <code>arr = [7, 1, 3, 2, 4, 5, 6]</code> we perform the following steps:</p> </blockquote> <pre><code>i arr swap (indices) 0 [7, 1, 3, 2, 4, 5, 6] swap (0,3) 1 [2, 1, 3, 7, 4, 5, 6] swap (0,1) 2 [1, 2, 3, 7, 4, 5, 6] swap (3,4) 3 [1, 2, 3, 4, 7, 5, 6] swap (4,5) 4 [1, 2, 3, 4, 5, 7, 6] swap (5,6) 5 [1, 2, 3, 4, 5, 6, 7] </code></pre> <blockquote> <p>It took 5 swaps to sort the array.</p> </blockquote> <p>The code:</p> <pre><code>int minimumSwaps(int arr_count, int* arr) { long long int i,count=0,j,temp,min,min_index; for(i=0;i&lt;arr_count;i++) { min=arr[i]; min_index=i; for(j=i+1;j&lt;arr_count;j++) { if(arr[j]&lt;min) { min=arr[j]; min_index=j; } } if(min_index!=i) { count++; temp=arr[min_index]; arr[min_index]=arr[i]; arr[i]=temp; } } return count; } </code></pre> <p>5 out of 15 test-cases are failing. Here is one of the test <a href="https://hr-testcases-us-east-1.s3.amazonaws.com/70816/input09.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&amp;Expires=1540365186&amp;Signature=2CFzpZcbYUrWPmQUfS48Mvhbq8E%3D&amp;response-content-type=text%2Fplain" rel="noreferrer">cases</a>. It is failing with a message as &quot;Terminated due to timeout&quot;.</p> <p>I used selection sort approach as selection sort makes minimum swap operation. My time complexity is O(n^2). Can I reduce it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T18:18:19.410", "Id": "397829", "Score": "0", "body": "The array length, array elements and return values are all of type `int`. It doesn't make any sense to use `long long int` for all local variables; that will just slow down your...
[ { "body": "<h3>Analyzing the problem, finding clues</h3>\n\n<blockquote>\n <p>I used selection sort approach as selection sort makes minimum swap operation.</p>\n</blockquote>\n\n<p>Really? (I don't know.) More importantly, are you sure sorting is needed here?</p>\n\n<blockquote>\n <p>My time complexity is <s...
{ "AcceptedAnswerId": "206309", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T05:26:46.237", "Id": "206158", "Score": "4", "Tags": [ "c", "programming-challenge", "sorting", "time-limit-exceeded" ], "Title": "Minimum number of swaps required to sort the array in ascending order" }
206158
<p>The code consists in making a list of elements sortable (with the drag on the right) and selectable (click on the text). However it seems a little too complex. </p> <p><a href="https://codesandbox.io/s/434p397p74" rel="nofollow noreferrer">https://codesandbox.io/s/434p397p74</a></p> <p>Would it be possible to simplify / improve?</p> <p>What are the missing good practices?</p> <p>PS: I am a beginner in React. I used a library for the sortable part and made the selectable part</p> <p><strong>index.js</strong></p> <pre><code>import React from "react"; import ReactDOM from "react-dom"; import { SortableContainer, SortableElement, arrayMove } from "react-sortable-hoc"; import { SelectableList, SelectableItem } from "./selectable"; import { SortableHandler } from "./sortable"; import "./styles.css"; function Item(props) { return ( &lt;li&gt; &lt;SelectableItem item={props.value} index={props.sortIndex} /&gt; -{" "} &lt;SortableHandler /&gt; &lt;/li&gt; ); } const SortableItem = SortableElement(Item); function List({ children }) { return ( &lt;ul&gt; &lt;SelectableList&gt;{children}&lt;/SelectableList&gt; &lt;/ul&gt; ); } const SortableList = SortableContainer(List); class App extends React.Component { constructor(props) { super(props); this.state = { items: ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"] }; } onSortEnd = ({ oldIndex, newIndex }) =&gt; { this.setState({ items: arrayMove(this.state.items, oldIndex, newIndex) }); }; render() { let items = []; for (let i in this.state.items) { items.push( &lt;SortableItem value={this.state.items[i]} index={parseInt(i)} sortIndex={this.state.items[i]} key={i} /&gt; ); } return ( &lt;SortableList onSortEnd={this.onSortEnd} useDragHandle={true} axis="y" lockAxis="y" lockOffset={["0%", "0%"]} lockToContainerEdges={true} useContainerAsSortableHelperParent={true} &gt; {items} &lt;/SortableList&gt; ); } } const rootElement = document.getElementById("root"); ReactDOM.render(&lt;App /&gt;, rootElement); </code></pre> <p><strong>selectable.js</strong></p> <pre><code>import React from "react"; const SelectableContext = React.createContext({ activeIndex: null, setActiveIndex: () =&gt; {} }); export class SelectableList extends React.Component { constructor(props) { super(props); this.container = React.createRef(); this.state = { activeIndex: null, setActiveIndex: this.setActiveIndex.bind(this) }; this.handleClickOutside = this.handleClickOutside.bind(this); } componentDidMount() { document.addEventListener("mousedown", this.handleClickOutside); } componentWillUnmount() { document.removeEventListener("mousedown", this.handleClickOutside); } handleClickOutside(event) { if ( this.container.current &amp;&amp; !this.container.current.contains(event.target) ) { this.setActiveIndex(null); } } setActiveIndex(index) { this.setState({ activeIndex: index }); } render() { return ( &lt;SelectableContext.Provider value={this.state}&gt; &lt;div className="selectable-container" ref={this.container}&gt; {this.props.children} &lt;/div&gt; &lt;/SelectableContext.Provider&gt; ); } } export class SelectableItem extends React.Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); } onClick(context) { context.setActiveIndex(this.props.index); } render() { return ( &lt;SelectableContext.Consumer&gt; {context =&gt; { return ( &lt;span style={{ color: context.activeIndex === this.props.index ? "red" : "black" }} onClick={() =&gt; { this.onClick(context); }} &gt; {this.props.item} &lt;/span&gt; ); }} &lt;/SelectableContext.Consumer&gt; ); } } </code></pre> <p><strong>sortable.js</strong></p> <pre><code>import React from "react"; import { SortableHandle } from "react-sortable-hoc"; const SortableHandler = SortableHandle(function() { return ( &lt;span style={{ border: "1px solid black", padding: "2px", fontSize: "10px" }} &gt; Drag &lt;/span&gt; ); }); export { SortableHandler }; </code></pre> <p><strong>react-sortable-hoc</strong></p> <p><a href="https://github.com/clauderic/react-sortable-hoc" rel="nofollow noreferrer">https://github.com/clauderic/react-sortable-hoc</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T12:09:25.480", "Id": "397743", "Score": "0", "body": "Code added to the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T12:42:26.457", "Id": "397752", "Score": "0", "body": "I cha...
[ { "body": "<p>To allow the management of a state common to several components but whose hierarchy is indirect (which is the case here for the components managing the selection), the simplest is to use Redux.</p>\n\n<p><a href=\"https://i.stack.imgur.com/MqhzT.png\" rel=\"nofollow noreferrer\"><img src=\"https:/...
{ "AcceptedAnswerId": "206511", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T08:51:29.407", "Id": "206169", "Score": "0", "Tags": [ "javascript", "algorithm", "react.js", "jsx" ], "Title": "List with selectable and sortable elements" }
206169
<p>We have a <code>modifyCoefficient(const char* name, int value)</code> function that updates the value of a coefficient in a container. The names are known at compile time, they are read from an XML file in a pre-build step and stored in an array.<br> Usage: <code>data.modifyCoefficient("ADAPTIVE", 1);</code><br> Compiler: MSVC 2017 v15.8</p> <p>I would like to get a compile time error when the coefficient name does not exist.<br> With the following code that happens, but is there a way to do it without a macro?</p> <pre><code>#include &lt;array&gt; #define COEFF(name) returnName&lt;coefficientExists(name)&gt;(name) constexpr std::array&lt;const char*, 3&gt; COEFFICIENTS = { "VERSION", "CHANNELS", "ADAPTIVE" }; constexpr bool coefficientExists(const char* name) { for (auto coefficientIndex = 0U; coefficientIndex &lt; COEFFICIENTS.size(); ++coefficientIndex) { if (COEFFICIENTS[coefficientIndex] == name) return true; } return false; } template&lt;bool CoefficientTest&gt; constexpr const char* returnName(const char* name) { static_assert(CoefficientTest, "coefficient does not exist"); return name; } int main() { static_assert(coefficientExists("VERSION"), "should exist"); static_assert(coefficientExists("TEST") == false, "should not exist"); static_assert(COEFF("ADAPTIVE") == "ADAPTIVE", "should return name"); COEFF("CHANNELS"); // data.modifyCoefficient(COEFF("ADAPTIVE"), 1); return 0; } </code></pre> <p><a href="https://godbolt.org/z/kpGcMS" rel="nofollow noreferrer">https://godbolt.org/z/kpGcMS</a></p>
[]
[ { "body": "<p>You have to compare values char by char, or even simpler change <code>const char*</code> to <code>std::string_view</code> make your code work.</p>\n\n<p>Thanks to the deduction guides, you can just write <code>std::array = ...</code> and template parameters will be automatically deduced.</p>\n\n<p...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T09:07:46.553", "Id": "206172", "Score": "3", "Tags": [ "c++", "constant-expression" ], "Title": "Check array contains element at compile time" }
206172
<p>I have tried to write a test-spy myself. Just for getting more familar with the topic.</p> <p>Here's 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>// --------- SPY - Start ----------------------------------- class Spy { constructor(func) { this.func = func; this.returnValue = null; this.result = null; this.countFuncCalled = 0; } invoke(...givenArgs) { this.receivedArgs = givenArgs; this.returnValue = this.func(...givenArgs); this.countFuncCalled++; } } // --------- SPY - End ------------------------------------ const calc = { add: (a, b) =&gt; { return a + b; }, sub: (a, b) =&gt; { return a - b; } } const addSpy = new Spy(calc.sub); addSpy.invoke(9, 4); console.log(`Used arguments: ${addSpy.receivedArgs.join(", ")}`); console.log(`Return value: ${addSpy.returnValue}`); console.log(`Count of function-calls: ${addSpy.countFuncCalled}`); addSpy.invoke(8, 7); console.log(`Used arguments: ${addSpy.receivedArgs.join(", ")}`); console.log(`Return value: ${addSpy.returnValue}`); console.log(`Count of function-calls: ${addSpy.countFuncCalled}`);</code></pre> </div> </div> </p> <p>What do you think about my implementation? Is is done in a basically correct way?</p> <p>I'm I using the ES6-features (Classes, Rest, Spread) right?</p> <p>What would you have done differently and why?</p> <p>Looking forward to reading your comments and answers.</p>
[]
[ { "body": "<blockquote>\n <p>What do you think about my implementation? Is is done in a basically correct way?</p>\n</blockquote>\n\n<p>Yeah who is to say what is \"correct\"? I mostly have worked with the <a href=\"https://www.chaijs.com/\" rel=\"nofollow noreferrer\">chaiJS</a> <a href=\"https://www.chaijs.c...
{ "AcceptedAnswerId": "208797", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T13:23:04.390", "Id": "206188", "Score": "1", "Tags": [ "javascript", "unit-testing", "ecmascript-6" ], "Title": "Test-Spy Implementation" }
206188
<p>I'm building a date range selector, and while this works, I feel like I'm making it more complicated than it needs to be. Is there a more elegant way of writing this?</p> <p>Possibly using computed values or watches?</p> <pre><code>&lt;template&gt; &lt;form&gt; &lt;select @change="rangeSelection"&gt; &lt;option v-for="(option, key) in rangeOptions" :key="key" :value="key"&gt; {{option.display}} &lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;/template&gt; &lt;script&gt; import moment from 'moment'; export default { name: 'DateRangeChooser', data: () =&gt; { return { selectedRange: "last7Days", startDate: moment().subtract(8, 'days'), endDate: moment().subtract(1, 'days'), rangeOptions: { last7Days: { display: 'Last 7 Days', startDate: moment().subtract(8, 'days'), endDate: moment().subtract(1, 'days') }, lastWeek: { display: 'Last Week', startDate: moment().startOf('week').subtract(1, 'week'), endDate: moment().endOf('week').subtract(1, 'week') }, last30days: { display: 'Last 30 days', startDate: moment().subtract(31, 'days'), endDate: moment().subtract(1, 'days') } } } }, methods: { rangeSelection: function(e){ this.endDate = this.rangeOptions[e.currentTarget.value].endDate; this.startDate = this.rangeOptions[e.currentTarget.value].startDate; } } }; &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-28T16:35:53.610", "Id": "414773", "Score": "0", "body": "I would suggest using `date-fns` instead of `moment`, since moment requires you to embed the entire library, and date-fns lets you import only the parts you need" } ]
[ { "body": "<p>Yes you can use <a href=\"https://vuejs.org/v2/guide/computed.html\" rel=\"nofollow noreferrer\">computed properties</a>:</p>\n\n<pre><code>computed: {\n endDate: function() {\n //determine endDate based on value of selectedRange\n },\n startDate: function() {\n //determine star...
{ "AcceptedAnswerId": "206213", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T13:51:00.880", "Id": "206192", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "vue.js" ], "Title": "Vue component over-complication" }
206192
<p>I've written two classes that I use to create and manage a high score list. I plan to use this code for my own, larger project. I would like to ask if there is something to complain about my code. Were the language tools and the libraries of the language used meaningfully? Does my implementation meet the requirements of good, object-oriented design? Is the code easy to read?</p> <p><strong>ScoreList</strong></p> <pre><code>import java.util.List; import java.util.ArrayList; import java.util.Comparator; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class ScoreList implements Serializable { private String description; private List&lt;Score&gt; scores; private int numberOfEntries; private String saveName; private boolean autoSave; // should be used, if the user wants to store his scores on disk public ScoreList(String description, int numberOfEntries, String saveName, boolean autoSave) { this.description = description; scores = new ArrayList&lt;&gt;(); this.numberOfEntries = numberOfEntries; this.saveName = saveName; this.autoSave = autoSave; } // should be used, if the scores dont have to be saved to a file public ScoreList(String description, int numberOfEntries) { this.description = description; this.numberOfEntries = numberOfEntries; saveName = null; autoSave = false; } private void sort() { scores.sort(new Comparator&lt;Score&gt;() { @Override public int compare(Score score1, Score score2) { Integer int1 = score1.getPoints(); Integer int2 = score2.getPoints(); return int1.compareTo(int2); } }); } public boolean addScore(Score score) { if (scores.size() &lt; numberOfEntries) { scores.add(score); sort(); if (autoSave) { save(); } return true; } Score lowestScore = scores.get(0); if (score.getPoints() &gt; lowestScore.getPoints()) { scores.remove(lowestScore); scores.add(score); sort(); if (autoSave) { save(); } return true; } return false; } public void save() { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(saveName))) { oos.writeObject(this); } catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { StringBuilder returnValue = new StringBuilder(); returnValue.append(description); returnValue.append("\n\n"); for (Score score : scores) { returnValue.append(score.getName()); returnValue.append(" - "); returnValue.append(score.getPoints()); returnValue.append("\n"); } return returnValue.toString(); } } </code></pre> <p><strong>Score</strong></p> <pre><code>import java.io.Serializable; public class Score implements Serializable { private String name; private int points; public Score(String name, int points) { this.name = name; this.points = points; } public String getName() { return name; } public int getPoints() { return points; } } </code></pre> <p><strong>Main</strong></p> <pre><code>import java.util.Random; // This class is the test class of the list public class Main { public static void main(String[] args) { // Create a ScoreList object and add scores to it ScoreList scoreList = new ScoreList("Who has the most flowerpots?", 10, "flowerPotsFile", true); String[] names = {"Klaus", "Dieter", "Hans", "Peter", "Maria", "Jürgen", }; Random random = new Random(); for (int i = 0; i &lt; 20; i++) { String name = names[random.nextInt(names.length)]; int points = random.nextInt(10) + 1; if (scoreList.addScore(new Score(name, points))) { System.out.println(name + " has " + points + " flowerpots and can be added to the score list!"); } else { System.out.println(name + " has only " + points + " flowerpots and that is not enough."); } } System.out.println("\n"); // print out score list System.out.println(scoreList); } } </code></pre>
[]
[ { "body": "<p>just some minor issues...</p>\n\n<h1>adding a proper serializable interface:</h1>\n\n<p>while you provide a filename within the constructor and a <code>save()</code> methode i would apprechiate to let the <code>ScoreList</code>class to implement a proper (at least a minimal) serialization interfac...
{ "AcceptedAnswerId": "207148", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T14:21:53.710", "Id": "206194", "Score": "2", "Tags": [ "java" ], "Title": "Managing a high score list" }
206194
<p>Consider this interview question:</p> <blockquote> <p>You have an array of integers, and for each index you want to find the product of every integer except the integer at that index.</p> <p>Write a method get_products_of_all_ints_except_at_index() that takes an array of integers and returns an array of the products.</p> <p>For example, given:</p> <pre><code>[1, 7, 3, 4] </code></pre> <p>your method would return:</p> <pre><code>[84, 12, 28, 21] </code></pre> <p>by calculating:</p> <pre><code>[7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3] </code></pre> <p>Here's the catch: You can't use division in your solution!</p> </blockquote> <p>And here's my solution:</p> <pre><code>def get_products_of_all_ints_except_at_index(arr) products = [] (0...arr.length).each do |index| product = 1 arr.each do |num| if num != arr[index] product *= num end end products &lt;&lt; product end products end </code></pre>
[]
[ { "body": "<p>The first thing I would look for as an interviewer would be the use of <code>with_index</code> as well as <code>map</code> for the outer loop and <code>reduce</code> for the inner loop.</p>\n\n<pre><code>def get_products_of_all_ints_except_at_index(arr)\n arr.each_with_index.map do |item, index|\...
{ "AcceptedAnswerId": "206294", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T14:24:11.173", "Id": "206195", "Score": "1", "Tags": [ "ruby", "interview-questions" ], "Title": "Whiteboarding - Multiply all values in array except at the index for each" }
206195
<p>This is a class in my React app. This code works and displays an appropriate icon and question for every description.</p> <pre><code>class myQuestion extends PureComponent { render() { const { description } = this.props.question; let icon = icon; let question = question; if (description === 'Happy') { icon = &lt;FontAwesomeIcon icon={faSmile} /&gt;; question = 'You answered happy. Why?'; } else if (description === 'OK') { icon = &lt;FontAwesomeIcon icon={faMeh} /&gt;; question = 'You answered OK. Why?'; } else if (description === 'Angry') { icon = &lt;FontAwesomeIcon icon={faAngry} /&gt;; question = 'You answered angry. Why?'; } else { icon = ''; question = ''; } return ( &lt;div&gt; &lt;Question icon={icon} description={description} question={question} /&gt; &lt;/div&gt; ); } } </code></pre> <p>I'd like to know how would be a better way to write this if else statement, preferably removing the let.</p> <p>'description' is a prop of the question, but 'icon' and 'question' are dependent on what the 'description' is. The 'description' comes from the ID of a previous answer to a question.</p> <p>Is there a way I could put this logic before the render function?</p>
[]
[ { "body": "<p>In cases where your value is determined by a string key, a key-value mapping is often the way to go. In this case, we store your icon JSX and questions in objects keyed by description. Then you simply access them using the current description as key.</p>\n\n<pre><code>const icons = {\n Happy: &lt...
{ "AcceptedAnswerId": "206202", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T14:51:12.567", "Id": "206200", "Score": "1", "Tags": [ "react.js", "jsx" ], "Title": "Reacting to moods with icons" }
206200
<p>I create simple Android timer application and I try to use MVP design pattern. I read some tutorials and after that I started writing code. My code is working correctly and as intended. There is really simple activity with 3 buttons (start, pause and stop) and text view with time to finish. I have always had problem with proper implementation of app architecture patterns so I'd like to know whether or not I properly separated view and business logic (in a way MVP pattern intended to). My code looks like this.</p> <p>View:</p> <pre><code>interface TimerView { fun updateTime(time: Long) fun disableStop() fun disableStart() fun disablePause() fun enableStop() fun enableStart() fun enablePause() } class MainActivity : AppCompatActivity(), TimerView { private var presenter = TimerPresenter(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) } override fun onResume() { super.onResume() presenter.restoreState(this) } override fun onPause() { super.onPause() presenter.saveState(this) presenter.stopTimer() } fun stopTimer(view: View) { presenter.stopTimer() presenter.resetTimer() } fun startTimer(view: View) { presenter.startTimer() } fun pauseTimer(view: View) { presenter.pauseTimer() } override fun updateTime(time: Long) { timeText.text = timeToString(time) } override fun disableStop() { stopFab.isEnabled = false } override fun disableStart() { startFab.isEnabled = false } override fun disablePause() { pauseFab.isEnabled = false } override fun enableStop() { stopFab.isEnabled = true } override fun enableStart() { startFab.isEnabled = true } override fun enablePause() { pauseFab.isEnabled = true } } </code></pre> <p>Presenter:</p> <pre><code>class TimerPresenter(private val view: TimerView) : TimerListener { private val timer = Timer(this) fun stopTimer() { timer.stop() } fun startTimer() { timer.start() } fun pauseTimer() { timer.pause() } fun resetTimer() { timer.reset() } fun saveState(context: Context) { timer.saveState(context) } fun restoreState(context: Context) { timer.restoreState(context) } private fun setStopView() { view.disableStop() view.disablePause() view.enableStart() } private fun setStartView() { view.disableStart() view.enableStop() view.enablePause() } private fun setPauseView() { view.disablePause() view.enableStop() view.enableStart() } private fun setViewState(state: TimerData.State) { when (state) { TimerData.State.Stop -&gt; setStopView() TimerData.State.Run -&gt; setStartView() TimerData.State.Pause -&gt; setPauseView() } } private fun updateTimer(timeRemaining: Long) { view.updateTime(timeRemaining) } override fun onTimerFinish() { timer.reset() } override fun onTimerTick(timeRemaining: Long) { updateTimer(timeRemaining) } override fun onTimerStateChange(newState: TimerData.State) { setViewState(newState) } override fun onTimerReset(timeRemaining: Long) { updateTimer(timeRemaining) } override fun onTimerStateRestored(timeRemaining: Long, state: TimerData.State) { updateTimer(timeRemaining) setViewState(state) if (state == TimerData.State.Run) { timer.start() } } } </code></pre> <p>Model:</p> <pre><code>interface TimerListener { fun onTimerFinish() fun onTimerTick(timeRemaining: Long) fun onTimerStateChange(state: TimerData.State) fun onTimerReset(timeRemaining: Long) fun onTimerStateRestored(timeRemaining: Long, state: TimerData.State) } data class TimerData(var state: State = State.Stop, var timerLength: Long = 0L, var timeRemaining: Long = 0L) { enum class State { Stop, Run, Pause } fun loadData(context: Context) { state = PrefUtils.getState(context) timerLength = PrefUtils.getTimerLength(context) timeRemaining = if (state != State.Stop) { PrefUtils.getTimeRemaining(context) } else { timerLength } } fun saveData(context: Context) { PrefUtils.setState(context, state) PrefUtils.setTimeRemaining(context, timerLength) PrefUtils.setTimeToStop(context, timeRemaining) } fun reset() { timeRemaining = timerLength } } class Timer(private val listener: TimerListener) { private var data = TimerData() private var timer: CountDownTimer? = null fun start() { timer = object : CountDownTimer(data.timeRemaining * 1000L, 1000L) { override fun onFinish() { stop() listener.onTimerFinish() } override fun onTick(millisUntilFinished: Long) { --data.timeRemaining listener.onTimerTick(data.timeRemaining) } }.start() data.state = TimerData.State.Run listener.onTimerStateChange(data.state) } fun stop() { timer?.cancel() data.state = TimerData.State.Stop listener.onTimerStateChange(data.state) } fun pause() { timer?.cancel() data.state = TimerData.State.Pause listener.onTimerStateChange(data.state) } fun reset() { data.reset() listener.onTimerReset(data.timeRemaining) } fun saveState(context: Context) { data.saveData(context) } fun restoreState(context: Context) { data.loadData(context) listener.onTimerStateRestored(data.timeRemaining, data.state) } } </code></pre> <p>Did I separate tasks correctly between classes or maybe there is something wrong with my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T15:26:23.290", "Id": "397799", "Score": "2", "body": "\"I create simple Android application\" Ok, good. Tell us more. Does it work as intended? What is it supposed to do? You used MVP, ok, but to do what? What problem does your code...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T15:00:10.250", "Id": "206201", "Score": "2", "Tags": [ "design-patterns", "android", "kotlin", "mvp" ], "Title": "Timer application in MVP" }
206201
<p>Anyone know how I write this code shorter, with modulos maybe? I also want to add weeks and years do this code, but it kind of got too long for that. Maybe there is some smart algoritm? Something in a for-loop?</p> <pre><code>public static String formatSeconds (long seconds) { if (seconds &lt; 60) return seconds != 1 ? seconds + " seconds" : "1 second"; if (seconds &lt; 3600) { seconds /= 60; return seconds != 1 ? seconds + " minutes" : "1 minute"; } if (seconds &lt; 86400) { seconds /= 3600; return seconds != 1 ? seconds + " hours" : "1 hour"; } if (seconds &lt; 2629743) //month { seconds /= 86400; return seconds != 1 ? seconds + " days" : "1 day"; } seconds /= 2629743; return seconds != 1 ? seconds + " months" : "1 month"; } </code></pre>
[]
[ { "body": "<p>This is a case for an <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow noreferrer\"><code>Enum</code></a> and a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/NavigableMap.html\" rel=\"nofollow noreferrer\"><code>NavigableMap</code></a>. </p>...
{ "AcceptedAnswerId": "206218", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T16:01:25.593", "Id": "206203", "Score": "2", "Tags": [ "java", "datetime", "formatting" ], "Title": "Java function to format seconds as minutes, hours, days" }
206203
<p>I added learning rate and momentum to a neural network implementation from scratch I found at: <a href="https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6" rel="nofollow noreferrer">https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6</a></p> <p>However I had a few questions about my implementation:</p> <ul> <li>Is it correct? Any suggested improvements? It appears to output adequate results generally but outside advice is very appreciated.</li> <li><p>With a learning rate &lt; 0.5 or momentum > 0.9 the network tends to gets stuck in a local optimum where loss = ~1. I assume this is because step size isn't big enough to escape this but is there a way to overcome this? Or is this inherent with the nature of the data being solved and unavoidable.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): sig = 1 / (1 + np.exp(-x)) return sig * (1 - sig) class NeuralNetwork: def __init__(self, x, y): self.input = x self.weights1 = np.random.rand(self.input.shape[1], 4) self.weights2 = np.random.rand(4, 1) self.y = y self.output = np.zeros(self.y.shape) self.v_dw1 = 0 self.v_dw2 = 0 self.alpha = 0.5 self.beta = 0.5 def feedforward(self): self.layer1 = sigmoid(np.dot(self.input, self.weights1)) self.output = sigmoid(np.dot(self.layer1, self.weights2)) def backprop(self, alpha, beta): # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1 d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output))) d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1))) # adding effect of momentum self.v_dw1 = (beta * self.v_dw1) + ((1 - beta) * d_weights1) self.v_dw2 = (beta * self.v_dw2) + ((1 - beta) * d_weights2) # update the weights with the derivative (slope) of the loss function self.weights1 = self.weights1 + (self.v_dw1 * alpha) self.weights2 = self.weights2 + (self.v_dw2 * alpha) if __name__ == "__main__": X = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) y = np.array([[0], [1], [1], [0]]) nn = NeuralNetwork(X, y) total_loss = [] for i in range(10000): nn.feedforward() nn.backprop(nn.alpha, nn.beta) total_loss.append(sum((nn.y-nn.output)**2)) iteration_num = list(range(10000)) plt.plot(iteration_num, total_loss) plt.show() print(nn.output) </code></pre></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T16:40:34.640", "Id": "397808", "Score": "0", "body": "\"Is it correct?\" Did you test it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T19:30:27.503", "Id": "397835", "Score": "0", "body...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T16:30:01.487", "Id": "206205", "Score": "2", "Tags": [ "python", "python-3.x", "ai", "machine-learning", "neural-network" ], "Title": "Simple Neural Network from scratch using NumPy (Python)" }
206205
<p>I was doing a simple mad libs game thing but I want to know if there's any more efficient or readable way to write the code as I don't know the best ways to structure code as I am just begginning. Before I write any more of them please can someone tell me if there's a "better" or more accpeted way to write any of the code like if I should make more things in to functions and how to do so. This is Python 3.6.6. The game is supposed to prompt the user to enter a random word of their choice (it has to be a certain type of word to make sense in the sentence like adjective or verb) and inputs the prompted words into a sentence so it's funny and doesn't make any sense</p> <pre><code>import random print("&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; Mad Libs &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;") adjective = [] noun = [] verb_pr = [] noun_p = [] verb_pa = [] verb = [] def nouns(): global noun ans = input("Noun(singular):\n&gt; ").lower() noun.append(ans) def nouns_p(): global noun_p ans = input("Noun(plural):\n&gt; ").lower() noun_p.append(ans) def adjectives(): global adjective ans = input("Adjective:\n&gt; ").lower() adjective.append(ans) def verbs_pr(): global verb_pr ans = input("Verb(-ing):\n&gt; ").lower() verb_pr.append(ans) def verbs_pa(): global verb_pa ans = input("Verb(-ed):\n&gt; ").lower() verb_pa.append(ans) def verbs(): global verb ans = input("Verb:\n&gt; ").lower() verb.append(ans) verbs_pr() nouns_p() nouns() nouns() verbs_pr() nouns_p() verbs_pa() verbs() nouns_p() adjectives() verbs_pr() nouns_p() verbs_pr() random.shuffle(adjective) random.shuffle(noun) random.shuffle(verb_pr) random.shuffle(noun_p) random.shuffle(verb_pa) random.shuffle(verb) print("{3[0]} these {2[0]}, {1[0]} like a {1[1]}, I'm {3[1]} {2[1]} now, someone {4[0]} me do I {5[0]} {2[2]}, it's gonna be {0[0]}, {3[2]} {2[3]} that's what I'm {3[3]} about yeah".format(adjective,noun,noun_p,verb_pr,verb_pa,verb)) adjective = [] noun = [] verb_pr = [] noun_p = [] verb_pa = [] verb = [] verbs_pa() nouns() adjectives() adjectives() verbs_pr() nouns() verbs() nouns_p() verbs_pa() nouns() nouns() nouns() nouns() adjectives() nouns_p() verbs() nouns() nouns() adjectives() nouns_p() nouns() nouns() nouns() verbs() random.shuffle(adjective) random.shuffle(noun) random.shuffle(verb_pr) random.shuffle(noun_p) random.shuffle(verb_pa) random.shuffle(verb) print("""You have been {4[0]} into Hogwarts {1[0]} of {0[0]} and {0[1]}. You will be {2[0]} throughout the {1[1]} and will {5[0]} in the {3[0]}. You will be {4[1]} in one of the four houses. {1[2]}, {1[3]}, {1[4]} or {1[5]} and will learn much about the {0[2]} {3[1]}. Once you arrive you will {5[1]} The Great {1[6]} for a feast with the headmaster, Proffessor {1[7]}. You will need to get all the {0[3]} {3[2]} in {1[8]} Alley and get a {1[9]} from Ollivanders {1[10]} shop. We hope to {5[2]} you there.""".format(adjective,noun,verb_pr,noun_p,verb_pa,verb)) </code></pre>
[]
[ { "body": "<p>That works, but obviously, the code is repetitive, and a lot of work to maintain. To prepare each Mad Lib, you have to count the number of each type of blank, to make the required number of prompts. Then, you fill in the blanks using <code><em>str</em>.format(…)</code> with some rather cryptic p...
{ "AcceptedAnswerId": "206223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T16:44:18.353", "Id": "206207", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Python code for mad libs game" }
206207
<p>This is my first "serious" project after learning python for a while. The purpose of this script is to scrape proxies and check if they pass HTTPS websites. The main functionality is:</p> <ul> <li>Get args and set (if there are any)</li> <li>Get links to scrape from</li> <li>Scrape for proxies and save them to a file</li> <li>Check the scraped proxies using concurrency (threading) while saving the hits to a new file.</li> </ul> <p>I've heard one of the best ways to learn is to get feedback, and I don't have anyone close to me who has anything related to programming. I hope you guys could help me out and give me a harsh feedback.</p> <hr> <h3>proxy_tool.py</h3> <pre><code>import requests import re import data import time import sys import os import argparse from bs4 import BeautifulSoup from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool # Get's list of url's with proxies def get_links(): links = [] keyword = 'server-list' index_url = 'http://www.proxyserverlist24.top/' page = requests.get(index_url) soup = BeautifulSoup(page.text, 'html.parser') temp_links = soup.find_all('a') for atag in temp_links: link = atag.get('href') if atag.get('href') is None: pass elif keyword in link and '#' not in link and link not in links: links.append(link) return links # Scrape most recently uploaded proxies and returns a list of proxies # according to the maximum amount entered by the user (default 800) def scrape(links): url = links[0] page = requests.get(url) ip_list = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', page.text) return max_proxies(ip_list,data.max) # Save scraped list into a file def save_scraped(ip_list): if os.path.isfile(data.filename): os.remove(data.filename) with open(data.filename,'a') as wfile: for ip in ip_list: wfile.write(ip) wfile.write('\n') print('[!] {} Proxies were scraped and saved ! '.format(len(ip_list))) # Maximum amount of proxies to scrape def max_proxies(ip_list, max): ip_list = ip_list.copy() return ip_list[0:max] # Check if proxy is alive and gets a 200 response def is_good(p): proxy = {'https' : '{}'.format(p)} try : r = requests.get(data.url,proxies=proxy,headers=data.headers,timeout=data.timeout) if r.status_code is 200: hits_count(p) save_hits(p) except (requests.exceptions.Timeout, requests.exceptions.ProxyError, requests.exceptions.SSLError, requests.exceptions.ConnectionError) as e: pass # Save working proxy to a file def save_hits(p): with open('{} Checked ProxyList.txt'.format(data.date),'a') as wfile: wfile.write(p) wfile.write('\n') # Count hits to display when script finished executing def hits_count(p): data.hits += 1 print('[+] HIT - {}'.format(p)) def hits(): print('[!] {} Proxies checked and saved !'.format(data.hits)) def check_args(args=None): parser = argparse.ArgumentParser(description='A script to quickly get alive HTTPS proxies') parser.add_argument('-u', '--url', type=str, help='url to check proxy against', required=False, default='https://www.google.com') parser.add_argument('-m', '--max', type=int, help='maximum proxies to scrape', required=False, default=800) parser.add_argument('-t', '--timeout', type=int, help='set proxy timeout limit', required=False, default=8) parser.add_argument('-st', '--set-threads', type=int, help='set number of threads to run', required=False, default=30) results = parser.parse_args(args) return(results.url, results.max, results.timeout, results.set_threads) # Check multiple proxies at once from a given proxy list def check(p_list): pool = ThreadPool(data.num_threads) pool.map(is_good,p_list) pool.close() pool.join() def main(): # Get_links returns a list with links which is passed to scrape() to scrape from # which returns a proxy list to save in a file save_scraped(scrape(get_links())) p_list = open(data.filename).read().splitlines() check(p_list) hits() if __name__ == "__main__": # Set user input data.url, data.max, data.timeout, data.num_threads = check_args(sys.argv[1:]) main() </code></pre> <h3>data.py</h3> <p>This is responsible for holding data.</p> <pre><code>import random import datetime user_agent_list = [ # Chrome 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', # Firefox 'Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)', 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)' ] headers = {'User-Agent': random.choice(user_agent_list)} date = datetime.datetime.today().strftime('%Y-%m-%d') filename = '{} ProxyList.txt'.format(date) threads = [] url = 'https://www.google.com' timeout = 8 hits = 0 num_threads = 30 max = 800 </code></pre> <hr> <p>I have some specific questions:</p> <ol> <li>Is using an external module to hold data like I did in <code>data.py</code> considered to be a good practice, or should I create the variables in <code>main()</code>? (it looks cleaner this way)</li> <li>Is using a lot of functions even for small things like I did with <code>hits()</code> or <code>hits_count()</code> considered to be a good practice ? </li> <li>How I implemented <code>save_scraped(scrape(get_links()))</code> looks pretty messy to me, but I tried to avoid using global variables; is that good practice?</li> <li>By changing to <code>asyncio</code> instead of <code>threading</code> could I achieve faster performance while checking the proxies?</li> <li>Is my PEP standard conformance okay?</li> </ol> <p>That's all I can think of right now. Feel free to suggest anything from more pythonic code to a better implementation of a function or whatever comes to your mind.</p>
[]
[ { "body": "<ol>\n<li><p>Of course. You can also do another thing: keep all the user agents in a separate file (eg. <code>ua.txt</code>) and then combine rest of the code with main file. With a one-liner, you can fetch all user-agents in the <code>user_agents_list</code>.</p>\n\n<pre><code>for line in open('ua.t...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T16:49:15.873", "Id": "206208", "Score": "5", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Proxy scraper and multithreaded checker" }
206208
<p>Here is my code that I made for a school assignment (a work in progress).</p> <p>I'm a beginner at programming and I'll be glad if someone gives me a thorough review of my code. I've just switched from TurboC++ to Code::Blocks IDE using MinGW.</p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;process.h&gt; #include &lt;string.h&gt; using namespace std; class Login { public: char username[10], password[10]; }log1,log2; int login() { cout &lt;&lt; "\t\t\t Login Panel" &lt;&lt; endl; getchar(); cout &lt;&lt; "Enter username: "; cin.getline(log1.username,10); cout &lt;&lt; "Enter password: "; cin.getline(log1.password,10); ifstream fin ("db", ios::binary | ios::in); if (!fin) { cout&lt;&lt; "Database cannot be accessed" &lt;&lt; endl; return 0; } int i=0; while(!fin.eof()) { fin.read((char*)&amp;log2 , sizeof(Login)); if (strcmp(log1.username,log2.username)==0 &amp;&amp; strcmp(log1.password,log2.password)==0) { cout &lt;&lt; "Logged in" &lt;&lt; endl; i=1; break; } } fin.close(); if(!i) cout &lt;&lt; "Wrong Credentials"; return i; } void signup() { cout &lt;&lt; "\t\t\t Signup Panel" &lt;&lt; endl; cout &lt;&lt; "Enter username: "; cin.getline(log1.username,10); cout &lt;&lt; "Enter password: "; cin.getline(log1.password,10); if( !strlen(log1.username) || !strlen(log1.password) ) { cout &lt;&lt; "Error, unsupported characters" &lt;&lt; endl; signup(); } ifstream fin ("db", ios::binary | ios::in); while(!fin.eof()) { fin.read((char*)&amp;log2 , sizeof(Login)); if (!fin) break; if (strcmp(log1.username,log2.username)==0 ) { cout &lt;&lt; "User already exists!" &lt;&lt; endl; system("PAUSE"); system("CLS"); signup(); } } fin.close(); ofstream fout ("db", ios::binary | ios::app); fout.write((char*)&amp;log1 , sizeof(Login)); fout.close(); } class stu { uint32_t rollno; char Name[20]; char Class[4]; float marks; char grade; char calcgrade(float t1, char t2) { if (t1 &gt;= 75) t2='A'; else if (t1 &gt;= 60) t2 = 'B'; else if (t1 &gt;= 50) t2 = 'C'; else if (t1 &gt;= 40) t2 = 'D'; else t2 = 'E' ; return t2; } public: void getdata() { cout&lt;&lt;"Rollno :"; cin&gt;&gt;rollno; cout&lt;&lt;"Class :"; cin&gt;&gt;Class; cout&lt;&lt;"Name :"; getchar(); cin.getline(Name, 20); cout&lt;&lt;"Marks :"; cin&gt;&gt;marks; grade=calcgrade(marks,grade); } void putdata() { cout&lt;&lt; "Rollno : " &lt;&lt; rollno &lt;&lt; "\t Name : " &lt;&lt; Name &lt;&lt; "\n Marks : " &lt;&lt; marks &lt;&lt; "\t Grade : " &lt;&lt; grade &lt;&lt; endl; } int getrno() { return rollno; } } s1, stud ; int data_append(char* neim) { ifstream fi (neim, ios::in | ios::binary); if (!fi) { return -1; } ofstream fo ("temp.dat", ios::out | ios::binary); char last ='y'; std::cout &lt;&lt; " Enter details of student whose record is to be inserted \n "; s1.getdata(); while (!fi.eof()) { fi.read((char*)&amp;stud, sizeof(stu)); if ( s1.getrno()&lt;= stud.getrno()) { fo.write((char*)&amp;s1, sizeof(stu)); last = 'n'; break; } else fo.write((char*)&amp;stud, sizeof(stu)); } if (last == 'y') fo.write((char*)&amp;s1, sizeof(stu)); else if (!fi.eof()) { while (!fi.eof()) { fi.read((char*)&amp;stud, sizeof(stu)); fo.write((char*)&amp;stud, sizeof(stu)); } } fi.close(); fo.close(); remove(neim); rename("temp.dat",neim); return 0; } int data_delete(char* neim) { ifstream fi (neim, ios::in | ios::binary); if (!fi) { cout &lt;&lt; "No such file in database" &lt;&lt; endl; system("PAUSE"); return -1; } ofstream file ("temp.dat", ios::out | ios::binary); int rno; char found = 'f' , confirm = 'n' ; cout &lt;&lt; " Enter rollno of student whose record is to be deleted \n"; cin &gt;&gt; rno; while (!fi.eof()) { fi.read((char*)&amp;s1,sizeof(stu)); if ( s1.getrno() == rno ) { s1.putdata(); found = 't'; cout &lt;&lt; " Are you sure, you want to delete this record? (y/n).. "; cin&gt;&gt; confirm ; if (confirm == 'n') file.write((char*)&amp;s1,sizeof(stu)); } else file.write((char*)&amp;s1,sizeof(stu)); } if ( found == 'f' ) cout &lt;&lt; " Record not found ;__; \n"; fi.close(); file.close(); remove(neim); rename("temp.dat",neim); return 0; } int data_modify(char* neim) { fstream fio(neim,ios::in|ios::out|ios::binary); int rno ; long pos ; char found = 'f'; cout &lt;&lt; " Enter rollno of student whose record is to be modified \n"; getchar(); cin &gt;&gt; rno; while ( !fio.eof()) { pos = fio.tellg(); fio.read((char*)&amp;s1, sizeof(stu)); if ( s1.getrno() == rno ) { fio.seekg(pos); fio.write((char*)&amp;s1, sizeof(stu)); found = 't'; break; } } if ( found == 'f') return -1; fio.seekg(0); cout &lt;&lt; "Now the file contains \n"; while(!fio.eof()) { fio.read((char*)&amp;stud, sizeof(stu)); stud.putdata(); } fio.close(); return 0; } int data_search(char* neim) { ifstream fi (neim, ios::in | ios::binary); if (!fi) { return -1; } int rno; char found = 'f' ; cout &lt;&lt; " Enter rollno of student whose record is to be searched \n"; cin &gt;&gt; rno; while (!fi.eof()) { fi.read((char*)&amp;s1,sizeof(stu)); if ( s1.getrno() == rno ) { s1.putdata(); found = 't'; fi.close(); } } if ( found == 'f' ) return -2; return 0; } int data_new(char* Class) { ifstream tmp1 (Class,ios::in); if (tmp1) { cout &lt;&lt; "Class already exists!!!" &lt;&lt; endl; tmp1.close(); return -1; } ofstream newclass (Class,ios::out); newclass.close(); return 0; } int data_remove(char* ClassDel) { ifstream tmp1 (ClassDel,ios::in); if ( !tmp1 ) return -1; tmp1.close(); remove(ClassDel); return 0; } int main() { loginpanel: if(!login()) { system("pause"); signup(); } system("pause"); menu: system("cls"); cout &lt;&lt; "\t\t\t Enter the number to proceed to corresponding operation" &lt;&lt; endl; cout &lt;&lt; "1. Create Class" &lt;&lt; endl &lt;&lt; "2. Append Data" &lt;&lt; endl &lt;&lt; "3. Delete Data" &lt;&lt; endl &lt;&lt; "4. Modify Data" &lt;&lt; endl &lt;&lt; "5. Search Record" &lt;&lt; endl &lt;&lt; "6. Delete Class" &lt;&lt; endl &lt;&lt; "7. Logout" &lt;&lt; endl &lt;&lt; "8. Exit" &lt;&lt; endl; int *op = new int; cin &gt;&gt; *op; switch (*op) { case 1 : { char Class[10]; cout &lt;&lt; "Enter new class name :"; getchar(); cin.getline(Class,10); cout &lt;&lt; "\nCreating Class files.." &lt;&lt; endl; *op=data_new(Class); if (*op==(-1)) { cout &lt;&lt; "Class already exists!!!" &lt;&lt; endl; break; } cout &lt;&lt; "Class creation successful" &lt;&lt; endl; system("pause"); delete op; break; } case 2 : { system("cls"); char neim[8]; cout &lt;&lt; "Enter class (use numerals only)"; //implemented for school project getchar(); cin.getline(neim,8); *op=data_append(neim); if (*op==(-1)) { cout &lt;&lt; "No such file in database" &lt;&lt; endl; break; } ifstream fi(neim, ios::in); cout &lt;&lt; "File now contains : \n"; while (!fi.eof()) { fi.read((char*)&amp;stud, sizeof(stu)); if (fi.eof()) break; stud.putdata(); } fi.close(); delete op; break; } case 3 : { cout &lt;&lt; "Enter class"; //implemented for school project getchar(); char neim1[8]; cin.getline(neim1,8); *op=data_delete(neim1); if (*op==(-1)) { cout &lt;&lt; "No such file in database" &lt;&lt; endl; system("PAUSE"); } ifstream fi; fi.open(neim1, ios::in); cout &lt;&lt; "File now contains : \n"; while (!fi.eof()) { fi.read((char*)&amp;stud, sizeof(stu)); if (fi.eof()) break; stud.putdata(); } fi.close(); delete op; break; } case 4 : { cout &lt;&lt; "Enter class (use numerals only)"; //implemented for school project char neim[8]; cin.getline(neim,8); *op=data_modify(neim); if ( *op==(-1)) { cout &lt;&lt; "Record not found ;__; \n"; } delete op; break; } case 5 : { cout &lt;&lt; "Enter class (use numerals only)"; //implemented for school project char neim[8]; cin.getline(neim,8); *op=data_search(neim); if(*op==(-1)) { cout &lt;&lt; "No such file in database" &lt;&lt; endl; system("PAUSE"); } else if(*op==(-2)) { cout &lt;&lt; "Record not found" &lt;&lt; endl; system("PAUSE"); } delete op; break; } case 6 : { char ClassDel[10]; cout &lt;&lt; "Enter class name to be deleted:" &lt;&lt; endl; cin.getline(ClassDel,10); cout &lt;&lt; "Deleting Class files.." &lt;&lt; endl; *op=data_remove(ClassDel); if(*op==(-1)) { cout &lt;&lt; "No such class as '" &lt;&lt; ClassDel &lt;&lt; "'" &lt;&lt; endl; } delete op; break; } case 7 : { delete op; goto loginpanel; } case 8 : { delete op; exit(0); } default : cout &lt;&lt; "Wrong input!"; } system("pause"); goto menu; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-04T15:44:57.620", "Id": "399165", "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 y...
[ { "body": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;process.h&gt;\n#include &lt;string.h&gt;\n</code></pre>\n\n<p>When you see an <code>include</code> directive followed by a vendor header, ending with<code>.h</code>, it's an alert: You're surely wrong. <a href=\"https://stac...
{ "AcceptedAnswerId": "206238", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T19:26:42.707", "Id": "206220", "Score": "1", "Tags": [ "c++" ], "Title": "School Student management project that keeps school records" }
206220
<p>I've implemented a C++ algorithm that moves elements satisfying a given unary predicate from one container into the other, deleting them from the input container.</p> <p>This is my implementation:</p> <pre><code>/** * Moves all elements in the input container * that satisfy the given predicate * into the output container, * and erases them from the input container. * @tparam Container The container type. * @tparam UnaryPredicate The predicate type. * @param in The input container. * @param out The output container. * @param predicate The predicate to satisfy. */ template &lt;class Container, class UnaryPredicate&gt; void move_and_erase_if(Container &amp;in, Container &amp;out, UnaryPredicate predicate) { // sort the input container so that all elements that // satisfy the predicate are moved to the end. std::sort(in.begin(), in.end(), [=](auto &amp;a, auto &amp;b){ return !predicate(a) &amp;&amp; predicate(b); }); // find the first element in the sorted container // that satisfies the predicate. // all elements following that element // also satisfy the predicate. auto it = std::find_if(in.begin(), in.end(), [=](auto &amp;val) { return predicate(val); }); // move the elements satisfying the predicate // into the output container. std::move(it, in.end(), std::back_inserter(out)); // erase the elements satisfying the predicate // from the input container. in.erase(it, in.end()); } </code></pre> <p>Is there a more efficient way to achieve this? Specifically, the call to <code>std::find_if</code> bugs me, as it applies the predicate to all elements a second time, until it finds the first one that satisfies it.</p> <p>I've written an example application using the algorithm on <a href="https://ideone.com/aXm1gP" rel="noreferrer">ideone</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T13:40:56.410", "Id": "397949", "Score": "1", "body": "This is too little to warrant its own answer but consider removing redundant comments. Good comments describe *why*, whereas code describes the *how*. Don’t have comments that pa...
[ { "body": "<p>Sorting the source is not specified as a requirement, so it seems that <a href=\"https://en.cppreference.com/w/cpp/algorithm/partition\" rel=\"noreferrer\"><code>std::partition</code></a> would do the necessary job more efficiently. As a perk benefit, <code>std::partition</code> returns the partit...
{ "AcceptedAnswerId": "206222", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T20:13:11.923", "Id": "206221", "Score": "8", "Tags": [ "c++", "algorithm", "c++11", "collections" ], "Title": "Moving elements satisfying a predicate from one container to another" }
206221
<p>I wrote the following sample script for learning purposes:</p> <pre><code>import requests import json import pyodbc import os import sys source_url = 'https://jsonplaceholder.typicode.com/posts/' query_posts_response = requests.get(source_url) if (query_posts_response.status_code == 200): posts = json.loads(query_posts_response.content.decode('utf-8')) db_connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=(local);" "Database=sandbox;" "Trusted_Connection=yes;") sys_devnull = open(os.devnull, 'w') sys_stdout_original = sys.stdout sys.stdout = sys_devnull db_cursor = db_connection.cursor() for post in posts: db_cursor.execute("INSERT INTO dbo.Posts(id, title) VALUES (?, ?)", post['id'], post['title']) db_connection.commit() db_connection.close() sys.stdout = sys_stdout_original </code></pre> <p>I'm grabbing content from a REST API, and I'm inserting it into a relational table.</p> <p>I write scripts in other languages, but this is my first Python script. I don't know what I don't know. I'm looking for a critique. I realize I was lazy on the database call and didn't create an exception handler. That said, is this the generally accepted way to interface with a REST endpoint and interact with a database?</p> <p>Concerning output of <code>db_cursor.execute()</code>, see the following:</p> <p><a href="https://i.stack.imgur.com/dASk8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dASk8.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T21:34:00.813", "Id": "397858", "Score": "2", "body": "Why do you redefine `sys.stdout` during the database operations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T21:36:01.397", "Id": "397859"...
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li>A linter (or two) such as pycodestyle or flake8 will help you write more idiomatic Python. For example, brackets are not required around an <code>if</code> statement.</li>\n<li>You can use <code>query_posts_response.json()</code> to easily get JSON response conte...
{ "AcceptedAnswerId": "206229", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T21:10:48.437", "Id": "206226", "Score": "0", "Tags": [ "python", "beginner", "json", "rest", "odbc" ], "Title": "Python script to query REST API and write to database" }
206226
<p>The data describes cycling activities (<code>key1</code>) and chunks of them (<code>key2</code>). In total there are around 1,000 <code>key1</code> objects and arrays under <code>key1</code> are 1-100 long.</p> <ul> <li>Is there a simpler, more semantic, faster, or otherwise better way than to use two nested map in step 1?</li> <li>I realise that step 3 is longer than it should be and there has to be a better way to do it. How can step 3 be improved?</li> </ul> <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>// Original array const arr = [ {key1: [{key2: {id: 1, name: 'a'}}]}, {key1: [{key2: {id: 2, name: 'b'}}]}, {key1: [{key2: {id: 2, name: 'b'}}, {key2: {id: 3, name: 'c'}}]} ]; console.log(arr); // Step 1: Extract meaningful information from original array const arrOfArrOfObj = arr .map(category =&gt; category.key1 .map(subCategory =&gt; ( { id: subCategory.key2.id, name: subCategory.key2.name } ) ) ); console.log(arrOfArrOfObj); // Step 2: Make the array one dimensional const arrOfObj = [].concat(...arrOfArrOfObj); console.log(arrOfObj); // Step 3: Remove duplicates and count object occurrences. let dedupedArrWithCount = []; l = arrOfObj.length; for (let i = 0; i &lt; l; i++) { let objExists = false; for (let j = 0; j &lt; dedupedArrWithCount.length; j++) { // Two objects are identical if their ids are identical. if (arrOfObj[i].id === dedupedArrWithCount[j].id) { objExists = true; dedupedArrWithCount[j].count += 1; } } if (!objExists) { dedupedArrWithCount.push({ id: arrOfObj[i].id, name: arrOfObj[i].name, count: 1 }) } } console.log(dedupedArrWithCount);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T21:42:10.130", "Id": "397861", "Score": "1", "body": "what does this data describe? will there always be two levels or might there ever be 3 or more?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T21...
[ { "body": "<h2>Responding to your questions</h2>\n\n<blockquote>\n <p><em>“Is there a simpler, more semantic, faster, or otherwise better way than to use two nested map in step 1?”</em></p>\n</blockquote>\n\n<p>While I like the benefits of functional approaches, they are often slower because of the extra funct...
{ "AcceptedAnswerId": "206735", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T21:24:18.103", "Id": "206227", "Score": "2", "Tags": [ "javascript", "beginner", "array", "functional-programming", "ecmascript-6" ], "Title": "Manipulating arrays to extract unique objects and count occurrences" }
206227
<p>Over on EL&amp;U Meta, someone raised the question of <a href="https://english.meta.stackexchange.com/questions/11802/does-ell-migrate-questions-to-elu">how many net migrations there are to/from our sister site</a>, ELL.</p> <p>The following SEDE query calculates the net migrations by quarter (<code>elu2ell - ell2elu</code>). You can <a href="https://data.stackexchange.com/english/query/916415/migrations-analysis" rel="nofollow noreferrer">play with the query in SEDE</a> here.</p> <pre><code>-- migration prefix length DECLARE @mhpl INT, @mapl INT, @mhid INT, @maid INT; SELECT @mhid = Id from PostHistoryTypes where Name = N'Post Migrated Here' SELECT @maid = Id from PostHistoryTypes where Name = N'Post Migrated Away' -- Create copy of PostHistory table with -- all the posts migrated here from other sites SELECT * INTO #ph FROM posthistory WHERE PostHistoryTypeId in (@mhid, @maid) -- Add "migration direction" column ALTER TABLE #ph ADD mDir CHAR(1) NULL; UPDATE #ph SET mDir = '&lt;' WHERE PostHistoryTypeId=@mhid UPDATE #ph SET mDir = '&gt;' WHERE PostHistoryTypeId=@maid -- Add column for site where question was migrated from ALTER TABLE #ph ADD mSite varchar(255) NULL; -- Parse migration source site from comment field -- and put into column SET @mhpl = LEN(N'from http://') SET @mapl = LEN(N'to http://' ) UPDATE #ph SET mSite = replace( CASE WHEN mDir = N'&lt;' THEN substring( COMMENT, @mhpl, charindex('.',COMMENT,@mhpl) - @mhpl ) ELSE substring( COMMENT, @mapl, charindex('.',COMMENT,@mapl) - @mapl ) END, N'/', '' ) -- Add calendar quarter column column for site where question was migrated from ALTER TABLE #ph ADD CalendarQuarter CHAR( 7 ) NULL; -- LEN(N'FYXXQYY') UPDATE #ph SET CalendarQuarter = N'FY' + RIGHT( CAST( YEAR(CreationDate) AS CHAR(4) ), 2 ) + N'Q' + CAST( CEILING( CAST( MONTH(CreationDate) AS DECIMAL(4,2) ) / 3 ) AS char(1) ) SELECT CalendarQuarter, SUM(CASE WHEN mDir='&gt;' THEN 1 ELSE 0 END) as Departing, SUM(CASE WHEN mDir='&lt;' THEN 1 ELSE 0 END) as Arriving, SUM(CASE WHEN mDir='&lt;' THEN 1 ELSE -1 END) as NetDepatures FROM #ph WHERE mSite='ell' GROUP BY CalendarQuarter ORDER BY CalendarQuarter DESC </code></pre> <p>I've used SQL here and there in my professional career, but I'm far from an expert. I'd like commentary on the overall query, structure, organization, style. Particular areas of concern:</p> <ul> <li>The duplication of the <code>charindex('.',COMMENT,@mhpl) - @mhpl</code> logic in the migration-site parsing <code>UPDATE</code> statement bugs me, </li> <li>as does the general verbosity and complexity of the <code>CalendarQuarter</code>-formatting code.</li> <li>You'll also see I use vertical indentation for most deeply-nested function calls. Is this normal or useful practice for complicated SQL queries? If not, how do you help the reader visually parse deeply-nested parens, without wasting so much real estate?</li> </ul> <p>Beyond that, performance optimizations are nice, but it's a small enough dataset that it doesn't matter that much. </p> <p>A final issue is I worry that the way I've structured the temp table will limit more general analysis to other (non-ELL) sites and over different time horizons, in particular by adding an explicit <code>CalendarQuarter</code> column.</p> <p>I'd like to do that dynamically for the sake of the final query (where I do want quarterly figures), but I found it difficult to both dynamically calculate that column as well <code>GROUP BY</code> it. </p> <p>So, if there's a way to structure the final table that makes future, more general analytics easier, that would be useful feedback.</p> <hr> <p><sub> I am also suspicious of the PostHistory table and whether I can rely on <code>PostHistoryTypeId in [35, 36]</code> to reliably tell me that a question was migrated. But this is CR, not SO, so let's assume the logic is correct, and focus on the code as code.</sub></p> <p><sub>In re: future extensions, I am aware that meta sites in general will not be categorized properly, as they all collapse down to <code>meta</code> before <a href="https://meta.stackexchange.com/questions/292058/network-wide-https-its-time">Great HTTPs Migration</a>, and are counted among the normal site migrations after it (i.e. <code>english.meta.stackexchange</code> and <code>english.stackexchange</code> both map to <code>english</code> now). But meta-migrations are rare enough for my purposes that I can ignore them. Nor am I concerned with hypothetical migrations to non-<code>*.stackexchange.com</code> sites (like the original trilogy). That won't happen for EL&amp;U.</sub></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T08:22:38.590", "Id": "397905", "Score": "0", "body": "Thanks for this great question - I hope you get some good reviews, and I hope to see more of your contributions here in future!" }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<blockquote>\n<p>I'd like commentary on the overall query, structure, organization, style.</p>\n</blockquote>\n<p>The query is consistent for style. Its structure and organization seems to match the functional decomposition you did to achieve the desired result.</p>\n<p>While the use of a temporary t...
{ "AcceptedAnswerId": "226527", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T23:58:28.623", "Id": "206232", "Score": "5", "Tags": [ "sql", "stackexchange" ], "Title": "SEDE query to calculate net migrations quarterly from ELU to ELL" }
206232
<p>Question:</p> <blockquote> <p>Implement a trie with insert, search, and startsWith methods.</p> </blockquote> <p>Source:</p> <blockquote> <p><a href="https://leetcode.com/problems/implement-trie-prefix-tree/description/" rel="noreferrer">https://leetcode.com/problems/implement-trie-prefix-tree/description/</a></p> </blockquote> <p>The Trie object will be instantiated and called as such:</p> <pre><code>obj = Trie() obj.insert(word) param_2 = obj.search(word) param_3 = obj.startsWith(prefix) </code></pre> <p>Code: I have a <code>TrieNode</code> class and a <code>Trie</code> class. I'm not sure if I can make my code more pythonic. I ran the code on leetcode and it passed all the testcases.</p> <pre><code>class TrieNode: def __init__(self): self.children = [0]*26 self.end = False def put(self, ch): self.children[ord(ch)-ord('a')] = TrieNode() def get(self, ch): return self.children[ord(ch)-ord('a')] def contains_key(self, ch): return self.children[ord(ch)-ord('a')] != 0 def set_end(self): self.end = True def is_end(self): return self.end class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ curr = self.root for i in range(len(word)): if not curr.contains_key(word[i]): curr.put(word[i]) curr = curr.get(word[i]) curr.set_end() def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ curr = self.root for i in range(len(word)): if not curr.contains_key(word[i]): return False curr = curr.get(word[i]) return True if curr.is_end() else False def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ curr = self.root for i in range(len(prefix)): if not curr.contains_key(prefix[i]): return False curr = curr.get(prefix[i]) return True </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T08:49:35.680", "Id": "397912", "Score": "2", "body": "Welcome to Code Review. This is a really good first submission." } ]
[ { "body": "<h2><code>for</code> with <code>range</code> and <code>len</code></h2>\n\n<p>This is one of the most common things to be seen in python code to someone that isn't very familiar to python, however it's not Pythonic and almost always the wrong way to do it.</p>\n\n<p>Firstly if you are not using the in...
{ "AcceptedAnswerId": "206268", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-25T00:32:13.243", "Id": "206234", "Score": "7", "Tags": [ "python", "algorithm", "trie" ], "Title": "Implementing a Trie in Python" }
206234