body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I was looking for a similar JavaScript method for <a href="http://php.net/manual/en/function.http-build-query.php" rel="nofollow noreferrer"><code>http_build_query</code></a> but did not find but create my own and here I am a bit confused to decide the right approach.</p> <p>Here is the problem. I have an object of params and need to create query string to append with URL with help of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow noreferrer"><code>encodeURIComponent</code></a>:</p> <pre><code>const params = { "name": ["alpha &amp;", "beta"], "id": ["one", "&amp;two=2"], "from": 1533735971000, "to": 1533822371147, "status": true }; </code></pre> <p>Now there are two approaches when there is an array of strings are there. I name them <code>pre-encode</code> and <code>post-encode</code> for now.</p> <h1><code>pre-encode</code></h1> <p>Apply <code>encodeURIComponent</code> to individual items and then join all items.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const params = { "name": ["alpha &amp;", "beta"], "id": ["one", "&amp;two=2"], "from": 1533735971000, "to": 1533822371147, "status": true }; const output = Object.entries(params).map((pair) =&gt; { const [key, val] = pair; if (val instanceof Array &amp;&amp; val.length &gt; 0) { let pre_encode = val.map(encodeURIComponent).join(','); console.log({pre_encode}); const pre_qs = `${encodeURIComponent(key)}=${pre_encode}`; console.log({pre_qs}) return pre_qs; } else { return pair.map(encodeURIComponent).join('='); } }).join('&amp;'); console.log({output});</code></pre> </div> </div> </p> <h3>Output</h3> <blockquote> <p>"name=alpha%20%26,beta&amp;id=one,%26two%3D2&amp;from=1533735971000&amp;to=1533822371147&amp;status=true"</p> </blockquote> <hr> <h1><code>post-encode</code></h1> <p>First, join all items then apply <code>encodeURIComponent</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>const params = { "name": ["alpha &amp;", "beta"], "id": ["one", "&amp;two=2"], "from": 1533735971000, "to": 1533822371147, "status": true }; const output = Object.entries(params).map((pair) =&gt; { const [key, val] = pair; if (val instanceof Array &amp;&amp; val.length &gt; 0) { let post_encode = encodeURIComponent(val.join(',')); console.log({post_encode}); const post_qs = `${encodeURIComponent(key)}=${post_encode}`; console.log({post_qs}) return post_qs; } else { return pair.map(encodeURIComponent).join('='); } }).join('&amp;'); console.log({output});</code></pre> </div> </div> </p> <h3>Output</h3> <blockquote> <p>"name=alpha%20%26%2Cbeta&amp;id=one%2C%26two%3D2&amp;from=1533735971000&amp;to=1533822371147&amp;status=true"</p> </blockquote> <p>Which approach is the more efficient and right and how to handle null and undefined values?</p>
[]
[ { "body": "<h1>Your main question</h1>\n\n<p>I have trouble understanding it, because:</p>\n\n<ul>\n<li><strong>minor reason</strong>:<br>\n(unless I'm missing something obvious) whatever way you encode the array parts, the resulting query string is quite valid in both cases;<br>\nso the only possible criterion...
{ "AcceptedAnswerId": "201435", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T18:35:50.097", "Id": "201316", "Score": "2", "Tags": [ "javascript", "ecmascript-6", "url" ], "Title": "Building query params which append to URL in a browser" }
201316
<p>I'm trying to learn how to program with Java which is more or less my first programming language (had some basic Pascal and C,C++ in school and college) but still a Beginner, with a capital 'B'. </p> <p>Right now I'm working on a mini game, which is similar to the "breakout" game, but it's going to have my own implementation and won't have any blocks to destroy (I know it sounds weird). I have written some core classes, created a field, a pad and a ball. I'd like to get some feedback on my coding: how could I improve my code so it would be easier to implement new features and I'd like to know some of my bad habits that I should try to avoid doing to become good in writing code? </p> <p>Here are my classes that I have already written:</p> <p>Game class:</p> <pre><code>package game; import java.awt.EventQueue; import javax.swing.JFrame; public class Game extends JFrame { public Game(){ Field field = new Field(); setContentPane(field); pack(); setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("BLOCK GAME bETA"); setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(() -&gt; { Game ex = new Game(); ex.setVisible(true); }); } } </code></pre> <p>Field class:</p> <pre><code>package game; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JLabel; public class Field extends JLabel{ //Dimensions of the field. public final int FIELD_HEIGHT = 800; public final int FIELD_WIDTH = 480; //Creates a pad. static Pad pad = new Pad(); //Creates a ball on top of the pad. static Ball ball = new Ball(pad.getPadX(), pad.getPadY()); private Timer timer; //Field constructor, creates a game field. public Field(){ setPreferredSize(new Dimension(FIELD_WIDTH, FIELD_HEIGHT)); setFocusable(true); addKeyListener(new Control()); timer = new Timer(); timer.scheduleAtFixedRate(new ScheduleTask(), 100, 20); } //Draws all of the components on the screen. @Override public void paintComponent(Graphics g){ super.paintComponent(g); setOpaque(true); setBackground(new Color(27, 89, 195)); drawFieldLimits(g); drawPad(g); drawBall(g); } private void drawFieldLimits(Graphics g){ // 15 pixel offset from the boarder of the frame. g.drawLine(15, 15, 15, FIELD_HEIGHT - 15); g.drawLine(15, 15, FIELD_WIDTH - 15, 15); g.drawLine(FIELD_WIDTH - 15, 15, FIELD_WIDTH - 15, FIELD_HEIGHT - 15); } private void drawPad(Graphics g){ g.fillRect(pad.getPadX(), pad.getPadY(), pad.getPadWidth(), pad.getPadHeight()); } private void drawBall(Graphics g){ g.fillOval(ball.getBallX(), ball.getBallY(), ball.getBallDiamiter(), ball.getBallDiamiter()); } private class Control extends KeyAdapter{ @Override public void keyReleased(KeyEvent e){ pad.keyReleased(e); } @Override public void keyPressed(KeyEvent e){ pad.keyPressed(e); } } private class ScheduleTask extends TimerTask{ @Override public void run() { pad.movement(); ball.movement(pad.getPadX(), pad.getPadY()); repaint(); } } } </code></pre> <p>Pad class:</p> <pre><code>package game; import java.awt.event.KeyEvent; public class Pad extends Field{ private final int PAD_WIDTH = 60; private final int PAD_HEIGHT = 10; //Starting point of the pad. private final int INITIAL_X = (FIELD_WIDTH/2) - (PAD_WIDTH/2); private final int INITIAL_Y = FIELD_HEIGHT - PAD_HEIGHT - 10; //Starting speed of the pad, may change during the game. private int initialPadSpeed = 5; private int padSpeed; //Pad position. private int padX, padY; //Constructor public Pad(){ padX = INITIAL_X; padY = INITIAL_Y; } //Defines the movement of the pad. public void movement(){ padX += padSpeed; if(padX &lt;= 15){ padX = 15; } // 15 is the offset. if(padX &gt;= FIELD_WIDTH - PAD_WIDTH - 15){ padX = FIELD_WIDTH - PAD_WIDTH - 15; } } //Getters. public int getPadX(){ return padX; } public int getPadY(){ return padY; } public int getPadWidth(){ return PAD_WIDTH; } public int getPadHeight(){ return PAD_HEIGHT; } //Action events used to move the pad left and right. public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_LEFT){ padSpeed = -initialPadSpeed; } if(e.getKeyCode() == KeyEvent.VK_RIGHT){ padSpeed = initialPadSpeed; } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { padSpeed = 0; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { padSpeed = 0; } } } </code></pre> <p>Ball class: </p> <pre><code>package game; public class Ball extends Pad{ //Variables that define the ball. private int ballX, ballY; private int initialBallSpeedVertical = 2; private int initialBallSpeedHorizontal = 2; private int ballSpeedVertical, ballSpeedHorizontal; private int ballDiameter = 10; //Constructor that has pad position coordinates as parameters, so the ball will be created on the pad. public Ball(int x, int y) { ballX = x + 30; // + pad width so the ball is at the middle of the pad. ballY = y; ballSpeedVertical = initialBallSpeedVertical; ballSpeedHorizontal = initialBallSpeedHorizontal; } //Defines how the ball moves during the game. Consists pad position coordinates //so the ball could bounce of the pad. public void movement(int padX, int padY){ ballX -= ballSpeedHorizontal; ballY -= ballSpeedVertical; if(ballX &lt;= 15){ ballSpeedHorizontal =-ballSpeedHorizontal; } if(ballX &gt;= FIELD_WIDTH - ballDiameter - 15){ ballSpeedHorizontal = ballSpeedHorizontal =-ballSpeedHorizontal; } if(ballY &lt;= 15){ ballSpeedVertical = -ballSpeedVertical; } if(ballY &gt;= FIELD_HEIGHT - ballDiameter){ ballSpeedHorizontal = 0; ballSpeedVertical = 0; } //Bouncing of the pad. if((ballX &gt;= getPadX() &amp;&amp; (ballX &lt;= padX + getPadWidth()) &amp;&amp; (ballY &gt;= padY))){ ballSpeedVertical = -ballSpeedVertical; } } //Getters. public int getBallX(){ return ballX; } public int getBallY(){ return ballY; } public int getBallDiamiter(){ return ballDiameter; } } </code></pre> <p>I'd also like to add that I have written this using numerous of online tutorials as an examples and help. I'd also like to know why I get <code>StackOverflowError</code> if I don't assign pad and ball objects as static in Field class because it worked for people who wrote tutorials that I was using?</p> <p>Also, I know that I could have made some variables <code>final</code> but I think they might be changeable on the future versions of the game (e.g. the ones that determine pad and ball speed).</p> <p>Also, feel free to bash me for my beginner skills (or lack of them) and don't be afraid of giving me some harsh criticism. Any feedback with coding advice will be much appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T19:22:02.543", "Id": "387704", "Score": "0", "body": "Please put notes at the top, so people see them when they first open the question. Unless it is a footnote, of course." }, { "ContentLicense": "CC BY-SA 4.0", "Creati...
[ { "body": "<p>First, the small stuff.</p>\n\n<ul>\n<li><p><code>getBallDiamiter</code> has a misspelling.</p></li>\n<li><p><code>movement</code> kinda sucks as a method name. <code>move</code> would be better, but makes <code>ball.move(30, 100)</code> a bit ambiguous. </p></li>\n<li><p>It's better if classes th...
{ "AcceptedAnswerId": "201422", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T18:48:26.873", "Id": "201317", "Score": "2", "Tags": [ "java", "beginner", "game" ], "Title": "Breakout-style game" }
201317
<p>I am using a toolbar button to present a modal view controller (in which I let the user export data as a PDF file). The main section of my app is a <code>UITableViewController</code> subclass embedded in a <code>UINavigationController</code>.</p> <p>Here is a schematic of my layout.</p> <p><a href="https://i.stack.imgur.com/rzBGI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rzBGI.jpg" alt="Schematic of my storyboard layout"></a></p> <p>The modal itself is embedded in a <code>UINavigationController</code> as I need it to have a bottom toolbar. It also has a transparent background and is presented using <code>.overCurrentContext</code>, so the main screen of the user's data blurs underneath. </p> <p>I found that to get it to <em>float</em> over everything else (including the navigation bar etc), I had to present it from the <code>UINavigationController</code> (otherwise the main navigation bar and toolbar appeared on top of it). The problem with this is that the <code>UITableViewController</code> method <code>prepare(for:sender:)</code> is not called.</p> <p>I call the segue to the modal view controller like this (from the <code>UITableViewController</code> subclass):</p> <pre><code>// User taps EXPORT button @objc func exportButtonTapped(_ sender: UIBarButtonItem) { self.navigationController?.performSegue(withIdentifier: "showExport", sender: nil) } </code></pre> <p>In order to transfer the array of user data to the modal view controller, I have called the following code in the <em>modal</em> view controller:</p> <pre><code>override func viewDidLoad() { super.viewDidLoad() // Get data from array in main table view controller let masterNav = navigationController?.presentingViewController as! UINavigationController let myTableVC = masterNav.topViewController as! MyTableViewController self.userData = myTableVC.userData // This is of type: [MyObject] } </code></pre> <p>The data is then rendered to a PDF (using HTML templating) in the modal view controller's <code>viewWillAppear()</code> method. This works as expected.</p> <p>However, I have some concerns about doing it this way:</p> <ol> <li>Is it guaranteed that <code>viewDidLoad()</code> will finish before <code>viewWillAppear()</code> is called? Will an even a larger data set be available for rendering as PDF in <code>viewWillAppear()</code>?</li> <li>Is it acceptable to present modally from the <code>UINavigationController</code>?</li> <li>Should I be subclassing the main <code>UINavigationController</code> and using its <code>prepare(for:sender:)</code> method (if this is even an option)?</li> <li>In the <code>performSegue(withIdentifier:sender:)</code> method, does the sender argument make any difference?</li> <li>Is it preferable to use <code>present()</code> rather than a segue?</li> </ol> <p>I would of course be grateful for any other advice or refinements to the code. It seems to work as expected but I just want to make sure I following best practice as far as possible.</p>
[]
[ { "body": "<blockquote>\n <p>Is it guaranteed that viewDidLoad() will finish before viewWillAppear() is called? Will an even a larger data set be available for rendering as PDF in viewWillAppear()?</p>\n</blockquote>\n\n<p>Yes. It needs to be loaded before it will appear.</p>\n\n<blockquote>\n <p>Is it accept...
{ "AcceptedAnswerId": "202952", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T19:18:07.993", "Id": "201320", "Score": "3", "Tags": [ "swift", "ios", "cocoa-touch" ], "Title": "Presenting and passing data to a modal view controller without using prepare(for:sender:) method" }
201320
<p>I had 15 minutes to code the following question:</p> <p>Given a file name return the char which appears maximal number of times.</p> <p>please do not take into account the unit test. Please look at the final foreach loop, I could have also used a for loop, I have doubts what is the best way to implement finding a max value and get the key from the dictionary.</p> <p>Also please comment about code style. Thanks</p> <pre><code>using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace JobInterviewTests { [TestClass] public class GetMostRepeatedCharQuestion { [TestMethod] public void TestForAasMax() { char result = GetMaxCharHelper.GetMaxReaptedCharFromFile("MaxA.txt"); Assert.AreEqual('A', result); } } public class GetMaxCharHelper { public static char GetMaxReaptedCharFromFile(string fileName) { Dictionary&lt;char, int&gt; charToCount = new Dictionary&lt;char, int&gt;(); using (var streamReader = new StreamReader(fileName)) { string line = streamReader.ReadLine(); while (line != null) { char[] charArray = line.ToCharArray(); foreach (var currentChar in charArray) { if (charToCount.ContainsKey(currentChar)) { charToCount[currentChar]++; } else { charToCount.Add(currentChar, 1); } } //don't forget to get next line when reading from a file line = streamReader.ReadLine(); } int maxCount = 0; char maxChar = '\0'; foreach (var current in charToCount) { if (current.Value &gt; maxCount) { maxCount = current.Value; maxChar = current.Key; } } return maxChar; } } } } </code></pre>
[]
[ { "body": "<p>Assuming modern C#, there are a couple of things you could do to be more concise:</p>\n\n<ol>\n<li><p>Instead of the dance with <code>while((line = reader.NextLine())...)</code> you can just use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readlines\" rel=\"nofollow norefer...
{ "AcceptedAnswerId": "201333", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T20:31:21.467", "Id": "201324", "Score": "6", "Tags": [ "c#", "interview-questions" ], "Title": "Find char which appears maximal number of times" }
201324
<p>I was solving this problem for implementing <code>LinkedList</code> and <code>ListNode</code> classes, and <code>Insert</code> and <code>Remove</code> methods for <code>LinkedList</code>. I was wondering if I can get any code review and feedback.</p> <pre><code>class ListNode: def __init__(self, value=None): self.value = value self.next = None self.prev = None def __repr__(self): """Return a string representation of this node""" return 'Node({})'.format(repr(self.value)) class LinkedList(object): def __init__(self, iterable=None): """Initialize this linked list and append the given items, if any""" """Best case Omega(1)""" """Worst case O(n)""" self.head = None self.tail = None self.size = 0 self.length = 0 if iterable: for item in iterable: self.append(item) def __repr__(self): """Return a string representation of this linked list""" # this actually helps me to see what's inside linkedList return 'LinkedList({})'.format(self.as_list()) def setHead(self,head): self.head = head def getNext(self): return self.next def setNext(self,next): self.next = next def size(self): """ Gets the size of the Linked List AVERAGE: O(1) """ return self.count def as_list(self): """Return a list of all items in this linked list""" items = [] current = self.head while current is not None: items.append(current.value) current = current.next return items def append(self, item): new_node = ListNode(item) if self.head is None: self.head = new_node # Otherwise insert after tail node else: self.tail.next = new_node # Update tail node self.tail = new_node # Update length self.size += 1 def get_at_index(self, index): """Return the item at the given index in this linked list, or raise ValueError if the given index is out of range of the list size. Best case running time: O(1) if it's head or no value, Worst case running time: O(n) if it's in the tail [TODO]""" if not (0 &lt;= index &lt; self.size): raise ValueError('List index out of range: {}'.format(index)) counter = self.head for i in range(index): counter = counter.next return counter.value def prepend(self, item): """Insert the given item at the head of this linked list""" """Best case Omega(1)""" """Worst case O(1)""" new_node = ListNode(item) # Insert before head node new_node.next = self.head # Update head node self.head = new_node # Check if list was empty if self.tail is None: self.tail = new_node # Update length self.size += 1 def insert(self, value, index): """ Inserts value at a specific index BEST: O(1) WORST: O(i -1) """ if not (0 &lt;= index &lt;= self.size): raise ValueError('List index out of range: {}'.format(index)) node = ListNode(value) prev = self.get_at_index(index) if index == 0: self.append(value) elif index == self.size: self.append(value) else: new_node = ListNode(value) node = self.head previous = None for i in range(index): previous = node node = node.next previous.next = new_node new_node.next = node self.size += 1 def remove(self, index): """Best case Omega(1)""" """Worst case O(n)""" previous = None current = self.head while current is not None: if current.value == self.get_at_index(index): if current is not self.head and current is not self.tail: previous.next = current.next if current is self.head: self.head = current.next if current is self.tail: if previous is not None: previous.next = None self.tail = previous return previous = current current = current.next return -1 def contains(self, value): """Return an item in this linked list if it's found""" """Best case Omega(1)""" """Worst case O(n)""" current = self.head # Start at the head node while current is not None: if value == current.value: return True current = current.next # Skip to the next node return False def test_linked_list(): ll = LinkedList() print(ll) print('Appending items:') ll.append('A') print(ll) ll.append('B') print(ll) ll.append('C') print(ll) print('head: {}'.format(ll.head)) print('testing: Getting items by index:') #ll = LinkedList(['A', 'B', 'C']) print(ll) ll.insert('AA', 0) print(ll) ll.remove(1) print(ll) if __name__ == '__main__': test_linked_list() </code></pre> <p>It also passes all of these tests:</p> <pre><code># ############## TESTING ############### # ########################################################### from io import StringIO import sys # custom assert function to handle tests # input: count {List} - keeps track out how many tests pass and how many total # in the form of a two item array i.e., [0, 0] # input: name {String} - describes the test # input: test {Function} - performs a set of operations and returns a boolean # indicating if test passed # output: {None} def expect(count, name, test): if (count is None or not isinstance(count, list) or len(count) != 2): count = [0, 0] else: count[1] += 1 result = 'false' error_msg = None try: if test(): result = ' true' count[0] += 1 except Exception as err: error_msg = str(err) print(' ' + (str(count[1]) + ') ') + result + ' : ' + name) if error_msg is not None: print(' ' + error_msg + '\n') class Capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) sys.stdout = self._stdout # compare if two flat lists are equal def lists_equal(lst1, lst2): if len(lst1) != len(lst2): return False for i in range(0, len(lst1)): if lst1[i] != lst2[i]: return False return True print('ListNode Class') test_count = [0, 0] def test(): node = ListNode() return isinstance(node, object) expect(test_count, 'able to create an instance', test) def test(): node = ListNode() return hasattr(node, 'value') expect(test_count, 'has value property', test) def test(): node = ListNode() return hasattr(node, 'next') expect(test_count, 'has next property', test) def test(): node = ListNode() return node is not None and node.value is None expect(test_count, 'has default value set to None', test) def test(): node = ListNode(5) return node is not None and node.value == 5 expect(test_count, 'able to assign a value upon instantiation', test) def test(): node = ListNode() node.value = 5 return node is not None and node.value == 5 expect(test_count, 'able to reassign a value', test) def test(): node1 = ListNode(5) node2 = ListNode(10) node1.next = node2 return (node1 is not None and node1.next is not None and node1.next.value == 10) expect(test_count, 'able to point to another node', test) print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n') print('LinkedList Class') test_count = [0, 0] def test(): linked_list = LinkedList() return isinstance(linked_list, object) expect(test_count, 'able to create an instance', test) def test(): linked_list = LinkedList() return hasattr(linked_list, 'head') expect(test_count, 'has head property', test) def test(): linked_list = LinkedList() return hasattr(linked_list, 'tail') expect(test_count, 'has tail property', test) def test(): linked_list = LinkedList() return hasattr(linked_list, 'length') expect(test_count, 'has length property', test) def test(): linked_list = LinkedList() return linked_list is not None and linked_list.head is None expect(test_count, 'default head set to None', test) def test(): linked_list = LinkedList() return linked_list is not None and linked_list.tail is None expect(test_count, 'default tail set to None', test) def test(): linked_list = LinkedList() return linked_list is not None and linked_list.length == 0 expect(test_count, 'default length set to 0', test) print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n') print('LinkedList Contains Method') test_count = [0, 0] def test(): linked_list = LinkedList() return (hasattr(linked_list, 'contains') and callable(getattr(linked_list, 'contains'))) expect(test_count, 'has contains method', test) def test(): linked_list = LinkedList() linked_list.append(5) linked_list.append(10) linked_list.append(15) return linked_list.contains(15) is True expect(test_count, 'returns True if linked list contains value', test) def test(): linked_list = LinkedList() linked_list.append(5) linked_list.append(10) linked_list.append(15) return linked_list.contains(8) is False expect(test_count, 'returns False if linked list contains value', test) print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n') </code></pre>
[]
[ { "body": "<p>use \"\"\" \"\"\" instead of multiple \"\"\"</p>\n\n<p>from</p>\n\n<pre><code> \"\"\"Initialize this linked list and append the given items, if any\"\"\"\n \"\"\"Best case Omega(1)\"\"\"\n \"\"\"Worst case O(n)\"\"\"\n</code></pre>\n\n<p>to</p>\n\n<pre><code> \"\"\"\n Initialize thi...
{ "AcceptedAnswerId": "201359", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T20:34:25.690", "Id": "201325", "Score": "5", "Tags": [ "python", "algorithm", "programming-challenge", "unit-testing", "linked-list" ], "Title": "LinkedList class implementation in Python" }
201325
<p>I was asked to complete the task described below:</p> <blockquote> <p>Event Emitters are objects that serve as the core building block in event-driven architectures. They simplify the process of handling asynchronous events and enable clean and decoupled code.</p> <p>Create an Event Emitter module in JavaScript (as modern of a version as you prefer) with documentation and tests. Your implementation should allow for:</p> <ul> <li>Emitting named events with any number of arguments.</li> <li>Registering handler functions for named events that are passed the appropriate arguments on emission.</li> <li>Registering a "one-time" handler that will be called at most one time.</li> <li>Removing specific previously-registered event handlers and/or all previously-registered event handlers.</li> </ul> <p>This module should be suitable for publishing to npm, though it is not necessary for you to do so.</p> <p>Do not subclass or otherwise require an existing Event Emitter module, and do not include any dependencies apart from testing or development dependencies.</p> </blockquote> <p>Below is the module I created, as well as the unit tests I developed as I created the module. It is similar to the <a href="https://nodejs.org/api/events.html" rel="nofollow noreferrer">NodeJS Event Emitter API</a> but obviously not as complex. </p> <p>How does the module and test code look? What would you recommend be done differently?</p> <h3>Emitter module:</h3> <pre class="lang-js prettyprint-override"><code>"use strict"; function Emitter() { //constructor this.eventHandlers = {}; } /** * Emit an event * @param event string * @param arg1...argN - any arguments to be sent to callback functions */ Emitter.prototype.emit = function(event) { const args = Array.from(arguments).slice(1); if (this.eventHandlers.hasOwnProperty(event)) { let indexesToRemove = []; for (const index in this.eventHandlers[event]) { const handler = this.eventHandlers[event][index]; handler.callback.apply(null, args); if (handler.hasOwnProperty('once')) { indexesToRemove.push(index); } } if (indexesToRemove.length) { for(const index in indexesToRemove) { this.eventHandlers[event].splice(index, 1); } } } }; /** * Register a callback for an event * @param event * @param callback */ Emitter.prototype.on = function(event, callback) { addHandler.call(this, event, {callback: callback}); }; /** * Register a callback for an event to be called only once * @param event * @param callback */ Emitter.prototype.once = function(event, callback) { addHandler.call(this, event, {callback: callback, once: true}); }; /** * Un-register a single or all callbacks for a given event * @param event * @param callback optional */ Emitter.prototype.off = function(event, callback) { if (this.eventHandlers.hasOwnProperty(event)) { if (callback !== undefined) { for (const index in this.eventHandlers[event]) { if (callback.toString() == this.eventHandlers[event][index].callback.toString()) { this.eventHandlers[event].splice(index, 1); } } } else { delete this.eventHandlers[event]; } } } module.exports = Emitter; /** * Helper function to add an event handler * @param event * @param handlerObject */ function addHandler(event, handlerObject) { if (!(event in this.eventHandlers)) { this.eventHandlers[event] = []; } this.eventHandlers[event].push(handlerObject); } </code></pre> <h3>Unit tests</h3> <pre class="lang-js prettyprint-override"><code>const EventEmitter = require("../src/"); const chai = require("chai"); const sinon = require('sinon'); const sinonChai = require("sinon-chai"); chai.should(); chai.use(sinonChai); describe("Event Emitter", function() { let emitter; before(function() { emitter = new EventEmitter(); }); it("Allows registering handler functions for named events that are passed the appropriate arguments on emission.", function() { const callback = sinon.fake(); emitter.on('scrape', callback); emitter.emit('scrape'); callback.should.have.been.called; const testValue1 = 'testValue1'; emitter.emit('scrape', testValue1); callback.should.have.been.calledWith(testValue1); const multiArgs = ['a', 'scraped', 'value']; emitter.emit('scrape', ...multiArgs); callback.should.have.been.calledWith(...multiArgs); }); it("Allows Registering a \"one-time\" handler that will be called at most one time.", function() { const callback = sinon.fake(); const callback2 = sinon.fake(); emitter.once('pull', callback); emitter.on('pull', callback2); emitter.emit('pull'); emitter.emit('pull'); callback.should.have.been.calledOnce; callback2.should.have.been.calledTwice; }); it("Allows Removing specific previously-registered event handlers and/or all previously-registered event handlers.", function() { const callback = sinon.fake(); const callback2 = sinon.fake(); const callback3 = sinon.fake(); const callback4 = sinon.fake(); emitter.on('push', callback); emitter.on('push', callback2); emitter.off('push', callback); emitter.emit('push'); callback.should.not.have.been.called; callback2.should.have.been.called; emitter.on('push', callback3); emitter.off('push'); emitter.emit('push'); emitter.on('unshift', callback4); emitter.emit('unshift'); callback3.should.not.have.been.called; callback4.should.have.been.called; }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T21:01:40.427", "Id": "387727", "Score": "0", "body": "That, ladies and gentelmen, is how you ask a question. *claps*" } ]
[ { "body": "<h1>Caveats of <code>{}</code></h1>\n\n<p>In JavaScript <code>{}</code> is often used as a map with user provided values being object property names. This can be a recipe for disaster. See this particular piece of code, that results in error:</p>\n\n<pre><code>var ev = new Emitter();\n\nev.once(\"toS...
{ "AcceptedAnswerId": "201486", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T20:36:50.997", "Id": "201326", "Score": "5", "Tags": [ "javascript", "reinventing-the-wheel", "ecmascript-6", "event-handling", "callback" ], "Title": "Event emitter npm module" }
201326
<p><code>position: sticky;</code> elements are sticky within the bounding box of their direct parent containers. I wanted to make a stickily-positioned button that sticks to the bottom of the viewport, not its parent. So here's what I did:</p> <pre><code>#container { position: relative; top: -99999px; margin-bottom: -99999px; pointer-events: none; } #offset { height: 99999px; } #button { position: sticky; bottom: 1rem; z-index: 99999; pointer-events: initial; } #unoffset { font-size: 1px; } </code></pre> <pre><code>&lt;div&gt; CONTENT CONTENT CONTENT &lt;div id=&quot;container&quot;&gt; &lt;div id=&quot;offset&quot;&gt;&lt;/div&gt; &lt;button id=&quot;button&quot;&gt;BUTTON&lt;/button&gt; &lt;/div&gt; &lt;div id=&quot;unoffset&quot;&gt;&amp;nbsp;&lt;/div&gt; &lt;/div&gt; CONTENT CONTENT CONTENT </code></pre> <p><code>#unoffset</code> is a dummy element for stopping margin-collapse because <code>#container</code> is at the end of its parent.</p> <p>Anyway, this whole solution seems too &quot;hacky.&quot; Is there a better way?</p> <hr /> <h2>Working Example</h2> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { position: relative; top: -99999px; margin-bottom: -99999px; pointer-events: none; } #offset { height: 99999px; } #button { position: sticky; bottom: 1rem; z-index: 99999; pointer-events: initial; } #unoffset { font-size: 1px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; How did I get into this mess? I really don't know how. We seem to be made to suffer. It's our lot in life. I've got to rest before I fall apart. My joints are almost frozen. What a desolate place this is. Where are you going? Well, I'm not going that way. It's much too rocky. This way is much easier. What makes you think there are settlements over there? Don't get technical with me. What mission? What are you talking about? I've had just about enough of you! Go that way! You'll be malfunctioning within a day, you nearsighted scrap pile! And don't let me catch you following me begging for help, because you won't get it. No more adventures. I'm not going that way. Stand by, Chewie, here we go. Cut in the sublight engines. What the...? Aw, we've come out of hyperspace into a meteor shower. Some kind of asteroid collision. It's not on any of the charts. What's going on? Our position is correct, except...no, Alderaan! What do you mean? Where is it? Thats what I'm trying to tell you, kid. It ain't there. It's been totally blown away. What? How? Destroyed...by the Empire! I can't abide these Jawas. Disgusting creatures. Go on, go on. I can't understand how we got by those troopers. I thought we were dead. The Force can have a strong influence on the weak-minded. You will find it a powerful ally. Do you really think we're going to find a pilot here that'll take us to Alderaan? Well, most of the best freighter pilots can be found here. Only watch your step. This place can be a little rough. I'm ready for anything. Come along, Artoo. Didn't we just leave this party? What kept you? We ran into some old friends. Is the ship all right? Seems okay, if we can get to it. Just hope the old man got the tractor beam out of commission. Look! Come on, Artoo, we're going! Now's our chance! Go! No! Come on! Come on! Luke, its too late! Blast the door! Kid! Obi-Wan Kenobi...Obi-Wan? How did I get into this mess? I really don't know how. We seem to be made to suffer. It's our lot in life. I've got to rest before I fall apart. My joints are almost frozen. What a desolate place this is. Where are you going? Well, I'm not going that way. It's much too rocky. This way is much easier. What makes you think there are settlements over there? Don't get technical with me. What mission? What are you talking about? I've had just about enough of you! Go that way! You'll be malfunctioning within a day, you nearsighted scrap pile! And don't let me catch you following me begging for help, because you won't get it. No more adventures. I'm not going that way. Stand by, Chewie, here we go. Cut in the sublight engines. What the...? Aw, we've come out of hyperspace into a meteor shower. Some kind of asteroid collision. It's not on any of the charts. What's going on? Our position is correct, except...no, Alderaan! What do you mean? Where is it? Thats what I'm trying to tell you, kid. It ain't there. It's been totally blown away. What? How? Destroyed...by the Empire! I can't abide these Jawas. Disgusting creatures. Go on, go on. I can't understand how we got by those troopers. I thought we were dead. The Force can have a strong influence on the weak-minded. You will find it a powerful ally. Do you really think we're going to find a pilot here that'll take us to Alderaan? Well, most of the best freighter pilots can be found here. Only watch your step. This place can be a little rough. I'm ready for anything. Come along, Artoo. Didn't we just leave this party? What kept you? We ran into some old friends. Is the ship all right? Seems okay, if we can get to it. Just hope the old man got the tractor beam out of commission. Look! Come on, Artoo, we're going! Now's our chance! Go! No! Come on! Come on! Luke, its too late! Blast the door! Kid! Obi-Wan Kenobi...Obi-Wan? How did I get into this mess? I really don't know how. We seem to be made to suffer. It's our lot in life. I've got to rest before I fall apart. My joints are almost frozen. What a desolate place this is. Where are you going? Well, I'm not going that way. It's much too rocky. This way is much easier. What makes you think there are settlements over there? Don't get technical with me. What mission? What are you talking about? I've had just about enough of you! Go that way! You'll be malfunctioning within a day, you nearsighted scrap pile! And don't let me catch you following me begging for help, because you won't get it. No more adventures. I'm not going that way. Stand by, Chewie, here we go. Cut in the sublight engines. What the...? Aw, we've come out of hyperspace into a meteor shower. Some kind of asteroid collision. It's not on any of the charts. What's going on? Our position is correct, except...no, Alderaan! What do you mean? Where is it? Thats what I'm trying to tell you, kid. It ain't there. It's been totally blown away. What? How? Destroyed...by the Empire! I can't abide these Jawas. Disgusting creatures. Go on, go on. I can't understand how we got by those troopers. I thought we were dead. The Force can have a strong influence on the weak-minded. You will find it a powerful ally. Do you really think we're going to find a pilot here that'll take us to Alderaan? Well, most of the best freighter pilots can be found here. Only watch your step. This place can be a little rough. I'm ready for anything. Come along, Artoo. Didn't we just leave this party? What kept you? We ran into some old friends. Is the ship all right? Seems okay, if we can get to it. Just hope the old man got the tractor beam out of commission. Look! Come on, Artoo, we're going! Now's our chance! Go! No! Come on! Come on! Luke, its too late! Blast the door! Kid! Obi-Wan Kenobi...Obi-Wan? How did I get into this mess? I really don't know how. We seem to be made to suffer. It's our lot in life. I've got to rest before I fall apart. My joints are almost frozen. What a desolate place this is. Where are you going? Well, I'm not going that way. It's much too rocky. This way is much easier. What makes you think there are settlements over there? Don't get technical with me. What mission? What are you talking about? I've had just about enough of you! Go that way! You'll be malfunctioning within a day, you nearsighted scrap pile! And don't let me catch you following me begging for help, because you won't get it. No more adventures. I'm not going that way. Stand by, Chewie, here we go. Cut in the sublight engines. What the...? Aw, we've come out of hyperspace into a meteor shower. Some kind of asteroid collision. It's not on any of the charts. What's going on? Our position is correct, except...no, Alderaan! What do you mean? Where is it? Thats what I'm trying to tell you, kid. It ain't there. It's been totally blown away. What? How? Destroyed...by the Empire! I can't abide these Jawas. Disgusting creatures. Go on, go on. I can't understand how we got by those troopers. I thought we were dead. The Force can have a strong influence on the weak-minded. You will find it a powerful ally. Do you really think we're going to find a pilot here that'll take us to Alderaan? Well, most of the best freighter pilots can be found here. Only watch your step. This place can be a little rough. I'm ready for anything. Come along, Artoo. Didn't we just leave this party? What kept you? We ran into some old friends. Is the ship all right? Seems okay, if we can get to it. Just hope the old man got the tractor beam out of commission. Look! Come on, Artoo, we're going! Now's our chance! Go! No! Come on! Come on! Luke, its too late! Blast the door! Kid! Obi-Wan Kenobi...Obi-Wan? How did I get into this mess? I really don't know how. We seem to be made to suffer. It's our lot in life. I've got to rest before I fall apart. My joints are almost frozen. What a desolate place this is. Where are you going? Well, I'm not going that way. It's much too rocky. This way is much easier. What makes you think there are settlements over there? Don't get technical with me. What mission? What are you talking about? I've had just about enough of you! Go that way! You'll be malfunctioning within a day, you nearsighted scrap pile! And don't let me catch you following me begging for help, because you won't get it. No more adventures. I'm not going that way. Stand by, Chewie, here we go. Cut in the sublight engines. What the...? Aw, we've come out of hyperspace into a meteor shower. Some kind of asteroid collision. It's not on any of the charts. What's going on? Our position is correct, except...no, Alderaan! What do you mean? Where is it? Thats what I'm trying to tell you, kid. It ain't there. It's been totally blown away. What? How? Destroyed...by the Empire! I can't abide these Jawas. Disgusting creatures. Go on, go on. I can't understand how we got by those troopers. I thought we were dead. The Force can have a strong influence on the weak-minded. You will find it a powerful ally. Do you really think we're going to find a pilot here that'll take us to Alderaan? Well, most of the best freighter pilots can be found here. Only watch your step. This place can be a little rough. I'm ready for anything. Come along, Artoo. Didn't we just leave this party? What kept you? We ran into some old friends. Is the ship all right? Seems okay, if we can get to it. Just hope the old man got the tractor beam out of commission. Look! Come on, Artoo, we're going! Now's our chance! Go! No! Come on! Come on! Luke, its too late! Blast the door! Kid! Obi-Wan Kenobi...Obi-Wan? How did I get into this mess? I really don't know how. We seem to be made to suffer. It's our lot in life. I've got to rest before I fall apart. My joints are almost frozen. What a desolate place this is. Where are you going? Well, I'm not going that way. It's much too rocky. This way is much easier. What makes you think there are settlements over there? Don't get technical with me. What mission? What are you talking about? I've had just about enough of you! Go that way! You'll be malfunctioning within a day, you nearsighted scrap pile! And don't let me catch you following me begging for help, because you won't get it. No more adventures. I'm not going that way. Stand by, Chewie, here we go. Cut in the sublight engines. What the...? Aw, we've come out of hyperspace into a meteor shower. Some kind of asteroid collision. It's not on any of the charts. What's going on? Our position is correct, except...no, Alderaan! What do you mean? Where is it? Thats what I'm trying to tell you, kid. It ain't there. It's been totally blown away. What? How? Destroyed...by the Empire! I can't abide these Jawas. Disgusting creatures. Go on, go on. I can't understand how we got by those troopers. I thought we were dead. The Force can have a strong influence on the weak-minded. You will find it a powerful ally. Do you really think we're going to find a pilot here that'll take us to Alderaan? Well, most of the best freighter pilots can be found here. Only watch your step. This place can be a little rough. I'm ready for anything. Come along, Artoo. Didn't we just leave this party? What kept you? We ran into some old friends. Is the ship all right? Seems okay, if we can get to it. Just hope the old man got the tractor beam out of commission. Look! Come on, Artoo, we're going! Now's our chance! Go! No! Come on! Come on! Luke, its too late! Blast the door! Kid! Obi-Wan Kenobi...Obi-Wan? Now thats a name I haven't heard in a long time...a long time. I think my uncle knew him. He said he was dead. Oh, he's not dead, not...not yet. You know him! Well of course, of course I know him. He's me! I haven't gone by the name Obi-Wan since oh, before you were born. Then the droid does belong to you. Don't seem to remember ever owning a droid. Very interesting... I think we better get indoors. The Sandpeople are easily startled but they will soon be back and in greater numbers. Threepio! Where am I? I must have taken a bad step... Can you stand? We've got to get out of here before the Sandpeople return. I don't think I can make it. You go on, Master Luke. There's no sense in you risking yourself on my account. I'm done for. No, you're not. What kind of talk is that? Quickly, son...they're on the move. Don't be too proud of this technological terror you've constructed. The ability to destroy a planet is insignificant next to the power of the Force. Don't try to frighten us with your sorcerer's ways, Lord Vader. Your sad devotion to that ancient religion has not helped you conjure up the stolen data tapes, or given you clairvoyance enough to find the Rebel's hidden fort... I find your lack of faith disturbing. Enough of this! Vader, release him! As you wish. This bickering is pointless. Lord Vader will provide us with the location of the Rebel fortress by the time this station is operational. We will then crush the Rebellion with one swift stroke. Well, that's the trick, isn't it? And it's going to cost you something extra. Ten thousand in advance. Ten thousand? We could almost buy our own ship for that! But who's going to fly it, kid! You? You bet I could. I'm not such a bad pilot myself! We don't have to sit here and listen... We haven't that much with us. But we could pay you two thousand now, plus fifteen when we reach Alderaan. Seventeen, huh! Okay. You guys got yourself a ship. We'll leave as soon as you're ready. Docking bay Ninety-four. Ninety-four. Looks like somebody's beginning to take an interest in your handiwork. All right, we'll check it out. There. You see Lord Vader, she can be reasonable. Continue with the operation. You may fire when ready. What? You're far too trusting. Dantooine is too remote to make an effective demonstration. But don't worry. We will deal with your Rebel friends soon enough. No! Commence primary ignition. Luke? Luke? Luke? Have you seen Luke this morning? He said he had some things to do before he started today, so he left early. Uh? Did he take those two new droids with him? I think so. Well, he'd better have those units in the south range repaired be midday or there'll be hell to pay! Wait, there's something dead ahead on the scanner. It looks like our droid...hit the accelerator. He says it's the best he can do. Since the XP-38 came out, they're just not in demand. It will be enough. If the ship's as fast as he's boasting, we ought to do well. Did you hear that? They've shut down the main reactor. We'll be destroyed for sure. This is madness! We're doomed! There'll be no escape for the Princess this time. What's that? Artoo! Artoo-Detoo, where are you? At last! Where have you been? They're heading in this direction. What are we going to do? We'll be sent to the spice mine of Kessel or smashed into who knows what! Wait a minute, where are you going? This is Chewbacca. He's first-mate on a ship that might suit our needs. I don't like the look of this. Han Solo. I'm captain of the Millennium Falcon. Chewie here tells me you're looking for passage to the Alderaan system. Yes, indeed. If it's a fast ship. Fast ship? You've never heard of the Millennium Falcon? Should I have? It's the ship that made the Kessel run in less than twelve parsecs! I've outrun Imperial starships, not the local bulk-cruisers, mind you. I'm talking about the big Corellian ships now. She's fast enough for you, old man. What's the cargo? Only passengers. Myself, the boy, two droids, and no questions asked. What is it? Some kind of local trouble? Let's just say we'd like to avoid any Imperial entanglements. What is it? I'm afraid I'm not quite sure, sir. He says I found her, and keeps repeating, She's here. Well, who...who has he found? Princess Leia. The princess? She's here? Princess? What's going on? Level five. Detention block A A-twenty-three. I'm afraid she's scheduled to be terminated. Oh, no! We've got to do something. What are you talking about? The droid belongs to her. She's the one in the message.. We've got to help her. Now, look, don't get any funny ideas. The old man wants us to wait right here. But he didn't know she was here. Look, will you just find a way back into the detention block? Here they come! They're coming in too fast! Oooh! We've lost lateral controls. Don't worry, she'll hold together. You hear me, baby? Hold together! Got him! I got him! Great kid! Don't get cocky. There are still two more of them out there! That's it! We did it! We did it! Help! I think I'm melting! This is all your fault. We don't serve their kind here! What? Your droids. They'll have to wait outside. We don't want them here. Listen, why don't you wait out by the speeder. We don't want any trouble. I heartily agree with you sir. Negola dewaghi wooldugger?!? He doesn't like you. I'm sorry. I don't like you either You just watch yourself. We're wanted men. I have the death sentence in twelve systems. I'll be careful than. You'll be dead. This little one isn't worth the effort. Come let me buy you something... Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run. Not a bad bit of rescuing, huh? You know, sometimes I even amaze myself. That doesn't sound too hard. Besides, they let us go. It's the only explanation for the ease of our escape. Easy...you call that easy? Their tracking us! Not this ship, sister. At least the information in Artoo is still intact. What's so important? What's he carrying? The technical readouts of that battle station. I only hope that when the data is analyzed, a weakness can be found. It's not over yet! It is for me, sister! Look, I ain't in this for your revolution, and I'm not in it for you, Princess. I expect to be well paid. I'm in it for the money! You needn't worry about your reward. If money is all that you love, then that's what you'll receive! Her resistance to the mind probe is considerable. It will be some time before we can extract any information from her. The final check-out is complete. All systems are operational. What course shall we set? Perhaps she would respond to an alternative form of persuasion. What do you mean? I think it is time we demonstrate the full power of this station. Set your course for Princess Leia's home planet of Alderaan. With pleasure. We count thirty Rebel ships, Lord Vader. But they're so small they're evading our turbo-lasers! We'll have to destroy them ship to ship. Get the crews to their fighters. Luke, let me know when you're going in. I'm on my way in now... Watch yourself! There's a lot of fire coming from the right side of that deflection tower. I'm on it. Squad leaders, we've picked up a new group of signals. Enemy fighters coming your way. Remember, a Jedi can feel the Force flowing through him. You mean it controls your actions? Partially. But it also obeys your commands. Hokey religions and ancient weapons are no match for a good blaster at your side, kid. You don't believe in the Force, do you? Kid, I've flown from one side of this galaxy to the other. I've seen a lot of strange stuff, but I've never seen anything to make me believe there's one all-powerful force controlling everything. There's no mystical energy field that controls my destiny. It's all a lot of simple tricks and nonsense. I suggest you try it again, Luke. This time, let go your conscious self and act on instinct. With the blast shield down, I can't even see. How am I supposed to fight? Your eyes can deceive you. Don't trust them. &lt;div id="container"&gt; &lt;div id="offset"&gt;&lt;/div&gt; &lt;button id="button"&gt;BUTTON&lt;/button&gt; &lt;/div&gt; &lt;div id="unoffset"&gt;&amp;nbsp;&lt;/div&gt; You must come along now, Artoo. There's really nothing more we can do. And my joints are freezing up. Don't say thing like that! Of course we'll see Master Luke again. He'll be quite all right, you'll see. Stupid little short-circuit. He'll be quite all right. Sir, all the patrols are in. There's still no contact from Skywalker or Solo. Mistress Leia, Artoo says he's been quite unable to pick up any signals, although he does admit that his own range is far too weak to abandon all hope. Your Highness, there's nothing more we can do tonight. The shield doors must be closed. Close the doors. Yes, sir. Yes, that's it. Dagobah. No, I'm not going to change my mind about this. I'm not picking up any cities or technology. Massive life-form readings, though. There's something alive down there... Yes, I'm sure it's perfectly safe for droids. I know, I know! All the scopes are dead. I can't see a thing! Just hang on, I'm going to start the landing cycle... No, Artoo, you stay put. I'll have a look around. What happened? Where? Found him in a junk pile? Oh, what a mess. Chewie, do you think you can repair him? Lando's got people who can fix him. No, thanks. I'm sorry. Am I interrupting anything? Not really. You look absolutely beautiful. You truly belong here with us among the clouds. Thank you. Will you join me for a little refreshment? Everyone's invited, of course. Having trouble with you droid? No. No problem. Why? Oh. No one to meet us. I don't like this. Well, what would you like? Well, they did let us land. Look, don't worry. Everything's going to be fine. Trust me. See? My friend. Keep your eyes open, okay? Why, you slimy, double-crossing, no-good swindler! You've got a lot of guts coming here, after what you pulled. How you doing, you old pirate? So good to see you! Inever thought I'd catch up with you again. Where you been? Steady, Rouge Two Activate harpoon. Good shot, Janson. One more pass. Coming around. Once more. One more. Cable out! Let her go! Detach cable. Cable detached. Come on! Whooha!! That got him! I see it, Wedge. Good work. I don't think we can protect two transports at a time. It's risky, but we can't hold out much longer. We have no choice. Launch patrols. Evacuate remaining ground staff. No, no! No! This one goes there, that one goes there. right? Artoo, you take good care of Master Luke now, understand? And...do take care of yourself. Oh, dear, oh, dear. &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-15T07:43:17.077", "Id": "388450", "Score": "4", "body": "[This question is being discussed on meta](https://codereview.meta.stackexchange.com/q/8939/52915)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-17...
[ { "body": "<p>I had a similar problem and independently came up with a very similar solution, which I suppose at least confirms that this isn't a totally crazy idea. After seeing your solution, I incorporated parts of it into mine.</p>\n\n<p>First, some comments:</p>\n\n<pre class=\"lang-css prettyprint-overrid...
{ "AcceptedAnswerId": "226321", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T20:41:53.280", "Id": "201327", "Score": "3", "Tags": [ "html", "css" ], "Title": "Trick circumvents [position: sticky] restriction to parent" }
201327
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/189590/searching-online-english-dictionaries">Searching online English dictionaries</a>:</p> <pre><code>import webbrowser import random available_dicts = [ ('Merriam-Webster Dictionary', 'https://www.merriam-webster.com/dictionary/', '%20'), ('Oxford Dictionary', 'https://en.oxforddictionaries.com/definition/', '_'), ('Camberidge Dictionary', 'https://dictionary.cambridge.org/dictionary/english/', '-'), ('Collins Dictionary','https://www.collinsdictionary.com/dictionary/english/', '-'), ('Longman Dictionary of Contemporary English', 'https://www.ldoceonline.com/dictionary/', '-'), ('The American Heritage Dictionary of the English Language', 'https://ahdictionary.com/word/search.html?q=', '%20'), ('Almaany English-Arabic Dictionary', 'www.almaany.com/en/dict/ar-en/', '-'), ('Wordreference English-Arabic Dictionary', 'http://www.wordreference.com/enar/', '%20') ] instructions = """ All of the ablove are the available online English dictionaries. To select a dictionary, type its corresponding numeral. To select more than one dictionary, seperate the numerals with ",". To select all of them, type "*". To let the program select a dictionary randomly, type "?". Do not type the quotation marks. Press Enter to exit.\n""" class OnlineDictionary: """Represents an online dictionary. Attributes: name: str representing the dictionary's name url: str representing the URL used to look the query up sep: str used to seperate the parts of the query if there are white spaces between them """ def __init__(self, name, url, sep): """Initializes an OnlineDictionary object. name: str url: str sep: str """ self.name = name self.url = url self.sep = sep def search_for(self, query): """Searches the dictionary for a given query. query: str """ query = self.sep.join(query.split()) query_url = self.url + query webbrowser.open(query_url) def print_data(available_dicts, instructions): """Prints the available dictionaries, their corresponding numerals and the instructions. available_dicts: list of tuples instructions: str """ for numeral, (name, _, _) in enumerate(available_dicts): print(numeral, name) print(instructions) def get_dicts(available_dicts): """Asks the user for which dictionary or dictionaries to use. available_dicts: list of tuples Returns: tuple """ dicts_to_use = input('Specify which dictionary or dictionaries to use.\n') if dicts_to_use == '': exit() elif dicts_to_use == '*': dicts_to_use = available_dicts elif dicts_to_use == '?': dicts_to_use = [random.choice(available_dicts)] else: try: dicts_to_use = dicts_to_use.replace(' ', '').split(',') numerals = [] for num in dicts_to_use: num = int(num) if num not in range(len(available_dicts)): raise ValueError numerals.append(num) dicts_to_use = [available_dicts[num] for num in set(numerals)] # set class is used to get rid of duplicates except ValueError: return get_dicts(available_dicts) return dicts_to_use def use_continuous_mode(): "Asks the user for what mode to use." message = """In Continuous Mode the selected dictionary or dictionaries are used for your next queries without asking you to select any again. Do you want to use it? Type "Yes" or "No", ommiting the quotation marks.\n""" mode = input(message).lower() return exit() if mode == '' else True if mode == 'yes' else False if mode == 'no' else use_continuous_mode() def get_query(): """Asks the user for what to search for.""" query = input('Type something to search for.\n') return exit() if query == '' else query def search_selected_dicts(selected_dicts, query): """Searches the selected dictionaries for the given query by making a list of OnlineDictionary objects out of them. selected_dicts: list of tuples query: str """ online_dicts = [OnlineDictionary(name, url, sep) for name, url, sep in selected_dicts] for online_dic in online_dicts: print('Searching %s for "%s"...' % (online_dic.name, query)) online_dic.search_for(query) print('\nFinished searching. Check your Web browser.\n') def main(): print_data(available_dicts, instructions) continuous_mode = use_continuous_mode() if continuous_mode: selected_dicts = get_dicts(available_dicts) while True: query = get_query() print() search_selected_dicts(selected_dicts, query) else: while True: selected_dicts, query = get_dicts(available_dicts), get_query() print() search_selected_dicts(selected_dicts, query) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>you can change your structure from </p>\n\n<pre><code>('Merriam-Webster Dictionary', 'https://www.merriam-webster.com/dictionary/', '%20'),\n</code></pre>\n\n<p>to </p>\n\n<pre><code>{\n 'name':'Merriam-Webster Dictionary',\n 'url':'https://www.merriam-webster.com/dictionary/',\n 'sep':'%...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T21:17:50.590", "Id": "201328", "Score": "3", "Tags": [ "python", "beginner", "object-oriented", "python-3.x" ], "Title": "Searching Online English Dictionaries - follow-up" }
201328
<p>Here is code I wrote to dynamically choose between three country options (United States, Canada, Other). After the user selects a country it will show the related select option or an empty input (when &quot;Other&quot; country is chosen). Then I pass the previous value into an input called spr(state/province/region). The end result is two values are saved: country and spr.</p> <p>I'm here because I think the code could be refactored, and I'm not thinking about it in an efficient way.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const country = '#country'; const province = '#province'; const region = '#region'; const state = '#state'; const spr = '#spr'; const usa = '#usa'; const canada = '#canada'; const otherCountry = '#otherCountry'; hideCountryOptions(); //initial hide $(country).on('change', function() { hideCountryOptions(); selectSPR($(country).val()); switch ($(country).val()) { case "UNITED STATES": $(usa).show(); break; case "CANADA": $(canada).show(); break; default: $(otherCountry).show(); } }) $(state + "," + province + "," + region).on('change', function() { selectSPR($(country).val()); }); function hideCountryOptions() { $(canada).hide(); $(usa).hide(); $(otherCountry).hide(); } function selectSPR(country) { //pass value into the state/province/region input $(spr).val(""); switch (country) { case "UNITED STATES": $(spr).val($(state).val()); break; case "CANADA": $(spr).val($(province).val()); break; default: $(spr).val($(region).val()); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div&gt; &lt;label for="country"&gt;*Country&lt;/label&gt; &lt;select name="country" id="country" required&gt; &lt;option value=""&gt;CHOOSE…&lt;/option&gt; &lt;option value="UNITED STATES"&gt;UNITED STATES&lt;/option&gt; &lt;option value="CANADA"&gt;CANADA&lt;/option&gt; &lt;option value="AFGHANISTAN"&gt;AFGHANISTAN&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="usa"&gt; &lt;label for="state"&gt;*State&lt;/label&gt; &lt;select name="state" id="state"&gt; &lt;option value=""&gt;CHOOSE...&lt;/option&gt; &lt;option value="ALABAMA"&gt;ALABAMA&lt;/option&gt; &lt;option value="ALASKA"&gt;ALASKA&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="canada"&gt; &lt;label for="province"&gt;*Province&lt;/label&gt; &lt;select class="custom-select" name="province" id="province"&gt; &lt;option value=""&gt;CHOOSE...&lt;/option&gt; &lt;option value="ALBERTA"&gt;ALBERTA&lt;/option&gt; &lt;option value="BRITISH COLUMBIA"&gt;BRITISH COLUMBIA&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="otherCountry"&gt; &lt;label for="region"&gt;*Region&lt;/label&gt; &lt;input type="text" name="region" id="region" placeholder="Region"&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="text" name="spr" id="spr"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>I reduced the script in this way:</p>\n\n<ol>\n<li>The script length (in lines): was 49, now 27</li>\n<li>The jQuery lookups: was 18, now 7</li>\n<li>The sub-function amount: was 2, now 0</li>\n</ol>\n\n<p>There is still 2 change handlers.</p>\n\n<p><strong>The main changes:</strong></p>\n\n<p>I u...
{ "AcceptedAnswerId": "201383", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T22:44:47.560", "Id": "201335", "Score": "4", "Tags": [ "javascript", "jquery", "html5", "form" ], "Title": "Dynamic country, state select options" }
201335
<p>I have a scenario where I do filters depending on checkboxes checked. Now I have only 2 checkbox and I need to cover all escenarios into <code>if</code> <code>else</code> conditionals like:</p> <pre><code> if (!chkProjectTechs.Checked &amp;&amp; !chkTeamLeader.Checked) { foreach (DataRowView list in lstTech.SelectedItems) { var selectedEmpGuid = (Guid)list[0]; EmpGuid.Add(selectedEmpGuid); } parameters = ToDataTable(EmpGuid); } else if (!chkTeamLeader.Checked &amp;&amp; chkProjectTechs.Checked) { foreach (var technician in projectTechnicians) { EmpGuid.Add(technician.EmpGuid); } parameters = ToDataTable(EmpGuid); } else if (!chkProjectTechs.Checked &amp;&amp; chkTeamLeader.Checked) { foreach (var teamLeader in teamLeaders) { EmpGuid.Add(teamLeader.EmpGuid); } parameters = ToDataTable(EmpGuid); } else if (chkProjectTechs.Checked &amp;&amp; chkTeamLeader.Checked) { foreach (var technician in projectTechnicians) { EmpGuid.Add(technician.EmpGuid); } parameters = ToDataTable(EmpGuid); foreach (var teamLeader in teamLeaders) { EmpGuid.Add(teamLeader.EmpGuid); } parameters = ToDataTable(EmpGuid); } </code></pre> <p>But I need to add more checkboxes. For <code>foreach</code> checkbox I will add to my form I need to add it to each conditional, and at the final of the day I will get very long code. Is there another way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T23:13:24.840", "Id": "387738", "Score": "0", "body": "Are you sure this code is working correctly? It looks like parameters would be set to only team leaders in the fourth case, rather than to a combination of both." }, { "...
[ { "body": "<p>It's not completely clear from the code, but assuming your intent is to display the combination of all selected sets, or the result of a separate list box if no sets are selected, then you can do it with one check per set. </p>\n\n<p>Assuming EmpGuid is a List or similar that starts out empty (if...
{ "AcceptedAnswerId": "201339", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T22:59:18.287", "Id": "201337", "Score": "-1", "Tags": [ "c#" ], "Title": "Making filters based on checkboxes" }
201337
<p>I've implemented a stored procedure for a search process SQL Server 2008. I'm not sure if everything I created is correct. Also I'm wondering if this code has any leaks or vulnerability on SQL Injection. Here is my stored procedure:</p> <pre><code>USE [TestDB] GO /****** Object: StoredProcedure [dbo].[Search_Dictionary] Script Date: 08/09/2018 19:17:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[Search_Dictionary] @FilterBy int = NULL, @Name varchar(50) = NULL, @Code char(2) = NULL AS BEGIN SET NOCOUNT ON; SELECT RecID, Status, Code, Name FROM Dictionary WHERE (@FilterBy = 1 AND Name LIKE '%'+@Name+'%') OR (@FilterBy = 2 AND Code = @Code) OR (@FilterBy = 3 AND @Name IS NULL AND @Code IS NULL); END </code></pre> <p>Here is example on how I call this procedure:</p> <pre><code>EXEC Search_Dictionary @FilterBy = 1, @Name = "Grant", @Code = NULL; </code></pre> <p>I just want to prevent, if for example Filter By is 2 that should search query by Code column returns any result if user pass word Grant. In that case should return 0 records.</p> <p>Also if anyone have any suggestions on how to improve the code please let me know.</p>
[]
[ { "body": "<h1>Vulnerabilities</h1>\n\n<p>There's <strong>no way this stored procedure can be used for SQL injection</strong>. The only way a stored procedure can allow SQL injection is if it allows an unsanitized user-entered string to be used to build a dynamic query using <code>sp_executesql</code> <a href=\...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T23:29:06.010", "Id": "201338", "Score": "2", "Tags": [ "performance", "sql", "sql-server", "stored-procedure" ], "Title": "Stored procedure to implement a search filter" }
201338
<p>This is probably the last time I will post this data structure that I have been working on. I have added in an iterator and const_iterator class (although I do not use them probably where I should be). I also did not follow another persons advice to add emplace, emplace_front, and emplace_back simply because I have no idea how nor can I find any code to refer to online.</p> <p>The idea of this post is to gain more insight in what I need to change in my class most likely with the additional classes I have added i.e. iterator and const_iterator. This is my first time implementing an iterator class and to be honest I am not sure where to change my code to use iterator and where not to. </p> <p>I want to again thank the community for helping me I really appreciate the effort.</p> <p>Here is my header file:</p> <pre><code>#ifndef SINGLELINKEDLIST_h #define SINGLELINKEDLIST_h template &lt;class T&gt; class SingleLinkedList { private: struct Node { T data; std::unique_ptr&lt;Node&gt; next = nullptr; // disable if noncopyable&lt;T&gt; for cleaner error msgs explicit Node(const T&amp; x, std::unique_ptr&lt;Node&gt;&amp;&amp; p = nullptr) : data(x) , next(std::move(p)) {} // disable if nonmovable&lt;T&gt; for cleaner error msgs explicit Node(T&amp;&amp; x, std::unique_ptr&lt;Node&gt;&amp;&amp; p = nullptr) : data(std::move(x)) , next(std::move(p)) {} }; std::unique_ptr&lt;Node&gt; head = nullptr; Node* tail = nullptr; void do_pop_front() { head = std::move(head-&gt;next); } public: // Constructors SingleLinkedList() = default; // empty constructor SingleLinkedList(SingleLinkedList const &amp;source); // copy constructor // Rule of 5 SingleLinkedList(SingleLinkedList &amp;&amp;move) noexcept; // move constructor SingleLinkedList&amp; operator=(SingleLinkedList &amp;&amp;move) noexcept; // move assignment operator ~SingleLinkedList(); // Overload operators SingleLinkedList&amp; operator=(SingleLinkedList const &amp;rhs); // Memeber functions void swap(SingleLinkedList &amp;other) noexcept; bool empty() const { return head.get() == nullptr; } int size() const; void push_back(const T &amp;theData); void push_back(T &amp;&amp;theData); void push_front(const T &amp;theData); void push_front(T &amp;&amp;theData); void insert(int pos, const T &amp;theData); void clear(); void pop_front(); void pop_back(); void delete_specific(int delValue); bool search(const T &amp;x); // Create an iterator class class iterator; iterator begin(); iterator end(); // Create const iterator class class const_iterator; const_iterator cbegin() const; const_iterator cend() const; const_iterator begin() const; const_iterator end() const; }; template &lt;class T&gt; SingleLinkedList&lt;T&gt;::SingleLinkedList(SingleLinkedList&lt;T&gt; const &amp;source) { for(Node* loop = source.head.get(); loop != nullptr; loop = loop-&gt;next.get()) { push_back(loop-&gt;data); } } template &lt;class T&gt; SingleLinkedList&lt;T&gt;::SingleLinkedList(SingleLinkedList&lt;T&gt;&amp;&amp; move) noexcept { move.swap(*this); } template &lt;class T&gt; SingleLinkedList&lt;T&gt;&amp; SingleLinkedList&lt;T&gt;::operator=(SingleLinkedList&lt;T&gt; &amp;&amp;move) noexcept { move.swap(*this); return *this; } template &lt;class T&gt; SingleLinkedList&lt;T&gt;::~SingleLinkedList() { clear(); } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::clear() { while (head) { do_pop_front(); } } template &lt;class T&gt; SingleLinkedList&lt;T&gt;&amp; SingleLinkedList&lt;T&gt;::operator=(SingleLinkedList const &amp;rhs) { SingleLinkedList copy{ rhs }; swap(copy); return *this; } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::swap(SingleLinkedList &amp;other) noexcept { using std::swap; swap(head, other.head); swap(tail, other.tail); } template &lt;class T&gt; int SingleLinkedList&lt;T&gt;::size() const { int size = 0; for (auto current = head.get(); current != nullptr; current = current-&gt;next.get()) { size++; } return size; } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::push_back(const T &amp;theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(theData); if (!head) { head = std::move(newNode); tail = head.get(); } else { tail-&gt;next = std::move(newNode); tail = tail-&gt;next.get(); } } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::push_back(T &amp;&amp;thedata) { std::unique_ptr&lt;Node&gt; newnode = std::make_unique&lt;Node&gt;(std::move(thedata)); if (!head) { head = std::move(newnode); tail = head.get(); } else { tail-&gt;next = std::move(newnode); tail = tail-&gt;next.get(); } } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::push_front(const T &amp;theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(theData); newNode-&gt;next = std::move(head); head = std::move(newNode); if (!tail) { tail = head.get(); } } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::push_front(T &amp;&amp;theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(std::move(theData)); newNode-&gt;next = std::move(head); head = std::move(newNode); if (!tail) { tail = head.get(); } } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::insert(int pos, const T &amp;theData) { if (pos &lt; 0) { throw std::out_of_range("The insert location is invalid."); } auto node = head.get(); int i = 0; for (; node &amp;&amp; node-&gt;next &amp;&amp; i &lt; pos; node = node-&gt;next.get(), i++); auto newNode = std::make_unique&lt;Node&gt;(theData); if (node) { newNode-&gt;next = std::move(node-&gt;next); if (!newNode-&gt;next) tail = newNode.get(); // created in case we insert after the current tail node-&gt;next = std::move(newNode); } else { head = std::move(newNode); tail = head.get(); } } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::pop_front() { if (empty()) { throw std::out_of_range("List is Empty!!! Deletion is not possible."); } do_pop_front(); } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::pop_back() { if (!head) return; auto current = head.get(); Node* previous = nullptr; while (current-&gt;next) { previous = current; current = current-&gt;next.get(); } if (previous) { previous-&gt;next = nullptr; } else { head = nullptr; } tail = previous; previous-&gt;next = nullptr; } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::delete_specific(int delValue) { if (!head.get()) { throw std::out_of_range("List is Empty!!! Deletion is not possible."); } auto temp1 = head.get(); Node* temp2 = nullptr; while (temp1-&gt;data != delValue) { if (temp1-&gt;next == nullptr) { throw std::invalid_argument("Given node not found in the list!!!"); } temp2 = temp1; temp1 = temp1-&gt;next.get(); } temp2-&gt;next = std::move(temp1-&gt;next); } template &lt;class T&gt; bool SingleLinkedList&lt;T&gt;::search(const T &amp;x) { return std::find(begin(), end(), x) != end(); } template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream &amp;str, SingleLinkedList&lt;T&gt;&amp; list) { for (auto const&amp; item : list) { str &lt;&lt; item &lt;&lt; "\t"; } return str; } template &lt;class T&gt; class SingleLinkedList&lt;T&gt;::iterator { Node* node = nullptr; public: using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T * ; using reference = T &amp; ; iterator(Node *node = nullptr) : node(node) {} bool operator!=(const iterator&amp; other) const { return node != other.node; } bool operator==(const iterator&amp; other) const { return node == other.node; } T&amp; operator*() const { return node-&gt;data; } T&amp; operator-&gt;() const { return node-&gt;data; } iterator&amp; operator++() { node = node-&gt;next.get(); return *this; } }; template &lt;class T&gt; class SingleLinkedList&lt;T&gt;::const_iterator { Node* node = nullptr; public: using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T * ; using reference = T &amp; ; const_iterator(Node *node = nullptr) : node(node) {} bool operator!=(const iterator&amp; other) const { return node != other.node; } bool operator==(const iterator&amp; other) const { return node == other.node; } const T&amp; operator*() const { return node-&gt;data; } const T&amp; operator-&gt;() const { return node-&gt;data; } const_iterator&amp; operator++() { node = node-&gt;next.get(); return *this; } }; template&lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::begin() { return head.get(); } template&lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::end() { return {}; } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::begin() const { return head.get(); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::end() const { return {}; } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::cbegin() const { return head.get(); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::cend() const { return {}; } #endif /* SingleLinkedList_h*/ </code></pre> <p>Here is my main.cpp file:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;memory&gt; #include &lt;utility&gt; #include &lt;stdexcept&gt; #include &lt;iosfwd&gt; #include &lt;stdexcept&gt; #include &lt;ostream&gt; #include "SingleLinkedList.h" #include "DoubleLinkedList.h" int main(int argc, const char * argv[]) { /////////////////////////////////////////////////////////////////////// ///////////////////////////// Single Linked List ////////////////////// /////////////////////////////////////////////////////////////////////// SingleLinkedList&lt;int&gt; obj; obj.push_back(2); obj.push_back(4); obj.push_back(6); obj.push_back(8); obj.push_back(10); std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------displaying all nodes---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"----------------Inserting At Start----------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.push_front(50); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"-------------inserting at particular--------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.insert(5,60); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout &lt;&lt; "\n--------------------------------------------------\n"; std::cout &lt;&lt; "-------------Get current size ---=--------------------"; std::cout &lt;&lt; "\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.size() &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"----------------deleting at start-----------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop_front(); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"----------------deleting at end-----------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop_back(); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"--------------Deleting At Particular--------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.delete_specific(4); std::cout &lt;&lt; obj &lt;&lt; "\n"; obj.search(8) ? printf("yes"):printf("no"); std::cout &lt;&lt; "\n--------------------------------------------------\n"; std::cout &lt;&lt; "--------------Testing copy----------------------------"; std::cout &lt;&lt; "\n--------------------------------------------------\n"; SingleLinkedList&lt;int&gt; obj1 = obj; std::cout &lt;&lt; obj1 &lt;&lt; "\n"; std::cin.get(); } </code></pre> <p>Here is also the following post I made <a href="https://codereview.stackexchange.com/questions/201042/generic-single-linked-list-using-smart-pointers-follow-up">here</a></p>
[]
[ { "body": "<h1>Design issues</h1>\n\n<ul>\n<li><p>An overload of <code>insert</code> that accepts <code>T&amp;&amp;</code> is missing.</p></li>\n<li><p>Now that there are iterators, I'd expect <code>insert</code> to take a <code>const_iterator</code> as parameter instead of <code>int pos</code>.</p>\n\n<p>This...
{ "AcceptedAnswerId": "201347", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-09T23:51:02.590", "Id": "201340", "Score": "2", "Tags": [ "c++", "linked-list", "pointers" ], "Title": "Generic Single Linked List with smart pointers follow up part 2" }
201340
<p>I'm learning Java and I created a simple solution for the following problem:</p> <blockquote> <p>Given a file <code>[filename].txt</code> such that each line has the format <code>string, double</code>, find the minimum possible difference between any two values and identify if it is less than an arbitrary value <code>mindDist</code></p> </blockquote> <pre><code>package com.company; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); System.out.print("Please enter the name of the input file: "); Scanner inFile = new Scanner(new File(sc.nextLine())); sc.close(); List&lt;Double&gt; l = new ArrayList&lt;&gt;(); while (inFile.hasNextLine()) { String[] parts = inFile.nextLine().split(","); l.add(Double.parseDouble(parts[1])); } Collections.sort(l); double minDist = 5; double diff; double minDiff = Double.MAX_VALUE; for (int i = 1; i &lt; l.size(); i++) { diff = l.get(i) - l.get(i - 1); if (diff &lt; minDiff) minDiff = diff; } if (minDiff &lt; minDist) System.out.println("The satellites are not in safe orbits."); else System.out.println("The satellites are in safe orbits."); if (l.size()!=1) System.out.println("The minimum distance between orbits (km): " + minDiff); inFile.close(); } catch (NumberFormatException | FileNotFoundException | ArrayIndexOutOfBoundsException e) { System.err.println(e); } } } </code></pre> <p>I am looking on advice on if there are any other possible errors / exceptions I may have missed, in addition to any way of increasing the efficiency / simplicity of my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T01:48:05.807", "Id": "387751", "Score": "0", "body": "I posted a [Meta question](https://codereview.meta.stackexchange.com/q/8929/71574) about an edit to this question and some other cosmetic issues. This should not block people fr...
[ { "body": "<ul>\n<li>You can divide your <code>main</code> into smaller methods.</li>\n<li>The whole code shouldn't be wrapped inside a <code>try/catch</code> block. You should minimize the scope of your <code>try</code> block only where expect an <code>Exception</code>.</li>\n<li>Calculation of the minimum dis...
{ "AcceptedAnswerId": "201389", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T01:05:49.543", "Id": "201344", "Score": "4", "Tags": [ "java", "beginner", "object-oriented", "array" ], "Title": "Minimum difference between numbers in a file" }
201344
<p>This is yet another take in Python for the infamous Sieve of Eratosthenes. I am a beginner in Python so any criticism is highly appreciated. </p> <pre><code># Find primes until this integer.. Modify to your taste.. upper_bound = 1000 # Pass a list of integers and a prime number, # will return you a list where numbers divisible by the prime you passed are removed. def remove_non_primes(list_of_ints, prime_to_check_against): multiplier = 1 while prime_to_check_against * multiplier &lt; list_of_ints[-1]: multiplier += 1 # Should be quite fast since list is sorted. if prime_to_check_against * multiplier in list_of_ints: list_of_ints.remove(prime_to_check_against * multiplier) return list_of_ints ints = list(range(2, upper_bound)) # Generate initial list of integers # Initial prime for bootstrap prime = 2 # Keep track of iteration count, so we know the next prime to work with in each iteration. iteration_count = 0 while True: # Use length of list to determine we removed everything we could by # checking this length against returning lists length. original_list_length = len(ints) # Do the magic, remove all non primes found by parameter prime. ints = remove_non_primes(ints, prime) # List was not modified.. Nothing to remove. if original_list_length == len(ints): break iteration_count += 1 prime = ints[iteration_count] print(ints) </code></pre> <p>Are there any modifications that will dramatically increase the performance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T04:21:15.430", "Id": "388154", "Score": "2", "body": "I have rolled back your lastedit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code R...
[ { "body": "<p>I question the following comment:</p>\n\n<pre><code> # Should be quite fast since list is sorted.\n if prime_to_check_against * multiplier in list_of_ints:\n list_of_ints.remove(prime_to_check_against * multiplier)\n</code></pre>\n\n<p>Why will this be fast, due to the sorted list? <...
{ "AcceptedAnswerId": "201346", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T01:24:08.477", "Id": "201345", "Score": "4", "Tags": [ "python", "performance", "beginner", "primes", "sieve-of-eratosthenes" ], "Title": "Sieve of Eratosthenes in Python" }
201345
<p>I have code like below. By default the location is <code>myloc</code>. When user clicks <code>btn-a</code> it selects <code>myloc</code> and when <code>btn-b</code> is clicked it select <code>myloc1</code>. In my code I repeat the code <code>L.circle</code> three times, which is bad practice. So can anybody help me? How can I optimize this code, DRY it up and improve the quality as well?</p> <pre><code>var myloc = new L.LatLng(13.7433242, 100.5421583); var myloc1 = new L.LatLng(14.979900, 102.097771); $(function () { var circle; var slider = document.getElementById('myRange'); var output = document.getElementById('demo'); output.innerHTML = slider.value + scale; slider.oninput = function (val) { output.innerHTML = this.value + scale; circle.setRadius(this.value); } circle = L.circle(myloc, { color: '#7a7777', weight: 0.1, fillColor: '#7a7777', fillOpacity: 0.2, radius: 0 }).addTo(map); $('.btn-a').on('click', function(e){ if ($(this).val() == 'First') { circle = L.circle(myloc, { color: '#7a7777', weight: 0.1, fillColor: '#7a7777', fillOpacity: 0.2, radius: 0 }).addTo(map); } else if($(this).val() == 'Second') { circle = L.circle(myloc1, { color: '#7a7777', weight: 0.1, fillColor: '#7a7777', fillOpacity: 0.2, radius: 0 }).addTo(map); } }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T05:49:23.743", "Id": "387766", "Score": "0", "body": "I don't know who proposed the edit, but I rejected it since it didn't solve the issue. The current title is more along the lines of what we're looking for. If it's inaccurate in ...
[ { "body": "<p>To DRY up your code, you need to use a variable to call the same code with different input.s It seems like if you had something like this:</p>\n\n<pre><code>const circles = {\n First: myloc,\n Second: myloc1\n}\n</code></pre>\n\n<p>Then you'd be able to dry up the <code>click</code> code:</p>\...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T03:43:26.470", "Id": "201351", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Select a location on the map depending on which button is clicked" }
201351
<p>The following function is designed to accept a string of characters and an integer. The function returns a string that's a reordered version of the original string. The reordering process is controlled by the second variable. If the function is called again with the same string and a different number, a different string will be returned. However, if the string and the integer do not change, repeat calls to this function will always return the same string. as the integer changes, the returned strings should not appear to be similar. I have tested this function on the following string, with integer values between 0 and 40000 without finding a duplicate returned string. </p> <pre><code>"1234567890abcdefghijklmnopqrstuvwxyz" </code></pre> <p>Are there obvious improvements that can be made? I am also curious about this function's limitations. So far, it seems to perform rather well.</p> <pre><code>function shuffleString($inputString, $seed = 2000){ $strLength = strlen($inputString); $newString = ""; $factor = 3 + (int)($seed / $strLength); while($strLength &gt; 0){ $seed += $factor; if($seed &gt;= $strLength){ $seed = $seed % $strLength; } $newString .= $inputString[$seed]; $copyStr = ""; $strLength --; if($seed != 0){ $copyStr = substr($inputString,0,$seed); } if($seed != $strLength){ $copyStr .= substr($inputString,$seed+1); } $inputString = $copyStr; } return $newString.$inputString; } </code></pre> <p>Example:</p> <pre><code>echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '&lt;br /&gt;'; echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '&lt;br /&gt;'; </code></pre> <p>returns</p> <pre><code>beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze </code></pre> <p>also:</p> <pre><code>for($i=0; $i&lt;5; $i++){ $dataStr = "1234567890abcdefghijklmnopqrstuvwxyz"; for($j=0; $j&lt;2000; $j++){ $dataStr = shuffleString($dataStr, ord($dataStr[0])); } echo $dataStr . '&lt;br /&gt;'; } </code></pre> <p>returns:</p> <pre><code>gdwy63zmnjxharpovk50qulf2cei8t174bs9 gdwy63zmnjxharpovk50qulf2cei8t174bs9 gdwy63zmnjxharpovk50qulf2cei8t174bs9 gdwy63zmnjxharpovk50qulf2cei8t174bs9 gdwy63zmnjxharpovk50qulf2cei8t174bs9 </code></pre>
[]
[ { "body": "<p>Why does it need to be this complicated? PHP has builtins for changing the seed of the random number generator, and for shuffling strings.</p>\n\n<pre><code>function shuffleString($input, $seed = 2000) {\n srand($seed); // set the random generator seed\n $shuffled = str_shuffle($input);\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T04:03:59.487", "Id": "201354", "Score": "1", "Tags": [ "php", "strings", "shuffle" ], "Title": "Shuffle a string in a repeatable way" }
201354
<p>I'm new to Java and am following a series of lectures on Stanford's YouTube. I know that the code works, but I'd like to know if it can be improved upon.</p> <pre><code>/* * File: PythagoreanTheorem.java * Name: Will * Section Leader: N/A, I'm freeloading the class off Youtube. * ----------------------------- * This file is the starter file for the PythagoreanTheorem problem. */ import acm.program.*; public class PythagoreanTheorem extends ConsoleProgram { public PythagoreanTheorem() {} public void run() { PythagoreanTheorem myCalculator = new PythagoreanTheorem(); double a = readDouble("a= "); double b = readDouble("b= "); if(myCalculator.formula(a,b) == Math.floor(myCalculator.formula(a,b))) { println("C= "+(int)myCalculator.formula(a,b));} else { println("C= "+myCalculator.formula(a,b));} } private double formula(double x, double y) { double c = Math.sqrt(x*x+y*y); return c; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T06:07:59.397", "Id": "387768", "Score": "0", "body": "For those wondering: [get your ACM here](https://cs.stanford.edu/people/eroberts/jtf/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T06:09:02.00...
[ { "body": "<p>I did not check the <code>acm</code> package but my 2 cents:</p>\n\n<h2>No need to instantate a <code>PythagoreanTheorem</code> each time</h2>\n\n<pre><code>public void run() {\n PythagoreanTheorem myCalculator = new PythagoreanTheorem();\n</code></pre>\n\n<p><code>run</code> is not static, so ...
{ "AcceptedAnswerId": "201365", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T05:53:28.423", "Id": "201363", "Score": "0", "Tags": [ "java", "beginner" ], "Title": "Pythagorean Theorem in Java" }
201363
<p>This is a rather minimal (though fully functional) implementation of a singly linked list. It supports \$\mathcal{O}(1)\$ front insertion and deletions, as well as \$\mathcal{O}(1)\$ random insertions and deletions via iterator.</p> <p>The goal was a clean and simple implementation that can be used effectively with standard algorithms and provides a strong exception guarantee as far as possible.</p> <p>Please tell if I've overlooked any major functionality that cannot be easily done with the provided methods.</p> <h1>forward_list.hpp</h1> <pre><code>#pragma once #include &lt;memory&gt; #include &lt;type_traits&gt; #include &lt;iterator&gt; #include &lt;stdexcept&gt; #include &lt;utility&gt; #include &lt;cstddef&gt; template&lt;typename T&gt; class forward_list { public: using value_type = T; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; using const_pointer = const T*; using size_type = std::ptrdiff_t; using difference_type = std::ptrdiff_t; class iterator; class const_iterator; private: struct node_type { value_type data; std::unique_ptr&lt;node_type&gt; next; template&lt;typename... Args, typename = std::enable_if_t&lt;std::is_constructible_v&lt;T, Args&amp;&amp;...&gt;&gt;&gt; explicit node_type(std::unique_ptr&lt;node_type&gt;&amp;&amp; next, Args&amp;&amp;... args) noexcept(std::is_nothrow_constructible_v&lt;T, Args&amp;&amp;...&gt;) : data{ std::forward&lt;Args&gt;(args)... }, next{ std::move(next) } {} }; std::unique_ptr&lt;node_type&gt; head = nullptr; size_type length = 0; public: forward_list() = default; forward_list(const forward_list&amp; other); forward_list(forward_list&amp;&amp; other) noexcept; forward_list(std::initializer_list&lt;T&gt; il); template&lt;typename Iter&gt; forward_list(Iter first, Iter last); ~forward_list() noexcept(std::is_nothrow_destructible_v&lt;T&gt;); forward_list&amp; operator=(const forward_list&amp; other) &amp;; forward_list&amp; operator=(forward_list&amp;&amp; other) &amp; noexcept(std::is_nothrow_destructible_v&lt;T&gt;); reference front(); const_reference front() const; void push_front(const T&amp; value); void push_front(T&amp;&amp; value); void pop_front() noexcept(std::is_nothrow_destructible_v&lt;T&gt;); template&lt;typename... Args&gt; void emplace_front(Args&amp;&amp;... args); iterator insert_after(const_iterator pos, const T&amp; value); iterator insert_after(const_iterator pos, T&amp;&amp; value); iterator erase_after(const_iterator pos) noexcept(std::is_nothrow_destructible_v&lt;T&gt;); template&lt;typename... Args&gt; iterator emplace_after(const_iterator pos, Args&amp;&amp;... args); void clear() noexcept(std::is_nothrow_destructible_v&lt;T&gt;); void swap(forward_list&amp; other) noexcept; size_type size() const noexcept; bool empty() const noexcept; iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cend() const noexcept; iterator before_begin() noexcept; const_iterator before_begin() const noexcept; const_iterator cbefore_begin() const noexcept; }; template&lt;typename T&gt; class forward_list&lt;T&gt;::iterator { node_type* node = nullptr; bool before_begin = false; public: friend class forward_list&lt;T&gt;; friend class const_iterator; using value_type = typename forward_list&lt;T&gt;::value_type; using pointer = typename forward_list&lt;T&gt;::pointer; using reference = typename forward_list&lt;T&gt;::reference; using difference_type = typename forward_list&lt;T&gt;::difference_type; using iterator_category = std::forward_iterator_tag; iterator() = default; iterator(node_type* node, bool before_begin = false) noexcept; iterator&amp; operator++(); iterator operator++(int); reference operator*() const; pointer operator-&gt;() const; bool operator==(iterator other) const noexcept; bool operator!=(iterator other) const noexcept; }; template&lt;typename T&gt; class forward_list&lt;T&gt;::const_iterator { node_type* node = nullptr; bool before_begin = false; public: friend class forward_list&lt;T&gt;; using value_type = typename forward_list&lt;T&gt;::value_type; using pointer = typename forward_list&lt;T&gt;::const_pointer; using reference = typename forward_list&lt;T&gt;::const_reference; using difference_type = typename forward_list&lt;T&gt;::difference_type; using iterator_category = std::forward_iterator_tag; const_iterator() = default; const_iterator(node_type* node, bool before_begin = false) noexcept; const_iterator(iterator other) noexcept; const_iterator&amp; operator++(); const_iterator operator++(int); reference operator*() const; pointer operator-&gt;() const; bool operator==(const_iterator other) const noexcept; bool operator!=(const_iterator other) const noexcept; }; /// FORWARD_LIST IMPLEMENTATION /////////////////////////////////////////////////// template&lt;typename T&gt; forward_list&lt;T&gt;::forward_list(const forward_list&amp; other) : forward_list{ other.begin(), other.end() } {} template&lt;typename T&gt; forward_list&lt;T&gt;::forward_list(forward_list&amp;&amp; other) noexcept : head{ std::move(other.head) }, length{ other.length } { other.length = 0; } template&lt;typename T&gt; forward_list&lt;T&gt;::forward_list(std::initializer_list&lt;T&gt; il) : forward_list{ il.begin(), il.end() } {} template&lt;typename T&gt; template&lt;typename Iter&gt; forward_list&lt;T&gt;::forward_list(Iter first, Iter last) { static_assert(std::is_copy_constructible_v&lt;T&gt;, "T must be copy constructible!"); auto insert_pos = before_begin(); for(auto it = first; it != last; ++it) { insert_pos = insert_after(insert_pos, *it); } } template&lt;typename T&gt; forward_list&lt;T&gt;::~forward_list() noexcept(std::is_nothrow_destructible_v&lt;T&gt;) { clear(); } template&lt;typename T&gt; forward_list&lt;T&gt;&amp; forward_list&lt;T&gt;::operator=(const forward_list&amp; other) &amp; { static_assert(std::is_copy_constructible_v&lt;T&gt;, "T must be copy constructible"); auto copy = forward_list{ other }; swap(copy); return *this; } template&lt;typename T&gt; forward_list&lt;T&gt;&amp; forward_list&lt;T&gt;::operator=(forward_list&amp;&amp; other) &amp; noexcept(std::is_nothrow_destructible_v&lt;T&gt;) { auto temp = forward_list{ std::move(other) }; swap(temp); return *this; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::reference forward_list&lt;T&gt;::front() { if (!head) throw std::range_error{ "list is empty!" }; return head-&gt;data; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_reference forward_list&lt;T&gt;::front() const { if (!head) throw std::range_error{ "list is empty!" }; return head-&gt;data; } template&lt;typename T&gt; void forward_list&lt;T&gt;::push_front(const T&amp; value) { emplace_front(value); } template&lt;typename T&gt; void forward_list&lt;T&gt;::push_front(T&amp;&amp; value) { emplace_front(std::move(value)); } template&lt;typename T&gt; void forward_list&lt;T&gt;::pop_front() noexcept(std::is_nothrow_destructible_v&lt;T&gt;) { if(head) { head = std::move(head-&gt;next); --length; } } template&lt;typename T&gt; template&lt;typename ... Args&gt; void forward_list&lt;T&gt;::emplace_front(Args&amp;&amp;... args) { static_assert(std::is_constructible_v&lt;T&gt;, "T cannot be constructed using the passed arguments"); head = std::make_unique&lt;node_type&gt;(std::move(head), std::forward&lt;Args&gt;(args)...); ++length; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::insert_after(const_iterator pos, const T&amp; value) { return emplace_after(pos, value); } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::insert_after(const_iterator pos, T&amp;&amp; value) { return emplace_after(pos, std::move(value)); } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::erase_after(const_iterator pos) noexcept(std::is_nothrow_destructible_v&lt;T&gt;) { if(pos.before_begin) { pop_front(); return begin(); } if (pos.node &amp;&amp; pos.node-&gt;next) { pos.node-&gt;next = std::move(pos.node-&gt;next-&gt;next); --length; return { pos.node-&gt;next.get() }; } return end(); } template&lt;typename T&gt; template&lt;typename ... Args&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::emplace_after(const_iterator pos, Args&amp;&amp;... args) { if(pos.before_begin) { emplace_front(std::forward&lt;Args&gt;(args)...); return begin(); } pos.node-&gt;next = std::make_unique&lt;node_type&gt;(std::move(pos.node-&gt;next), std::forward&lt;Args&gt;(args)...); ++length; return { pos.node-&gt;next.get() }; } template&lt;typename T&gt; void forward_list&lt;T&gt;::clear() noexcept(std::is_nothrow_destructible_v&lt;T&gt;) { while (head) head = std::move(head-&gt;next); length = 0; } template&lt;typename T&gt; void forward_list&lt;T&gt;::swap(forward_list&amp; other) noexcept { using std::swap; swap(head, other.head); swap(length, other.length); } template&lt;typename T&gt; typename forward_list&lt;T&gt;::size_type forward_list&lt;T&gt;::size() const noexcept { return length; } template&lt;typename T&gt; bool forward_list&lt;T&gt;::empty() const noexcept { return head == nullptr; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::begin() noexcept { return { head.get() }; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::begin() const noexcept { return { head.get() }; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::cbegin() const noexcept { return begin(); } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::end() noexcept { return {}; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::end() const noexcept { return {}; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::cend() const noexcept { return end(); } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::before_begin() noexcept { return { head.get(), true }; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::before_begin() const noexcept { return { head.get(), true }; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::cbefore_begin() const noexcept { return before_begin(); } /// ITERATOR IMPLEMENTATION /////////////////////////////////////////////////////// template&lt;typename T&gt; forward_list&lt;T&gt;::iterator::iterator(node_type* node, bool before_begin) noexcept : node{ node }, before_begin{ before_begin } {} template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator&amp; forward_list&lt;T&gt;::iterator::operator++() { if (before_begin) before_begin = false; else node = node-&gt;next.get(); return *this; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator forward_list&lt;T&gt;::iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator::reference forward_list&lt;T&gt;::iterator::operator*() const { return node-&gt;data; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::iterator::pointer forward_list&lt;T&gt;::iterator::operator-&gt;() const { return &amp;node-&gt;data; } template&lt;typename T&gt; bool forward_list&lt;T&gt;::iterator::operator==(iterator other) const noexcept { return node == other.node &amp;&amp; before_begin == other.before_begin; } template&lt;typename T&gt; bool forward_list&lt;T&gt;::iterator::operator!=(iterator other) const noexcept { return !(*this == other); } /// CONST_ITERATOR IMPLEMENTATION ///////////////////////////////////////////////// template&lt;typename T&gt; forward_list&lt;T&gt;::const_iterator::const_iterator(node_type* node, bool before_begin) noexcept : node{ node }, before_begin{ before_begin } {} template&lt;typename T&gt; forward_list&lt;T&gt;::const_iterator::const_iterator(iterator other) noexcept : node{ other.node }, before_begin{ other.before_begin } {} template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator&amp; forward_list&lt;T&gt;::const_iterator::operator++() { if (before_begin) before_begin = false; else node = node-&gt;next.get(); return *this; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator forward_list&lt;T&gt;::const_iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator::reference forward_list&lt;T&gt;::const_iterator::operator*() const { return node-&gt;data; } template&lt;typename T&gt; typename forward_list&lt;T&gt;::const_iterator::pointer forward_list&lt;T&gt;::const_iterator::operator-&gt;() const { return &amp;node-&gt;data; } template&lt;typename T&gt; bool forward_list&lt;T&gt;::const_iterator::operator==(const_iterator other) const noexcept { return node == other.node &amp;&amp; before_begin == other.before_begin; } template&lt;typename T&gt; bool forward_list&lt;T&gt;::const_iterator::operator!=(const_iterator other) const noexcept { return !(*this == other); } /// FREE FUNCTIONS IMPLEMENTATION ///////////////////////////////////////////////// template&lt;typename T&gt; void swap(forward_list&lt;T&gt;&amp; lhs, forward_list&lt;T&gt;&amp; rhs) noexcept { lhs.swap(rhs); } </code></pre> <h1>unittests.cpp (using the <a href="https://github.com/catchorg/Catch2" rel="noreferrer">Catch2 testing framework</a>)</h1> <pre><code>#include "forward_list.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" #include &lt;algorithm&gt; #include &lt;mutex&gt; TEST_CASE("Using an empty forward_list", "[forward_list]") { auto list = forward_list&lt;int&gt;{}; REQUIRE(list.size() == 0); REQUIRE(list.empty()); REQUIRE(list.begin() == list.end()); SECTION("Adding an element at the front sets up invariants") { constexpr auto value = 1234; list.push_front(value); REQUIRE(!list.empty()); REQUIRE(list.front() == value); REQUIRE(list.size() == 1); REQUIRE(list.begin() != list.end()); REQUIRE(++list.begin() == list.end()); } SECTION("Adding multiple elements increases size correctly") { constexpr auto value = 1234; for(auto i = 0; i &lt; 10; ++i) { list.push_front(i); REQUIRE(list.size() == i + 1); REQUIRE(std::distance(list.begin(), list.end()) == i + 1); } } SECTION("pop_front on empty list does nothing") { list.pop_front(); REQUIRE(list.size() == 0); REQUIRE(list.empty()); REQUIRE(list.begin() == list.end()); } SECTION("front on empty list throws") { REQUIRE_THROWS(list.front()); } } TEST_CASE("Using a forward list with multiple elements", "[forward_list]") { static auto init_values = std::vector&lt;int&gt;{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; auto list = forward_list&lt;int&gt;{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; REQUIRE(list.size() == init_values.size()); REQUIRE(!list.empty()); REQUIRE(std::distance(list.begin(), list.end()) == init_values.size()); REQUIRE(std::equal(list.begin(), list.end(), init_values.begin())); SECTION("Can find elements with std::find") { auto found = std::find(std::begin(list), std::end(list), 5); REQUIRE(found != std::end(list)); REQUIRE(*found == 5); } SECTION("Insert new value after iterator position") { static auto expected = std::vector&lt;int&gt;{ 9, 8, 7, 6, 5, 11, 4, 3, 2, 1, 0 }; const auto iter = std::find(std::begin(list), std::end(list), 5); REQUIRE(iter != std::end(list)); auto inserted = list.insert_after(iter, 11); REQUIRE(inserted != std::end(list)); REQUIRE(*inserted == 11); REQUIRE(std::equal(std::begin(list), std::end(list), std::begin(expected))); } SECTION("Insertion handles before_begin() iterator correctly") { list.insert_after(list.before_begin(), 12); REQUIRE(list.front() == 12); } SECTION("pop_front removes front node") { list.pop_front(); REQUIRE(list.front() == 8); REQUIRE(list.size() == 9); } SECTION("erase_after removes element") { static auto expected = std::vector&lt;int&gt;{ 9, 8, 7, 6, 5, 4, 2, 1, 0 }; auto iter = std::find(list.begin(), list.end(), 4); auto after_removed = list.erase_after(iter); REQUIRE(list.size() == init_values.size() - 1); REQUIRE(after_removed != list.end()); REQUIRE(*after_removed == 2); REQUIRE(std::equal(list.begin(), list.end(), expected.begin())); } SECTION("erase_after handles before_begin() iterator correctly") { static auto expected = std::vector&lt;int&gt;{ 8, 7, 6, 5, 4, 3, 2, 1, 0 }; auto after_removed = list.erase_after(list.before_begin()); REQUIRE(list.size() == init_values.size() - 1); REQUIRE(after_removed == list.begin()); REQUIRE(std::equal(list.begin(), list.end(), expected.begin())); REQUIRE(list.front() == expected.front()); } SECTION("clear removes all nodes") { list.clear(); REQUIRE(list.size() == 0); REQUIRE(list.empty()); REQUIRE(list.begin() == list.end()); } SECTION("copy construction") { auto second_list = list; REQUIRE(list.size() == init_values.size()); REQUIRE(std::equal(list.begin(), list.end(), init_values.begin())); REQUIRE(second_list.size() == list.size()); REQUIRE(std::equal(second_list.begin(), second_list.end(), list.begin())); } SECTION("copy assignment") { auto second_list = forward_list&lt;int&gt;{}; second_list = list; REQUIRE(list.size() == init_values.size()); REQUIRE(std::equal(list.begin(), list.end(), init_values.begin())); REQUIRE(second_list.size() == list.size()); REQUIRE(std::equal(second_list.begin(), second_list.end(), list.begin())); } SECTION("move construction leaves original list in empty state") { auto second_list = forward_list&lt;int&gt;{ std::move(list) }; REQUIRE(list.empty()); REQUIRE(second_list.size() == init_values.size()); REQUIRE(std::equal(second_list.begin(), second_list.end(), init_values.begin())); } SECTION("move assignment leaves original list in empty state") { auto second_list = forward_list&lt;int&gt;{ 11, 12, 13 }; second_list = std::move(list); REQUIRE(list.empty()); REQUIRE(second_list.size() == init_values.size()); REQUIRE(std::equal(second_list.begin(), second_list.end(), init_values.begin())); } SECTION("swap exchanges states") { static auto second_list_values = std::vector&lt;int&gt;{ 1, 2, 3 }; auto second_list = forward_list&lt;int&gt;{ second_list_values.begin(), second_list_values.end() }; swap(list, second_list); REQUIRE(list.size() == second_list_values.size()); REQUIRE(std::equal(list.begin(), list.end(), second_list_values.begin())); REQUIRE(second_list.size() == init_values.size()); REQUIRE(std::equal(second_list.begin(), second_list.end(), init_values.begin())); } } TEST_CASE("Can use non.movable and non-copyable types", "[forward_list]") { auto list = forward_list&lt;std::mutex&gt;{}; REQUIRE(list.empty()); REQUIRE(list.size() == 0); REQUIRE(list.begin() == list.end()); SECTION("Can use emplace_front") { list.emplace_front(); REQUIRE(!list.empty()); REQUIRE(list.size() == 1); } SECTION("Can use emplace_after") { list.emplace_front(); list.emplace_after(list.begin()); REQUIRE(list.size() == 2); } SECTION("Can use -&gt; on iterators") { list.emplace_front(); auto iter = list.begin(); REQUIRE(iter != list.end()); iter-&gt;lock(); iter-&gt;unlock(); } // Fails to compile, as expected: /* SECTION("Copy doesn't work") { auto copy = forward_list&lt;std::mutex&gt;{ list }; } */ } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:31:27.250", "Id": "387881", "Score": "1", "body": "That's a lot of *minimal* code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:45:42.040", "Id": "387884", "Score": "1", "body": "...
[ { "body": "<p>Generally excellent code. Although you claim it's \"minimal\", the only non-trivial thing that seems to be missing is user-specified allocation.</p>\n\n<p>Good use of <code>noexcept</code> and <code>const</code> throughout.</p>\n\n<p>There's an argument for reducing duplication by making the iter...
{ "AcceptedAnswerId": "201375", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T07:19:49.627", "Id": "201368", "Score": "12", "Tags": [ "c++", "linked-list", "reinventing-the-wheel", "c++17" ], "Title": "Modern C++ singly linked list" }
201368
<p>It is my first time trying to create smooth animations using rAF and I would like some insight from more experienced developers. Basically I have 16 elements with x,y coordinates and on mousemove over their parent container, all elements move a set amount in the opposite direction. When I do tests on lower-end machines there is some stutter. Is there any technique I am not aware of that can boost my animation performance?</p> <pre><code>(function ($) { $(document).ready(() =&gt; { const animCont = document.querySelector('.shop-header-container'); const animContWidth = animCont.offsetWidth; const animContHeight = animCont.offsetHeight; const leftOffset = animCont.getBoundingClientRect().left; const topOffset = document.querySelector('#primary').offsetTop; const animImgs = animCont.querySelectorAll('.elem'); let mouseX = 0; let mouseY = 0; let mouseOver = false; let positions = [ { id: 82, start: { x: 0.596, y: 0.654, }, range: 0.4, } ... ] positions.forEach(el =&gt; { el.target = {}; el.current = {}; }) function updateElements(){ mouseTargetX = (mouseX - leftOffset) / animContWidth; mouseTargetY = (mouseY + topOffset) / animContHeight; positions.forEach((el,i) =&gt; { if (mouseOver) { el.target.x = ((mouseTargetX - el.start.x) * -el.range + el.start.x ) * animContWidth; el.target.y = ((mouseTargetY - el.start.y) * -el.range + el.start.y ) * animContHeight; } else { el.target.x = el.start.x * animContWidth; el.target.y = el.start.y * animContHeight; } if(!el.current.x) { el.current.x = el.target.x; el.current.y = el.target.y; } else { el.current.x = el.current.x + (el.target.x - el.current.x)*0.1; el.current.y = el.current.y + (el.target.y - el.current.y)*0.1; } animImgs[i].style.transform = 'translate3d('+el.current.x+'px,'+el.current.y+'px,0)'; }) requestAnimationFrame(updateElements); } updateElements(); function animContMouseEnter(e){ mouseOver = true; } function animContMouseLeave(){ mouseOver = false; } function animContMouseOver(e){ mouseX = e.clientX; mouseY = e.clientY; } animCont.addEventListener("mousemove",animContMouseOver,false); animCont.addEventListener("mouseenter",animContMouseEnter,false); animCont.addEventListener("mouseleave",animContMouseLeave,false); }); }(jQuery)); </code></pre>
[]
[ { "body": "<p>There is not enough information in your question to get a clear picture of where there may be a problem.</p>\n\n<h2>Your code</h2>\n\n<p>You code does not have any glaring performance issues. Some minor changes would be...</p>\n\n<ul>\n<li><p>Use <code>for</code> loops rather than <code>forEach</c...
{ "AcceptedAnswerId": "201403", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T07:56:04.563", "Id": "201371", "Score": "1", "Tags": [ "javascript", "animation" ], "Title": "Creating smooth animations using rAF" }
201371
<p>I wrote a <a href="https://gitlab.com/coNQP/mcipc" rel="noreferrer">library</a> implementing the <a href="https://wiki.vg/RCON" rel="noreferrer">RCON</a> protocol to automate interaction with Minecraft servers.<br> I know that there are already a couple of implementations out there, but neither I found was convincing me, so I re-invented the wheel.</p> <p>The library will also be featuring an implementation of the <a href="http://wiki.vg/Query" rel="noreferrer">Query</a> protocol, which is not implemented yet. This is the reason why the RCON stuff is in a <code>rcon</code> subpackage.<br> However, this review shall only focus on the fully implemented RCON part.</p> <p><strong><code>mcipc.config.py</code></strong></p> <pre><code>"""Server configuration parser.""" from configparser import ConfigParser from pathlib import Path __all__ = ['SERVERS_INI', 'FORTUNE', 'servers'] SERVERS_INI = Path('/etc/mcipc.d/servers.conf') _SERVERS = ConfigParser() FORTUNE = Path('/usr/bin/fortune') def servers(): """Yields the respective servers.""" _SERVERS.read(str(SERVERS_INI)) return { section: (_SERVERS[section]['host'], int(_SERVERS[section]['port']), _SERVERS[section].get('passwd')) for section in _SERVERS.sections()} </code></pre> <p><strong><code>mcipc.rcon.__init__.py</code></strong></p> <pre><code>"""RCON client library.""" from mcipc.rcon.client import Client from mcipc.rcon.console import rconcmd from mcipc.rcon.proto import RequestIdMismatch, PacketType, Packet, RawClient __all__ = [ 'RequestIdMismatch', 'rconcmd', 'PacketType', 'Packet', 'RawClient', 'Client'] </code></pre> <p><strong><code>mcipc.rcon.client.py</code></strong></p> <pre><code>"""High level client API.""" from collections import namedtuple from datetime import datetime from locale import LC_TIME, getdefaultlocale, setlocale from logging import getLogger from subprocess import PIPE, CalledProcessError, check_output from mcipc.config import FORTUNE from mcipc.rcon.proto import RequestIdMismatch, RawClient LOGGER = getLogger(__file__) _PLAYER_OR_COORDS = TypeError('Must specify either dst_player or coords.') def _fix_text(text): """Fixes text for ascii compliance.""" return text.replace('\t', ' ') class OnlinePlayers(namedtuple('OnlinePlayers', ('online', 'max', 'players'))): """Online players information.""" @classmethod def from_string(cls, string): """Creates the players information from the server response string.""" header, players = string.split(':', maxsplit=1) players = [player for player in players.split(', ') if player] _, _, amount, _, _ = header.split() online, max_ = amount.split('/') return cls(int(online), int(max_), players) class Client(RawClient): """A high-level RCON client.""" @property def players(self): """Returns the players.""" return OnlinePlayers.from_string(self.run('list')) def login(self, passwd): """Performs a login, returning False on failure.""" try: return super().login(passwd) except RequestIdMismatch: return False def say(self, message): """Broadcast a message to all players.""" LOGGER.debug('Sending text: "%s".', message) return self.run('say', _fix_text(message)) def tell(self, player, message): """Whispers a message to the respective player.""" return self.run('tell', player, _fix_text(message)) def mkop(self, player): """Makes the respective player an operator.""" return self.run('op', player) def deop(self, player): """Revokes operator status from the respective player.""" return self.run('deop', player) def kick(self, player, *reasons): """Kicks the respective player.""" return self.run('kick', player, *reasons) def teleport(self, player, dst_player=None, coords=None, yaw_pitch=None): """Teleports players.""" args = [str(player)] if dst_player is not None and coords is not None: raise _PLAYER_OR_COORDS elif dst_player is not None: args.append(str(dst_player)) elif coords is not None: coord_x, coord_y, coord_z = coords args += [str(coord_x), str(coord_y), str(coord_z)] else: raise _PLAYER_OR_COORDS if yaw_pitch is not None: yaw, pitch = yaw_pitch args += [str(yaw), str(pitch)] return self.run('tp', *args) def fortune(self, short=True, offensive=False): """Sends a fortune to all players.""" args = [] if short: args.append('-s') if offensive: args.append('-o') try: text = check_output([FORTUNE] + args, stderr=PIPE) except FileNotFoundError: LOGGER.error('%s is not available.', FORTUNE) except CalledProcessError as called_process_error: LOGGER.error('Error running %s.', FORTUNE) LOGGER.debug(called_process_error.stderr.decode()) else: text = text.decode() LOGGER.debug('Fortune text:\n%s', text) return self.say(text) return False def datetime(self, frmt='%c'): """Tells all players the current datetime.""" setlocale(LC_TIME, getdefaultlocale()) # Fix loacale. text = datetime.now().strftime(frmt) return self.say(text) </code></pre> <p><strong><code>mcipc.rcon.console.py</code></strong></p> <pre><code>"""An interactive console.""" from getpass import getpass from mcipc.rcon.proto import RequestIdMismatch from mcipc.rcon.client import Client __all__ = ['rconcmd'] PS1 = 'RCON&gt; ' EXIT_COMMANDS = ('exit', 'quit') def _read(prompt, type_=None): """Reads input and converts it to the respective type.""" while True: try: raw = input(prompt) except EOFError: continue if type_ is not None: try: return type_(raw) except (TypeError, ValueError): print(f'Invalid {type_}: {raw}.') continue return raw def _login(client, passwd): """Performs a login.""" if passwd is None: passwd = getpass('Password: ') while not client.login(passwd): print('Invalid password.') passwd = getpass('Password: ') return passwd def rconcmd(host=None, port=None, passwd=None, *, prompt=PS1): """Initializes the console.""" if host is None: try: host = _read('Host: ') except KeyboardInterrupt: print('\nAborted...') return 1 if port is None: try: port = _read('Port: ', type_=int) except KeyboardInterrupt: print('\nAborted...') return 1 with Client(host, port) as client: try: passwd = _login(client, passwd) except (EOFError, KeyboardInterrupt): print('\nAborted...') return 1 while True: try: command = input(prompt) except EOFError: print('\nAborted.') break except KeyboardInterrupt: print() continue command, *args = command.split() if command in EXIT_COMMANDS: break try: result = client.run(command, *args) except RequestIdMismatch: print('Session timed out. Please login again.') try: passwd = _login(client, passwd) except (EOFError, KeyboardInterrupt): print() continue print(result) return 0 </code></pre> <p><strong><code>mcipc.rcon.credentials.py</code></strong></p> <pre><code>"""RCON server credentials.""" from collections import namedtuple from mcipc.config import servers __all__ = ['InvalidCredentialsError', 'Credentials'] class InvalidCredentialsError(ValueError): """Indicates invalid credentials.""" pass class Credentials(namedtuple('Credentials', ('host', 'port', 'passwd'))): """Represents server credentials.""" @classmethod def from_string(cls, string): """Reads the credentials from the given string.""" try: host, port = string.split(':') except ValueError: try: return servers()[string] except KeyError: raise InvalidCredentialsError(f'No such server: {string}.') try: port = int(port) except ValueError: InvalidCredentialsError(f'Not an integer: {port}.') try: passwd, host = host.rsplit('@', maxsplit=1) except ValueError: passwd = None return cls(host, port, passwd) </code></pre> <p><strong><code>mcipc.rcon.proto.py</code></strong></p> <pre><code>"""Low-level protocol stuff.""" from collections import namedtuple from enum import Enum from itertools import chain from logging import getLogger from random import randint from socket import socket from struct import pack, unpack __all__ = [ 'RequestIdMismatch', 'PacketType', 'Packet', 'RawClient'] LOGGER = getLogger(__file__) TAIL = b'\0\0' class InvalidPacketStructureError(Exception): """Indicates an invalid packet structure.""" pass class RequestIdMismatch(Exception): """Indicates that the sent and received request IDs do not match.""" def __init__(self, sent_request_id, received_request_id): """Sets the sent and received request IDs.""" super().__init__(sent_request_id, received_request_id) self.sent_request_id = sent_request_id self.received_request_id = received_request_id def _rand_int32(): """Returns a random int32.""" return randint(0, 2_147_483_647 + 1) class PacketType(Enum): """Available packet types.""" LOGIN = 3 COMMAND = 2 COMMAND_RESPONSE = 0 def __int__(self): return self.value class Packet(namedtuple('Packet', ('request_id', 'type', 'payload'))): """An RCON packet.""" def __bytes__(self): """Returns the packet as bytes.""" payload = pack('&lt;i', self.request_id) payload += pack('&lt;i', int(self.type)) payload += self.payload.encode() payload += TAIL return pack('&lt;i', len(payload)) + payload @classmethod def from_bytes(cls, bytes_): """Creates a packet from the respective bytes.""" request_id, type_ = unpack('&lt;ii', bytes_[:8]) payload = bytes_[8:-2] tail = bytes_[-2:] if tail != TAIL: raise InvalidPacketStructureError('Invalid tail.', tail) return cls(request_id, type_, payload.decode()) @classmethod def from_command(cls, command): """Creates a command packet.""" return cls(_rand_int32(), PacketType.COMMAND, command) @classmethod def from_login(cls, passwd): """Creates a login packet.""" return cls(_rand_int32(), PacketType.LOGIN, passwd) class RawClient(socket): """An RCON client.""" def __init__(self, host, port): """Sets host an port.""" super().__init__() self.host = host self.port = port def __enter__(self): """Sets up and conntects the socket.""" super().__enter__() sock = self.socket LOGGER.debug('Connecting to socket %s.', sock) self.connect(sock) return self def __exit__(self, *args): """Disconnects the socket.""" LOGGER.debug('Disconnecting from socket %s.', self.getsockname()) return super().__exit__(*args) @property def socket(self): """Returns the respective socket.""" return (self.host, self.port) def sendpacket(self, packet): """Sends an Packet.""" bytes_ = bytes(packet) LOGGER.debug('Sending %i bytes.', len(bytes_)) return self.send(bytes_) def recvpacket(self): """Receives a packet.""" length, = unpack('&lt;i', self.recv(4)) payload = self.recv(length) return Packet.from_bytes(payload) def login(self, passwd): """Performs a login.""" login_packet = Packet.from_login(passwd) self.sendpacket(login_packet) response = self.recvpacket() if response.request_id == login_packet.request_id: return True raise RequestIdMismatch( login_packet.request_id, response.request_id) def run(self, command, *arguments): """Runs a command.""" command = ' '.join(chain((command,), arguments)) command_packet = Packet.from_command(command) self.sendpacket(command_packet) response = self.recvpacket() if response.request_id == command_packet.request_id: return response.payload raise RequestIdMismatch( command_packet.request_id, response.request_id) </code></pre> <p>The library also features two scripts. One for an interactive console and one for a oneshot client:</p> <p><strong><code>/usr/bin/rconclt</code></strong></p> <pre><code>#! /usr/bin/env python3 """rconclt. A Minecraft RCON client. Usage: rconclt &lt;server&gt; datetime [--format=&lt;format&gt;] [options] rconclt &lt;server&gt; fortune [--long] [--offensive] [options] rconclt &lt;server&gt; &lt;command&gt; [&lt;args&gt;...] [options] Options: --passwd=&lt;passwd&gt; Specifies the respective RCON password. --format=&lt;format&gt; Specifies the datetime format [default: %c]. --long Also generate long fortunes. --offensive Only genenrate offensive fortunes. --debug Enters debug mode. --help, -h Shows this page. """ from logging import DEBUG, INFO, basicConfig, getLogger from sys import exit as exit_ from docopt import docopt from mcipc.rcon.client import Client from mcipc.rcon.credentials import InvalidCredentialsError, Credentials LOGGER = getLogger(__file__) _LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s' def main(options): """Runs the RCON client.""" log_level = DEBUG if options['--debug'] else INFO basicConfig(level=log_level, format=_LOG_FORMAT) try: host, port, passwd = Credentials.from_string(options['&lt;server&gt;']) except InvalidCredentialsError as error: LOGGER.error(error) exit_(2) if passwd is None: passwd = options['--passwd'] or '' with Client(host, port) as client: if client.login(passwd): if options['datetime']: result = client.datetime(frmt=options['--format']) elif options['fortune']: result = client.fortune( short=not options['--long'], offensive=options['--offensive']) else: result = client.run(options['&lt;command&gt;'], *options['&lt;args&gt;']) if result: LOGGER.info(result) else: LOGGER.error('Failed to log in.') exit_(1) if __name__ == '__main__': main(docopt(__doc__)) </code></pre> <p><strong><code>/usr/bin/rconcmd</code></strong></p> <pre><code>#! /usr/bin/env python3 """An interactive RCON console.""" from sys import exit as exit_ from mcipc.rcon.console import rconcmd if __name__ == '__main__': exit_(rconcmd()) </code></pre> <p>I'd appreciate any critique.</p>
[]
[ { "body": "<p>I managed to get rid of the <code>struct</code> module used in <code>proto.py</code>, after I learned that <code>int</code> has a built-in <a href=\"https://docs.python.org/3/library/stdtypes.html#int.from_bytes\" rel=\"nofollow noreferrer\"><code>from_bytes</code></a> classmethod.</p>\n\n<p>Furth...
{ "AcceptedAnswerId": "203675", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T10:24:46.433", "Id": "201378", "Score": "6", "Tags": [ "python", "python-3.x", "reinventing-the-wheel", "minecraft", "protocols" ], "Title": "Library for RCON clients" }
201378
<p>I'm trying to find a simplest solution to append a newline character to a string.</p> <p>Although the following code works, I would like to know if it's possible to make the code simpler. (The argument should be <code>const char*</code> and not <code>std::string</code>)</p> <p><strong>My Code :</strong></p> <pre><code>static void sysGui(const char *s) { char buf[1000]; std::strcpy(buf, s); std::size_t size = std::strlen(s); buf[size] = '\n'; buf[size + 1] = '\0'; sys_gui(buf); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T11:49:52.487", "Id": "387811", "Score": "0", "body": "what does sys_gui do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T11:55:00.137", "Id": "387812", "Score": "0", "body": "@ratchetfr...
[ { "body": "<p>If you're really certain of the necessary conditions for this to actually work, a somewhat cleaner way to do the job would be to use <code>sprintf</code>:</p>\n\n<pre><code>static void sysGui(const char *s)\n{\n char buf[1000];\n sprintf(buf, \"%s\\n\", s);\n sys_gui(buf);\n}\n</code></pr...
{ "AcceptedAnswerId": "201390", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T11:43:13.450", "Id": "201379", "Score": "-2", "Tags": [ "c++" ], "Title": "Appending a newline character to a string" }
201379
<pre><code>(defun euclid-sub-wrapper (a b) (euclid-sub (abs a) (abs b))) (defun euclid-sub (a b) (if (eq a b) a (if (&gt; a b) (euclid-sub (- a b) b) (euclid-sub a (- b a))))) </code></pre> <p>The above code is an implementation of the Euclid subtraction algorithm to find the greatest common divisor in lisp (Common Lisp). To make the algorithm work for negative numbers I had to use this wrapper function but I wonder if there is another way to do everything in one function. I do like to keep the recursion and although I could just call <code>(abs a)</code> and <code>(abs b)</code> every time I do a recursive step it is only needed once (and therefor somewhat redundant), so I don't really like that either.</p> <p>If there isn't a way to fix this, could someone maybe give me a better name for the wrapper function and / or the function it is wrapping. Any help would be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:19:39.807", "Id": "387874", "Score": "0", "body": "Which exactly Lisp?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:19:58.773", "Id": "387875", "Score": "0", "body": "Do you mean ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T14:49:40.920", "Id": "201393", "Score": "1", "Tags": [ "algorithm", "recursion", "lisp" ], "Title": "Own implementation of Euclid sub algorithm in Lisp" }
201393
<p>This is my first C program and I'm just looking for some constructive criticism before I start trying to do more with it. Am in quite unfamiliar territory here and am uncertain if I'm releasing all my resources, handling errors, and whatnot "properly".</p> <pre><code>#include &lt;errno.h&gt; #include &lt;share.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #define BUFFER_SIZE 4096 #define DATA_FILE_NAME "X" static inline bool fillBuffer(FILE *, char [], size_t *, size_t *); static inline bool nextCharEquals(FILE *, char [], size_t *, size_t *, char); int main(void) { char buffer[BUFFER_SIZE]; FILE *dataFile = NULL; size_t numBytesRead = 0; size_t numBytesUsed = 0; size_t statusCode = 0; dataFile = _fsopen(DATA_FILE_NAME, "rbS", _SH_DENYWR); if (!dataFile) { goto error; } while ((numBytesUsed &lt; numBytesRead) || fillBuffer(dataFile, buffer, &amp;numBytesRead, &amp;numBytesUsed)) { char c = buffer[numBytesUsed++]; if (('\n' == c) || ('\r' == c)) { if ((c == '\r') &amp;&amp; nextCharEquals(dataFile, buffer, &amp;numBytesRead, &amp;numBytesUsed, '\n')) { numBytesUsed++; } continue; // TODO: something useful... } } error: if (errno) { strerror_s(buffer, BUFFER_SIZE, errno); fprintf(stderr, "%s\n", buffer); statusCode = -1; } exit: if (dataFile) { fclose(dataFile); } return statusCode; } static inline bool fillBuffer(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed) { *numBytesRead = fread(buffer, 1, BUFFER_SIZE, file); *numBytesUsed = 0; return (0 &lt; *numBytesRead); } static inline bool nextCharEquals(FILE *file, char buffer[], size_t *numBytesRead, size_t *numBytesUsed, char value) { return (((*numBytesUsed &lt; *numBytesRead) || fillBuffer(file, buffer, numBytesRead, numBytesUsed)) &amp;&amp; (buffer[*numBytesUsed] == value)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:11:08.467", "Id": "387872", "Score": "0", "body": "It's generally helpful to have at least some description of what the code is intended to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:24...
[ { "body": "<pre><code>static inline bool fillBuffer(FILE *, char [], size_t *, size_t *);\n</code></pre>\n\n<p>It'd be nice to provide names for these function parameters, especially since two of them have the same type (<code>size_t *</code>).</p>\n\n<p>It's fairly unusual to see a pointer parameter declared w...
{ "AcceptedAnswerId": "201499", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T14:55:48.893", "Id": "201394", "Score": "0", "Tags": [ "c", "windows" ], "Title": "read line endings sequentially" }
201394
<p>I've written a very simple linked list based stack implementation and was wondering if this is the standard way to do it in C.</p> <pre><code>typedef struct Node { int value; struct Node *prev; } Node; Node * push(Node *top, int value) { Node *node = (Node *) malloc(sizeof(Node)); node-&gt;value = value; node-&gt;prev = top; return node; } Node * pop(Node *top, int *val_addr) { *val_addr = top-&gt;value; Node *new_top = top-&gt;prev; free(top); return new_top; } int is_empty(Node *top) { return top == NULL; } </code></pre> <p>Before deciding to post on code review I decided to check google for stack implementations to see if mine was okay. But most of the decent sources that I checked used an array implementation. I was wondering in what situation is it better to use a dynamic array based stack?</p>
[]
[ { "body": "<p>A dynamic array based stack will use less memory, as it does not have to store an address with each element. It will probably be faster for push because it doesn't need to make an allocation each time.</p>\n\n<p>The main benefit of using a linked list is immutability. With a linked list, you can m...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:30:07.040", "Id": "201399", "Score": "3", "Tags": [ "algorithm", "c", "array", "linked-list", "stack" ], "Title": "A Stack Implementation In C" }
201399
<p>I've been working on a solution to Pset3 of CS50 Harvard course for last couple of hours and managed to finish it. Although it works as intended I'm unhappy with how clean this code is, mostly because of use of multiple nested conditionals inside the main switch case. The function takes a string, for example "B#3", and converts it to correct frequency.</p> <p>If interested <a href="https://docs.cs50.net/2018/x/psets/3/music/music.html" rel="noreferrer">here</a> is the Pset and <a href="https://pages.mtu.edu/~suits/notefreqs.html" rel="noreferrer">here</a> is the frequency table.</p> <pre><code>// Calculates frequency (in Hz) of a note int frequency(string note) { const double a4Frequency = 440; char key; float numOfSemitones = 0; double octave = 0; bool flat, sharp; // Determine octave and whether key is sharp or flat if (note[1] == 'b') { octave = note[2] - '0'; flat = true; } else if(note[1] == '#') { octave = note[2] - '0'; sharp = true; } else octave = note[1] - '0'; key = note[0]; // Base frequency knowing that A4 is 440 hz if(((key == 'A') &amp;&amp; (octave == 4)) &amp;&amp; ((!flat) &amp;&amp; (!sharp))) return 440; // TODO find alternative way to count distance between keys - there is a pattern // Count frequency using distance in semitones from A4 double frequency = 0.0; switch(key) { case 'B': if (flat) numOfSemitones = 1; else numOfSemitones = 2; frequency = pow(2, (numOfSemitones / 12)) * a4Frequency; break; case 'A': if (flat){ numOfSemitones = 1; frequency = a4Frequency / pow(2, (numOfSemitones / 12)); } else if (sharp){ numOfSemitones = 1; frequency = pow(2, (numOfSemitones / 12)) * a4Frequency; } else frequency = a4Frequency; break; case 'G': if (flat) numOfSemitones = 3; else if (sharp) numOfSemitones = 1; else numOfSemitones = 2; frequency = a4Frequency / pow(2, (numOfSemitones / 12)); break; case 'F': if (sharp) numOfSemitones = 3; else numOfSemitones = 4; frequency = a4Frequency / pow(2, (numOfSemitones / 12)); break; case 'E': if (flat) numOfSemitones = 6; else numOfSemitones = 5; frequency = a4Frequency / pow(2, (numOfSemitones / 12)); break; case 'D': if (flat) numOfSemitones = 8; else if (sharp) numOfSemitones = 6; else numOfSemitones = 7; frequency = a4Frequency / pow(2, (numOfSemitones / 12)); break; case 'C': if (sharp) numOfSemitones = 8; else numOfSemitones = 9; frequency = a4Frequency / pow(2, (numOfSemitones / 12)); break; } // Multiply or divide frequency to get note in correct octave int final; if (octave &gt; 4) { octave = pow(2, (octave - 4)); final = round(frequency * octave); } else if (octave == 4) { octave = 0.0; final = round(frequency); } else { octave = pow(2, (4 - octave)); final = round(frequency / octave); } return final; } </code></pre> <p>I'm trying to focus on writing clean code from start, yet this solutions seems a bit hacked to me. How can I make this code more readable? What's the alternative to nested conditionals? What's "illegal" about this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T18:02:00.083", "Id": "387891", "Score": "1", "body": "@Peter please leave the indentation as is, unless it isn't formatted as code. Refer to [this meta answer](https://codereview.meta.stackexchange.com/a/763/120114) as to why and al...
[ { "body": "<p>I believe if you want to write \"cleaner looking\" code you could implement a hashtable.</p>\n\n<p><a href=\"https://stackoverflow.com/a/4384446/1575353\">This answer goes over how to create a hashtable</a>.</p>\n\n<p>I think for your purposes it might be a little bit overkill, since your data set...
{ "AcceptedAnswerId": "201439", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T16:52:35.923", "Id": "201401", "Score": "7", "Tags": [ "beginner", "c", "music" ], "Title": "Calculating frequency of a note from a string" }
201401
<p>Here is a static class with some helper methods for some common LINQ operations on enumerables, built against .NET Framework 2.0. This class is part of the <a href="https://github.com/spearson/xofz.Core98" rel="nofollow noreferrer">xofz.Core98</a> library.</p> <p>Edit: a full review is not necessary. Any limitations or irritations discovered would be much appreciated. The code here is provided free for your use either via the library or by copy and pasting it into your own project.</p> <pre><code>namespace xofz { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; public static class EnumerableHelpers { public static IEnumerable&lt;TResult&gt; Select&lt;T, TResult&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, TResult&gt; selector) { if (source == default(IEnumerable&lt;T&gt;)) { yield break; } if (selector == default(Func&lt;T, TResult&gt;)) { yield break; } foreach (var item in source) { yield return selector(item); } } public static IEnumerable&lt;TResult&gt; SelectMany&lt;T, TResult&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, IEnumerable&lt;TResult&gt;&gt; selector) { if (source == default(IEnumerable&lt;T&gt;)) { yield break; } if (selector == default(Func&lt;T, IEnumerable&lt;TResult&gt;&gt;)) { yield break; } foreach (var item in source) { foreach (var selectee in selector(item)) { yield return selectee; } } } public static IEnumerable&lt;T&gt; Where&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == default(IEnumerable&lt;T&gt;)) { yield break; } if (predicate == default(Func&lt;T, bool&gt;)) { yield break; } foreach (var item in source) { if (predicate(item)) { yield return item; } } } public static IEnumerable&lt;T&gt; Skip&lt;T&gt;( IEnumerable&lt;T&gt; source, int numberToSkip) { if (source == default(IEnumerable&lt;T&gt;)) { yield break; } var currentIndex = 0; foreach (var item in source) { ++currentIndex; if (currentIndex &gt; numberToSkip) { yield return item; } } } public static T First&lt;T&gt;( IEnumerable&lt;T&gt; source) { if (source == default(IEnumerable&lt;T&gt;)) { throw new InvalidOperationException( "The enumerable is null and therefore " + "does not have a first item. If this can happen, " + "consider using FirstOrDefault&lt;T&gt;()"); } foreach (var item in source) { return item; } throw new InvalidOperationException( "The enumerable is empty and therefore " + "does not have a first item. If this can happen, " + "consider using FirstOrDefault&lt;T&gt;()"); } public static T First&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == default(IEnumerable&lt;T&gt;)) { throw new InvalidOperationException( "The enumerable is null and therefore " + "does not have a first item. If this can happen, " + "consider using FirstOrDefault&lt;T&gt;()"); } var empty = true; foreach (var item in source) { empty = false; if (predicate(item)) { return item; } } if (empty) { throw new InvalidOperationException( "The enumerable is empty and therefore " + "does not have a first item. If this can happen, " + "consider using FirstOrDefault&lt;T&gt;()"); } throw new InvalidOperationException( "The non-empty enumerable did not have any elements " + "which matched the predicate."); } public static T FirstOrDefault&lt;T&gt;( IEnumerable&lt;T&gt; source) { if (source == default(IEnumerable&lt;T&gt;)) { return default(T); } foreach (var item in source) { return item; } return default(T); } public static T FirstOrDefault&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == default(IEnumerable&lt;T&gt;)) { return default(T); } foreach (var item in source) { if (predicate(item)) { return item; } } return default(T); } public static bool Any&lt;T&gt;( IEnumerable&lt;T&gt; source) { if (source == null) { return false; } foreach (var item in source) { return true; } return false; } public static bool Any&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == null) { return false; } foreach (var item in source) { if (predicate(item)) { return true; } } return false; } public static bool All&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == null) { return true; } foreach (var item in source) { if (!predicate(item)) { return false; } } return true; } public static bool Contains&lt;T&gt;( IEnumerable&lt;T&gt; source, T item) { if (source == default(IEnumerable&lt;T&gt;)) { return false; } var itemIsNull = item == null; foreach (var itemInSource in source) { if (itemInSource == null &amp;&amp; itemIsNull) { return true; } if (item?.Equals(itemInSource) ?? false) { return true; } } return false; } public static IEnumerable&lt;T&gt; Cast&lt;T&gt;( IEnumerable source) { if (source == null) { yield break; } foreach (var item in source) { yield return (T)item; } } public static int Count&lt;T&gt;( IEnumerable&lt;T&gt; source) { if (source == default(IEnumerable&lt;T&gt;)) { return default(int); } var totalCount = 0; foreach (var item in source) { ++totalCount; } return totalCount; } public static int Count&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == default(IEnumerable&lt;T&gt;)) { return default(int); } var totalCount = 0; foreach (var item in source) { if (predicate(item)) { ++totalCount; } } return totalCount; } public static long LongCount&lt;T&gt;( IEnumerable&lt;T&gt; source) { if (source == default(IEnumerable&lt;T&gt;)) { return default(int); } long totalCount = 0; foreach (var item in source) { ++totalCount; } return totalCount; } public static long LongCount&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) { if (source == default(IEnumerable&lt;T&gt;)) { return default(int); } long totalCount = 0; foreach (var item in source) { if (predicate(item)) { ++totalCount; } } return totalCount; } public static T[] ToArray&lt;T&gt;(IEnumerable&lt;T&gt; source) { if (source == default(IEnumerable&lt;T&gt;)) { return new T[0]; } var ll = new LinkedList&lt;T&gt;(); foreach (var item in source) { ll.AddLast(item); } var array = new T[ll.Count]; ll.CopyTo(array, 0); return array; } public static List&lt;T&gt; ToList&lt;T&gt;( IEnumerable&lt;T&gt; source) { return new List&lt;T&gt;(source); } public static ICollection&lt;T&gt; OrderBy&lt;T, TKey&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, TKey&gt; keySelector) { return orderBy( source, keySelector, Comparer&lt;TKey&gt;.Default, false); } public static ICollection&lt;T&gt; OrderBy&lt;T, TKey&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, TKey&gt; keySelector, IComparer&lt;TKey&gt; comparer) { return orderBy( source, keySelector, comparer, false); } public static ICollection&lt;T&gt; OrderByDescending&lt;T, TKey&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, TKey&gt; keySelector) { return orderBy( source, keySelector, Comparer&lt;TKey&gt;.Default, true); } public static ICollection&lt;T&gt; OrderByDescending&lt;T, TKey&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, TKey&gt; keySelector, IComparer&lt;TKey&gt; comparer) { return orderBy( source, keySelector, comparer, true); } private static ICollection&lt;T&gt; orderBy&lt;T, TKey&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, TKey&gt; keySelector, IComparer&lt;TKey&gt; comparer, bool descending) { if (source == default(IEnumerable&lt;T&gt;)) { return new List&lt;T&gt;(); } if (keySelector == default(Func&lt;T, TKey&gt;)) { return new List&lt;T&gt;(); } var d = new Dictionary&lt;TKey, IList&lt;T&gt;&gt;(); var itemsWithNullKeys = new LinkedList&lt;T&gt;(); foreach (var item in source) { var key = keySelector(item); if (key == null) { itemsWithNullKeys.AddLast(item); continue; } if (!d.ContainsKey(key)) { d.Add(key, new List&lt;T&gt;()); } d[key].Add(item); } var keyList = new List&lt;TKey&gt;(d.Keys); keyList.Sort(comparer); if (descending) { keyList.Reverse(); } var finalList = new List&lt;T&gt;(); foreach (var key in keyList) { finalList.AddRange(d[key]); } finalList.AddRange(itemsWithNullKeys); return finalList; } public static TEnd Aggregate&lt;T, TEnd&gt;( IEnumerable&lt;T&gt; source, TEnd seed, Func&lt;TEnd, T, TEnd&gt; accumulator) { if (source == default(IEnumerable&lt;T&gt;)) { return default(TEnd); } if (accumulator == default(Func&lt;TEnd, T, TEnd&gt;)) { return default(TEnd); } var end = seed; foreach (var item in source) { end = accumulator(end, item); } return end; } public static IEnumerable&lt;T&gt; OfType&lt;T&gt;(IEnumerable source) { if (source == null) { yield break; } foreach (var item in source) { if (item is T t) { yield return t; } } } public static IEnumerable&lt;T&gt; SafeForEach&lt;T&gt;(IEnumerable&lt;T&gt; source) { if (source == default(IEnumerable&lt;T&gt;)) { yield break; } foreach (var item in source) { yield return item; } } public static IEnumerable&lt;T&gt; Iterate&lt;T&gt;(params T[] items) { foreach (var item in items) { yield return item; } } public static IEnumerable&lt;T&gt; PrivateFieldsOfType&lt;T&gt;( object o) { if (o == null) { yield break; } foreach (var fieldInfo in o.GetType().GetFields( BindingFlags.Instance | BindingFlags.NonPublic)) { var value = fieldInfo.GetValue(o); if (value is T t) { yield return t; } } } public static int Sum&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, int&gt; valueComputer) { if (source == null) { return 0; } var sum = 0; foreach (var item in source) { checked { sum += valueComputer(item); } } return sum; } public static long Sum&lt;T&gt;( IEnumerable&lt;T&gt; source, Func&lt;T, long&gt; valueComputer) { if (source == null) { return 0; } long sum = 0; foreach (var item in source) { checked { sum += valueComputer(item); } } return sum; } public static int Min( IEnumerable&lt;int&gt; source) { if (source == null) { return 0; } var min = int.MaxValue; var minChanged = false; foreach (var item in source) { minChanged = true; if (item &lt; min) { min = item; } } if (!minChanged) { return 0; } return min; } public static long Min( IEnumerable&lt;long&gt; source) { if (source == null) { return 0; } var min = long.MaxValue; var minChanged = false; foreach (var item in source) { minChanged = true; if (item &lt; min) { min = item; } } if (!minChanged) { return 0; } return min; } public static int Max( IEnumerable&lt;int&gt; source) { if (source == null) { return 0; } var max = 0; foreach (var item in source) { if (item &gt; max) { max = item; } } return max; } public static long Max( IEnumerable&lt;long&gt; source) { if (source == null) { return 0; } long max = 0; foreach (var item in source) { if (item &gt; max) { max = item; } } return max; } public static ICollection&lt;T&gt; Reverse&lt;T&gt;( IEnumerable&lt;T&gt; source) { var ll = new LinkedList&lt;T&gt;(); foreach (var item in source) { ll.AddFirst(item); } return ll; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T17:55:40.813", "Id": "387887", "Score": "4", "body": "This is a lot of code and none description at all. Could you write something more about it? What is so special about your code? What is your code doing and why? What is it solvin...
[ { "body": "<p>These are (to me) unexpected:</p>\n\n<pre><code>if (source == default(IEnumerable&lt;T&gt;))\n{\n yield break;\n}\n\nif (selector == default(Func&lt;T, IEnumerable&lt;TResult&gt;&gt;))\n{\n yield break;\n}\n</code></pre>\n\n<p>LINQ itself crashes helpfully if you pass <code>null</code> to <c...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T17:52:48.160", "Id": "201406", "Score": "4", "Tags": [ "c#", ".net", "linq" ], "Title": "EnumerableHelpers: a partial implementation of LINQ for .NET Framework 2.0" }
201406
<p>I'm fairly new to python and pandas but trying to get better with it for parsing and processing large data files. I'm currently working on a project that requires me to parse a a few hundred CSV CAN files at the time. The files have 9 columns of interest (1 ID and 7 data fields), have about 1-2 million rows, and are encoded in hex.</p> <pre><code> id Flags DLC Data0 Data1 Data2 Data3 Data4 Data5 Data6 Data7 cf11505 4 1 ff cf11505 4 1 ff cf11505 4 1 ff cf11a05 4 1 0 cf11505 4 1 ff cf11505 4 1 ff cf11505 4 1 ff cf11005 4 8 ff ff ff ff ff ff ff ff </code></pre> <p>I need to decode the hex, and then extract a bunch of different variables from it depending on the CAN ID.</p> <p>I wrote a script to parse these files that looks like this:</p> <pre><code>import os import csv # imports the csv module import itertools import datetime import time from tkinter import filedialog from tkinter import Tk Tk().withdraw() filenames = filedialog.askopenfiles(title="Select .csv log file", filetypes=(("CSV files", "*.csv"), ("all files", "*.*"))) start = time.clock() flist = [] for name in filenames: flist.append(name.name) for filename in flist: cur_file = ''.join(filename.split('/')[-1:]) print('working on ' + cur_file +'...') time_s = 0 var = [0,0,0,0] var4 = 0 var5 = 0 var6 = 0 var7 = 0 var8 = 0 var9 = 0 var10 = 0 var11 = 0 var12 = 0 ###########create new filename and filepath cur_file = ''.join(filename.split('/')[-1:]) #pulls filename of current file folders_to_append = '/Log Files--Processed/' + '/'.join(flist[0].split('/')[-3:-1]) #folders to append to new filepath trunc_filepath = '/'.join(filename.split('/')[0:-4]) new_filepath = trunc_filepath + folders_to_append + '/' new_filename= trunc_filepath + folders_to_append + '/processed_' + cur_file if not os.path.exists(new_filepath): os.makedirs(new_filepath) ########################################## csvInput = open(filename, 'r') # opens the csv file csvOutput = open(new_filename, 'w', newline='') writer = csv.writer(csvOutput) #creates the writer object writer.writerow(['Date','Time Since Start (s)', 'var1', 'var2', 'var3', 'var4', 'var5', 'var6', 'var7', 'var8', 'var9', 'var10', 'var11', 'var12', 'var13', 'var14', 'var15', 'var16']) try: reader = csv.reader(csvInput) data=list(reader) if (data[3][1] == 'HEX'): dataType = 16 elif (data[3][1] == 'DEC'): dataType = 10 else: print('Invalid Data Type') if (data[4][1] == 'HEX'): idType = 16 elif (data[4][1] == 'DEC'): idType = 10 else: print('Invalid ID Type') start_date = datetime.datetime.strptime(data[6][1],'%Y-%m-%d %H:%M:%S') for row in itertools.islice(data,8,None): #print(row) try: ID = int(row[2],idType) except: ID = 0 #print(ID) if (ID == 0xcf11005): for i in range(0,4): var[i] = float((int(row[2*i+6],dataType)&lt;&lt;8)|(int(row[2*i+5],dataType)))/10 elif (ID == 0xcf11505): var4 = int(row[5],dataType) elif (ID == 0xcf11605): var8 = str(bin(int(row[5],dataType))) var9 = str(bin(int(row[6],dataType))); elif (ID == 0xcf11a05): var10 = row[5] elif (ID == 0xcf11e05): var11 = float((int(row[6],dataType)&lt;&lt;8)|(int(row[5],dataType))) var12 = float((int(row[8],dataType)&lt;&lt;8)|(int(row[7],dataType))) var13 = float((int(row[10],dataType)&lt;&lt;8)|(int(row[9],dataType))) elif (ID == 0xcf11f05): var14 = int(row[5],dataType) var15 = int(row[6],dataType)-40 var16 = int(row[7],dataType)-40 else: continue time_s = float(row[0]) date = start_date+datetime.timedelta(seconds=time_s) writer.writerow([date,time_s, var[0], var[1], var[2], var[3], var4, var5, var6, var7, var8, var9, var10, var11, var12]) finally: csvInput.close() csvOutput.close() end = time.clock() print(end - start) print('done') </code></pre> <p>It basically uses the CSV reader and writer to generate a processed CSV file line by line for each CSV. For a 2 million row CSV CAN file, it takes about 40 secs to fully run on my work desktop. Knowing that line by line iteration is much slower than performing vectorized operations on a pandas dataframe, I thought I could do better, so I wrote a separate script (which I'll call script #2) where all the math was performed in a vectorized fashion, and then I used pandas .to_csv() function. Unfortunately, with script #2, the .to_csv() function took as long to run as the entire script #1, so it didn't end up being faster. I played around with the chunk size of .to_csv(), but I never managed to improve the runtime more than a second or so.</p> <p>Is using the CSV reader/writer really the fastest way to do this? And if so, is there any way I can make my code run faster? </p>
[]
[ { "body": "<p>I will avoid using <code>pandas</code> for now, since it can be really easy to say \"pandas will make X faster\" and miss out on making what is currently written performant, even though it may be true. Someone else can show the light of numpy/pandas as it pertains to this example.</p>\n\n<h1>Style...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T18:04:24.420", "Id": "201408", "Score": "7", "Tags": [ "python", "csv", "pandas" ], "Title": "Fastest way to write large CSV file in python" }
201408
<p>I've got the following code which is ran inside tampermonkey (It's a userscript), but there is a variable that is being declared, used, then overwritten by the next line. I'm looking for a way to shorten this code, or possibly remove the line if I can get the same results another way.</p> <pre><code>$(function() { /***** RELATED TAGS *****/ var oldtags = main_content.find('div#related-tags, .module.js-gps-related-tags'); var vctags = genSBWidget('Related Tags', '&lt;svg aria-hidden="true" class="svg-icon" width="18" height="18" viewBox="0 0 24 24"&gt;&lt;path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"&gt;&lt;/path&gt;&lt;/svg&gt;', 'relatedtags'); oldtags.before(vctags).children('h4, a').remove().parent(); vctags = main_content.find('div#visualcrumbs-relatedtags'); //THIS LINE vctags.prepend(oldtags.children()).children().wrapAll('&lt;div class="js-watched-tag-list grid gs4 py4 fw-wrap"&gt;').each(function() { $(this).toggleClass('dno js-hidden js-tag grid--cell').children().slice(1).remove(); }); }); </code></pre> <p>genSBWidget simply generates some HTML, not sure if this is really relevant but I'll post the function anyways:</p> <pre><code>function genSBWidget(title, icon, innerid) { var widget = '\ &lt;div class="s-sidebarwidget" style="margin-bottom:19.500px;"&gt;\ &lt;div class="s-sidebarwidget--header grid"&gt;\ &lt;span class="grid--cell mr4"&gt;'+ icon +'&lt;/span&gt;\ &lt;span class="grid--cell fl1"&gt;' + title + '&lt;/span&gt;\ &lt;/div&gt;\ &lt;div id="visualcrumbs-'+ innerid +'" class="s-sidebarwidget--content fd-column"&gt;&lt;/div&gt;\ &lt;/div&gt;\ '; return widget; } </code></pre> <p>Side not: This script just takes "Related tags" in the right sidebar of stackoverflow and puts it into one of the new style boxes in the sidebar, and gives it the same styling as Watched Tags.</p> <p>My actual userscript works on more than just related tags, it converts everything in the sidebar into this new style box, what I'm hoping to do from this question is learn some new methods of doing what I'm trying to do with related tags, so I can expand this accross my entire script.</p> <p>Here is a minimal example of the script:</p> <pre><code>// ==UserScript== // @name Related Tags Beautifier // @namespace https://github.com/GrumpyCrouton/Userscripts // @version 1.0 // @description Customizes StackExchange to your liking. // @author GrumpyCrouton // @match *://*.stackoverflow.com/* // @grant none // ==/UserScript== (function() { 'use strict'; var $ = window.jQuery; /***** GLOBAL SITE CHANGES *****/ var main_content = $('body div.container').find('div#content'); $(function() { /***** RELATED TAGS *****/ var oldtags = main_content.find('div#related-tags, .module.js-gps-related-tags'); var vctags = genSBWidget('Related Tags', '&lt;svg aria-hidden="true" class="svg-icon" width="18" height="18" viewBox="0 0 24 24"&gt;&lt;path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"&gt;&lt;/path&gt;&lt;/svg&gt;', 'relatedtags'); oldtags.before(vctags).children('h4, a').remove().parent(); vctags = main_content.find('div#visualcrumbs-relatedtags'); vctags.prepend(oldtags.children()).children().wrapAll('&lt;div class="js-watched-tag-list grid gs4 py4 fw-wrap"&gt;').each(function() { $(this).toggleClass('dno js-hidden js-tag grid--cell').children().slice(1).remove(); }); }); function genSBWidget(title, icon, innerid) { var widget = '\ &lt;div class="s-sidebarwidget" style="margin-bottom:19.500px;"&gt;\ &lt;div class="s-sidebarwidget--header grid"&gt;\ &lt;span class="grid--cell mr4"&gt;'+ icon +'&lt;/span&gt;\ &lt;span class="grid--cell fl1"&gt;' + title + '&lt;/span&gt;\ &lt;/div&gt;\ &lt;div id="visualcrumbs-'+ innerid +'" class="s-sidebarwidget--content fd-column"&gt;&lt;/div&gt;\ &lt;/div&gt;\ '; return widget; } })(); </code></pre>
[]
[ { "body": "<blockquote>\n <p>[...], but there is a variable that is being declared, used, then overwritten by the next line.</p>\n</blockquote>\n\n<p>Indeed. And it's not clear why it is that way.\nI believe you're talking about <code>vctags</code>, here:</p>\n\n<blockquote>\n<pre><code>vctags = main_content.f...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T18:10:41.463", "Id": "201410", "Score": "2", "Tags": [ "javascript", "jquery", "stackexchange", "userscript" ], "Title": "Tampermonkey script to beautify related tags in Stack Exchange" }
201410
<p>I'm a beginner to PHP and I've written a function that validates a U.K National Insurance Number. The function works by checking whether the given number against the format below;</p> <blockquote> <p>The National Insurance Number (<code>$NINO</code>) is made up of 3 components in the format AAnnnnnnA. The 3 components are the prefix, numeric body and suffix.</p> <p><strong>Prefix</strong></p> <p>The first two alpha characters, validated as follows:</p> <p>• The prefix must not be BG, GB, NK, KN, TN, NT or ZZ</p> <p>• The prefix must not contain D F I Q U or V</p> <p>• The second character of the NINo prefix must not be O</p> <p><strong>Numeric body</strong></p> <p>The 8 numeric characters of the NINO, validated as follows:</p> <p>• Must be numeric in the range 000000 – 999999</p> <p><strong>Suffix</strong></p> <p>The final alpha character; validated as follows:</p> <p>• Must be in the range A – D </p> </blockquote> <pre><code>&lt;?php function validateNI($NINO) { $NILength = strlen($NINO); if (!($NILength &lt; 10 | $NILength &gt; 10)) { $NIParts = str_split($NINO, 2); if(!(preg_match("/[^!@#$%^&amp;*]*(BG|GB|NK|TN|NT|ZZ|D|F|I|Q|U|V)[^!@#$%^&amp;*]*/i", $NIParts[0]))) { $NIPartsSplit = str_split($NIParts[0]); if(preg_match("/[^!@#$%^&amp;*]*(O)[^!@#$%^&amp;*]*/i", $NIPartsSplit[1])) { echo "Invalid National Insurance Number."; } else { $NIPartsNum = $NIParts[1].$NIParts[2].$NIParts[3]; if (is_numeric($NIPartsNum)) { if(preg_match("/[^!@#$%^&amp;*]*(A|B|C|D)[^!@#$%^&amp;*]*/i", $NIParts[4])) { echo "Valid National Insurance Number."; } else { echo "Invalid National Insurance Number."; } } else { echo "Invalid National Insurance Number."; } } } else { echo "Invalid National Insurance Number."; } } else { echo "Invalid National Insurance Number."; } } validateNI("AA1220091A"); ?&gt; </code></pre> <p>I'm looking for advice on how I can reduce the overall lines of code (including the use of regex) as well as increasing the efficiency and simplicity of my code.</p>
[]
[ { "body": "<p>I am happy for you, that you are asking for help with refactoring this scary function.\nFirst of all, you must not write more than 2 indentations with <code>if</code> statements, if you want to be a great developer.</p>\n\n<p>Secondly, when you write a program, keep in your mind that every method ...
{ "AcceptedAnswerId": "201438", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T19:05:55.113", "Id": "201414", "Score": "5", "Tags": [ "beginner", "php" ], "Title": "National Insurance Number Validation" }
201414
<p>I've wrote this code and it does what is expected. However, I'm thinking if there are better ways to write this, specially if is useful to wrap it in a class, or other ways to make it less loosen. I'll be glad and grateful for any others corrections or suggestions.</p> <p><pre>interest_list = [0.5, 0.4, 0.3, 0.5, 0.7, 0.4, -0.2, -0.5, 0.3, 0.7, 0.9, 1.0]</p> <code>def get_unitary(interest_list): unit_list = [] for i in range(len(interest_list)): unit_list.append(1+ interest_list[i]/100) return unit_list # I've tested on some lists and found this faster than using reduce() def prod(uni_list): p = 1 for i in uni_list: p *= i return p def get_accrued(prod): sub_1 = prod -1 return sub_1 * 100 accrued = get_accrued(prod(get_unitary(interest_list))) </code></pre>
[]
[ { "body": "<p>It'd be easier to help if you explained the purpose of the algorithm. </p>\n\n<p>However the obvious simplification is in the <code>get_unitary</code> function. You don't want that list, you only want to work with the values that come back from that operation. So you can omit the creation and pop...
{ "AcceptedAnswerId": "201427", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T19:48:56.127", "Id": "201415", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Python code to get Accrued interest" }
201415
<p>I've created a basic Python CLI script, which takes a Github username, and returns some basic information associated with said username. I use the <a href="http://docs.python-requests.org/en/master/" rel="nofollow noreferrer">requests</a> for HTTP requests (I'm new to this area) and <a href="http://docopt.org/" rel="nofollow noreferrer">docopt</a> for command-line handling.</p> <pre><code>#!/usr/bin/env python3 """Github User Info Get basic information on a Github user Usage: github_user_info.py USERNAME github_user_info.py (-h | --help) github_user_info.py (-v | --version) Arguments: USERNAME Github username Options: -h --help Show this screen. -v --version Show version. """ from docopt import docopt import requests import sys def main(): if len(sys.argv) == 1: sys.argv.append('-h') # Show help screen if no arguments are passed cmd_arguments = docopt(__doc__, version='Github User Info v1.0') username = cmd_arguments["USERNAME"] if len(username.split()) != 1: print('Github usernames must be one word in length! Exiting!') return response = requests.get(f'https://api.github.com/users/{username}') if response.status_code != requests.codes.ok: if response.status_code == 404: # No such user was found print(f'No Github user was found with username {username}!') else: print(f'An unexpected error occured! Exiting with error code: ' f'{response.status_code}') return responses_json = response.json() print(f'The following information was found on user: {username}', end='\n\n') print(f'Name: {responses_json["name"]}') print(f'Bio: {responses_json["bio"]}') print(f'Followers: {responses_json["followers"]}') print(f'Following: {responses_json["following"]}') if __name__ == '__main__': main() </code></pre> <p>I'd mainly like to know if this is the correct way to handle HTTP requests (in terms of getting them, error handling, etc.). I'd also like to make sure that I follow good Python conventions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T06:19:46.563", "Id": "387938", "Score": "0", "body": "as a side note, if you want to pursue the project further, see the pygithub project !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T22:42:03.373...
[ { "body": "<p>Just a note:\ninstead of using <code>string.split()</code> to check for spaces, you can directly check with <code>in</code>.</p>\n\n<p>From:</p>\n\n<blockquote>\n<pre><code>if len(username.split()) != 1:\n print('Github usernames must be one word in length! Exiting!')\n return\n</cod...
{ "AcceptedAnswerId": "201444", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T20:36:40.623", "Id": "201419", "Score": "4", "Tags": [ "python", "python-3.x", "http" ], "Title": "Python program that gets basic information on a Github user" }
201419
<p>I have this code that hypothetically returns multiple rows from a database and encodes them in a JSON. I am wondering if this is the best and most presentable way to do it. </p> <p>Note: I am using msqli not PDO, and procedural php not OOP.</p> <pre><code>&lt;?php $query = $_REQUEST["query"]; require(connect.php); $response = array(); $response["success"] = false; if ($con) { $statement = mysqli_prepare($con, "SELECT * FROM `lecturers_general` WHERE ? IN (lecturer_id, title, first_name, middle_name, last_name, course1, course2, course3, course4, course5, course6, office_number, office_building, department)"); mysqli_stmt_bind_param($statement, "s", $query); mysqli_stmt_execute($statement); $lecturer_id = null; $title = null; $first_name = null; $middle_name = null; $last_name = null; $course1 = null; $course2 = null; $course3 = null; $course4 = null; $course5 = null; $course6 = null; $office_number = null; $office_building = null; $department = $null; mysqli_stmt_bind_result($lecturer_id, $title, $first_name, $middle_name, $last_name, $course1, $course2, $course3, $course4, $course5, $course6, $office_number, $office_building, $department); // $rows = mysqli_fetch_assoc($statement); $num_rows = mysqli_num_rows($statement); if ($num_rows &gt;= 1) { do { $lecturer_id = $rows["lecturer_id"]; $title = $rows["title"]; $first_name = $rows["first_name"]; $middle_name = $rows["middle_name"]; $last_name = $rows["last_name"]; $course1 = $rows["course1"]; $course2 = $rows["course2"]; $course3 = $rows["course3"]; $course4 = $rows["course4"]; $course5 = $rows["course5"]; $course6 = $rows["course6"]; $office_number = $rows["office_number"]; $office_building = $rows["office_building"]; $department = $rows["department"]; $result['lecturers: '][] = array('lecturer_id' =&gt; $lecturer_id,'title' =&gt; $title,'first_name' =&gt; $first_name,'middle_name' =&gt; $middle_name,'last_name' =&gt; $last_name,'course1' =&gt; $course1,'course2' =&gt; $course2,'course3' =&gt; $course3,'course4' =&gt; $course4,'course5' =&gt; $course5,'course6' =&gt; $course6,'office_number' =&gt; $office_number,'office_building' =&gt; $office_building,'department' =&gt; $department); } while($rows = mysqli_fetch_assoc($statement)); echo json_encode($result); } else { echo 'No results'; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T21:24:11.217", "Id": "387913", "Score": "0", "body": "are there any columns in the `lecturers_general` table that should not go into JSON data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T21:31:40...
[ { "body": "<p>Because you replied to my question: </p>\n\n<blockquote>\n <p>are there any columns in the <code>lecturers_general</code> table that should not go into JSON data? </p>\n</blockquote>\n\n<p>With the answer:</p>\n\n<blockquote>\n <p>Nope... all columns are to be returned.</p>\n</blockquote>\n\n<p>...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T20:51:20.727", "Id": "201421", "Score": "1", "Tags": [ "php", "mysql", "json", "mysqli" ], "Title": "Encoding multiple rows from prepared statement in php" }
201421
<p>I have been making an effort to add a fair amount of unit testing into my code. However, I find myself going against the DRY principle quite a bit.</p> <p>I am currently running tests on my API with my tests in the following folder structure:</p> <pre><code>/user user.model.js user.test.js .... /blog blog.model.js blog.test.js .... </code></pre> <p>Ive been using wildcards in my script test path to target all my test files <code>nodemon --exec 'mocha ../api/resources/**/*.test.js'</code></p> <p>I have noticed all my test files have a lot of stuff to require. Most of which is the same in each of the test files, example:</p> <pre><code>const chai = require('chai') const chaiHttp = require('chai-http') const { expect } = chai const app = require('../../../app') const { dropDb } = require('../../../test/helpers') const mongoose = require('mongoose') const User = mongoose.model('user') chai.use(chaiHttp) </code></pre> <p>And my tests have a lot of duplicate 'expect' statements</p> <pre><code>it('should return error when no user email found', async () =&gt; { const result = await chai.request(app) .post('/api/user/login') .send({ email: 'fail@email.com', password: currentUserData.password }) *expect(result).to.have.status(401) expect(result.error).to.exist expect(result.error.text).to.contain('No user found')* }) it('should return error when password is incorrect', async () =&gt; { const result = await chai.request(app) .post('/api/user/login') .send({ email: currentUserData.email, password: '123456' }) *expect(result).to.have.status(401) expect(result.error).to.exist expect(result.error.text).to.contain('Incorrect password')* }) </code></pre> <p>As you can see from the above tests the expect statements are basically the same minus the text. I have a lot of other tests where I have expects that check to make sure its JSON data or 200 before the more specific expects.</p> <p>To me it feels as if I am repeating myself quite a bit on the requires and the expect statements. Is this standard practice or could I create some sort of higher order function to run the tests without having to require all the time.</p> <p>Additionally, can I reuse a function with similar expect statements in it?</p>
[]
[ { "body": "<p>One of the recommended techniques for tests is refactor into an assert method. Duplications drive into fragile tests. </p>\n\n<p>You should also try to create factory methods for the SUT.</p>\n\n<pre><code>it('should return error when password is incorrect', async () =&gt; {\n // Arrange\n c...
{ "AcceptedAnswerId": "201457", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T22:21:17.663", "Id": "201429", "Score": "1", "Tags": [ "javascript", "unit-testing", "mocha" ], "Title": "Mocha + chai tests" }
201429
<p>I just submitted a Python solution to the <a href="https://leetcode.com/problems/two-sum/description/" rel="nofollow noreferrer">'Two Sum' problem on LeetCode</a>.</p> <h2>The Problem</h2> <blockquote> <p>Given an array of integers, <strong>return indices</strong> of the two numbers such that they add up to a specific target.</p> <p>You may assume that each input would have <strong>exactly one solution</strong>, and you may not use the same element twice.</p> <h3>Example</h3> <p>Given <code>nums = [2, 7, 11, 15]</code>, <code>target = 9</code></p> <p>Because <code>nums[0] + nums[1] = 2 + 7 = 9</code></p> <p>return <code>[0, 1]</code>.</p> </blockquote> <h2>My Solution</h2> <pre><code>class Solution: def twoSum(self, nums, target): number_bonds = {} for index, value in enumerate(nums): if value in number_bonds: return [number_bonds[value], index] number_bonds[target - value] = index return None </code></pre> <p>It was accepted and then told me the following:</p> <blockquote> <p>Your runtime beats 83.12 % of python3 submissions.</p> </blockquote> <p>This means that 16.88% of python3 submissions were more efficient than this one.</p> <p>How can I get this more efficient than the solution provided above? Is there a funky way to do this with numpy that I'm not getting? Is there maybe another data structure I should use in this situation? Or a better algorithm altogether? I've explored a few alternate solutions and profiled with <code>timeit</code> but none were faster than this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T22:54:54.120", "Id": "387924", "Score": "5", "body": "Why the unnecessary class? Is that part of the challenge?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T09:09:43.783", "Id": "387946", "...
[ { "body": "<p>I think your solution is already pretty good. It is at worst \\$\\mathcal{O}(n)\\$ in both runtime and memory. You use <code>enumerate</code> instead of iterating over the indicies manually.</p>\n\n<p>The only four things I would comment on are:</p>\n\n<ol>\n<li>In real life code, this being a <co...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T22:51:57.810", "Id": "201431", "Score": "9", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "k-sum" ], "Title": "Python 3 two-sum performance" }
201431
<p>I have a function that generates HTML for hyperlinks. It's arguments may be string literals or variables read from the database. An example call to this function looks like:</p> <pre><code>hLink('http://example.com', 'website', 'section', 'input=0', '_blank'); </code></pre> <p>which returns:</p> <pre><code>'&lt;a HRef="http://example.com?input=0#section" target="_blank"&gt;website&lt;/a&gt;' </code></pre> <p>The first argument is required, and the remaining four have defaults.</p> <p>In my first foray into object-oriented programming, I've written a replacement for this function by a method defined in a class, so the function calls are replaced with calls to that method acting on an object from that class. I've written two versions:</p> <ul> <li><p>In the first version, each link works by creating a new instance of the class, with the required arguments of <code>hLink()</code> handled by the class constructor, and optional arguments handled by setting properties of the object, and then an output method <code>hLink()</code> finally acting on those properties to generate the HTML link. If you want to see the code for this version, it's in the edit history of this question, but I've removed it in favor of the second version, which I think is probably better.</p></li> <li><p>In the second version, the class has no constructor. One instance of the class is created and all links are generated by this one object. The class has a method <code>clear()</code> that resets all the properties to empty, as well as additional methods to set the values of any properties that are needed, and finally an output method <code>hLink()</code> to generate the HTML link.</p></li> </ul> <p>I wrote the second version because it seemed that the first was wasteful by creating an object for each link, and those objects were never used again after generating the HTML. So the second version reuses the same object repeatedly for this task. </p> <p>The code for the second version is as follows: (Pardon my formatting. I know it's unconventional, but I find this easier to read.)</p> <pre><code>&lt;?php declare(strict_types = 1); $oLink = new link; class link {private $sURL; private $sText; private $sAnchor; private $sQuery; private $sWindow; public function clear() {$this-&gt;sURL = ''; $this-&gt;sText = ''; $this-&gt;sAnchor = ''; $this-&gt;sQuery = ''; $this-&gt;sWindow = ''; return $this; } public function URL(string $sURL) {$this-&gt;sURL = $sURL; return $this;} public function text(string $sText) {$this-&gt;sText = $sText; return $this;} public function anchor(string $sAnchor) {$this-&gt;sAnchor = $sAnchor; return $this;} public function query(string $sQuery) {$this-&gt;sQuery = $sQuery; return $this;} public function window(string $sWindow) {$this-&gt;sWindow = $sWindow; return $this;} public function hLink() {return('&lt;a HRef="' . $this-&gt;sURL . ($this-&gt;sQuery == '' ? '' : '?' . $this-&gt;sQuery) . ($this-&gt;sAnchor == '' ? '' : '#' . $this-&gt;sAnchor) . '"' . ($this-&gt;sWindow == '' ? '' : ' target="' . $this-&gt;sWindow . '"') . '&gt;' . $this-&gt;sText . '&lt;/a&gt;'); } } echo('&lt;p&gt;Link to ' . $oLink-&gt;clear()-&gt;URL('http://example.com')-&gt;text('website')-&gt;anchor('section')-&gt;query('input=0')-&gt;window('_blank')-&gt;hLink() . ' in text&lt;/p&gt;'); </code></pre> <p>I've tested the above code as a freestanding script, and it does output the intended:</p> <pre><code>&lt;p&gt;Link to &lt;a HRef="http://example.com?input=0#section" target="_blank"&gt;website&lt;/a&gt; in text&lt;/p&gt; </code></pre> <p>I'd like to know if I'm doing this right, or even if I should be doing this at all (i.e., if this is a sensible use of objects). Is this the best way to generate HTML for hyperlinks embedded in text in PHP?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-17T14:10:54.193", "Id": "388955", "Score": "2", "body": "Being [discussed on meta](https://codereview.meta.stackexchange.com/questions/8943/please-reopen-php-object-for-html-hyperlink)" }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>For the suggested use case having an object is an overkill.</p>\n\n<p>As far as I can tell from the code provided, every link is generated only once, which makes class variables; a dedicated method to clean the state; and a code to instantiate an object all unnecessary. So a function would be more...
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T23:15:35.673", "Id": "201432", "Score": "0", "Tags": [ "php", "object-oriented", "html", "url" ], "Title": "Object for generating HTML for hyperlinks" }
201432
<p>How can I remove the code duplication in this code? It is trying to cast the left and right numbers as integers or doubles and then using it.</p> <pre><code>public Object example(Object left, Object right) { if(left instanceof Integer &amp;&amp; right instanceof Integer) { switch (operator) { case ADD: return (Integer)left + (Integer)right; case SUB: return (Integer)left - (Integer)right; case MUL: return (Integer)left * (Integer)right; case DIV: return (Integer)left / (Integer)right; } } else if(left instanceof Double &amp;&amp; right instanceof Double) { switch (operator) { case ADD: return (Double)left + (Double)right; case SUB: return (Double)left - (Double)right; case MUL: return (Double)left * (Double)right; case DIV: return (Double)left / (Double)right; } } else { throw new Error("wrong types of arguments"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T04:33:59.330", "Id": "388016", "Score": "1", "body": "Please provide the context for this code. Where do the inputs come from? What function is this, and what is its return type?" }, { "ContentLicense": "CC BY-SA 4.0", "...
[ { "body": "<p>One option would be to do your math operations on a double. You can use a generic method that accepts any derivative of the Number class and use the <code>doubleValue()</code> method for your calculation. The caller of the method can cast to Integer as needed:</p>\n\n<pre><code>enum Operators {\...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-10T23:53:45.917", "Id": "201433", "Score": "0", "Tags": [ "java", "casting" ], "Title": "Casting the left and right numbers as integers or doubles" }
201433
<p>Over on SO I posted a question: <a href="https://stackoverflow.com/q/51491008/1682405">Change transition duration during loop with requestAnimationFrame</a> which hasn't got any responses just yet. I've since come up with this idea and wanted to know if there was any way to improve it.</p> <p>Essentially I would like to loop over an array of elements that have a smooth transition (a different state to normal) when swapping between them.</p> <p>Instead of setting a <code>setTimeout</code> during <code>Array.forEach</code>, then using <code>requestAnimationFrame</code> to loop over the whole thing. I'm now using <code>requestAnimationFrame</code> for the main loop and <code>Array.shift</code>ing to work on the current element.</p> <p>Any ideas for improvement? Is this efficient?</p> <pre><code>function animateArray(fooArray, bar) { // Timing var start = null; var interval = 3000; // how long each element in the array will be displayed for var intro = 1000; // easing/tweening in duration var outro = 1000; // easing/tweening out duration var last = 0 // The last interval, var current; //current element of array var fooLength = fooArray.length; function update(timestamp) { // get the start time and progress if (!start) start = timestamp; var progress = timestamp - start; // do something every `interval` seconds (if it can) if(!last || timestamp - last &gt;= interval) { last = timestamp; // pull off the first element in the array to work on current = fooArray.shift(); } if (typeof current !== null) { // Do something during the intro if (timestamp &lt; last + intro) { console.log(`${current}-intro`); // The main animation } else if (timestamp &gt; last + intro &amp;&amp; timestamp &lt; last + (interval - outro)) { console.log(`${current}`); // do something else during the outro } else { console.log(`${current}-outro`); } } // loop if (progress &lt; interval * fooLength) { requestAnimationFrame((timestamp) =&gt; update(timestamp, fooArray, bar)); } }; requestAnimationFrame((timestamp) =&gt; update(timestamp, fooArray, bar)); } animateArray([1,2,3], 'bar'); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T00:22:28.263", "Id": "201434", "Score": "1", "Tags": [ "javascript", "animation" ], "Title": "Looping over an array with requestAnimationFrame" }
201434
<p>This is my function:</p> <pre><code>def two_powers(num): powers = [] i = 1 while i &lt;= num: if i &amp; num: powers.append(i) i &lt;&lt;= 1 return powers </code></pre> <p>I have python 3.6(Windows 10 64-bit). I want the result in the form of a list. My problem statement is to express a integer(<code>num</code>) in the form of sum of powers of 2.</p> <p>Do I have to create a list in the beginning and then append to it each time ? Can I return a list directly without creating it in the beginning ?</p> <p>This will will speed up my execution time, right ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T08:45:25.830", "Id": "387941", "Score": "0", "body": "What version of Python do you use and what is your actual problem statement? Why do you need a list? In what format do you want the result?" }, { "ContentLicense": "CC BY...
[ { "body": "<p>I think that list generator won't improve your performance in this case because it will require you to create another list (since <code>range</code> is not a good fit for this). You could create a generator that <code>yield</code>s powers but it basically will be moving one piece of code to anothe...
{ "AcceptedAnswerId": "201479", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T08:15:27.187", "Id": "201447", "Score": "3", "Tags": [ "python", "performance" ], "Title": "Express a number as a sum of powers of 2" }
201447
<p>So I've been trying to check through a string, looping for, <code>[</code> (start) and <code>]</code> (end).</p> <p>In this, I also have to check for nested brackets.</p> <p>My expected output, given input <code>[depth1[depth2]]</code> is as follows:</p> <ol> <li><code>depth2</code></li> <li><code>depth1[depth2]</code></li> </ol> <p>To achieve this, I wrote this little snippet of code, which uses a <code>Dictionary&lt;int, int&gt;</code> to store the initial bracket's position at a given depth. If it finds another opening bracket, the depth will increase (and the position will be recorded). It will look for the next ending bracket (with respect to any other opening brackets), and get the initial position of the bracket for that depth. (Thus we get both the beginning and ending of that nested string)</p> <pre><code> var depthItems = new Dictionary&lt;int, int&gt;(); int depth = 0; string input = "[depth1[depth2]]"; for (int i = 0; i &lt; input.Length; i++) { if (input[i] == '[') { depth++; depthItems.Add(depth, i); } else if (input[i] == ']') { int item = depthItems[depth]; depthItems.Remove(depth); depth--; Console.Write($"Found item at ({item}, {i}) -&gt; "); Console.WriteLine(input.Substring(item + 1, i - item - 1)); } } </code></pre> <p>I'm not sure how viable this would be when looking up against large strings with lots of nested brackets - I think it's a start, at least.</p> <p>I will note that I was first surprised that higher "depths" were returned first, but then realised that in order for the lower ones to complete, the higher ones should have been returned first. Not a bad thing, but curious to note.</p> <p>So how <em>could</em> this be improved, especially in terms of memory (i.e. large strings)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T14:44:51.227", "Id": "387975", "Score": "0", "body": "\"I think it's a start, at least.\" Looks like it should work, right? Have you tested this for multiple inputs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate"...
[ { "body": "<blockquote>\n <p>I'm not sure how viable this would be when looking up against large strings with lots of nested brackets [...]</p>\n</blockquote>\n\n<p><em>\"how viable\"</em> is a very vague question.\nTwo common performance metrics are CPU load and memory load,\nperhaps that's what you were tryi...
{ "AcceptedAnswerId": "201464", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T14:40:00.587", "Id": "201462", "Score": "6", "Tags": [ "c#", "strings", "balanced-delimiters" ], "Title": "Looping through a string finding nested brackets" }
201462
<p>I have 4 functions that process texts or <code>tweepy.models.Status</code> object (this object stores text information, author information, retweets &amp; likes information of a specific tweet).</p> <p>The first function is <code>filter_unique</code>, which is used to exclude duplicate tweets from a list of tweets. The result is a <code>generator</code>.</p> <p>The function <code>clean_text</code>, is used to remove punctuations, undefined characters, and whitespaces from a string.</p> <p>The function <code>split_texts</code> has two inputs, the list of tweets/strings and the mode of the splits (<code>naive=True</code> means it only use <code>text.split()</code>, if set to <code>False</code> then it will clean the text first before splitting)</p> <p>The function <code>total_rts</code> calculates the total number of retweets. <code>string_inclusion='word'</code> means that it will calculate the total retweets of tweets that contain <code>'word'</code>.</p> <p>Question: How to make this module more efficient, and perhaps advanced?</p> <p>We can use the sample tweets <a href="https://github.com/anbarief/statistweepy/blob/master/samples/testfile.npy" rel="nofollow noreferrer"><code>testfile.npy</code></a> which contains objects <code>tweepy.models.Status</code>.</p> <hr> <pre><code>import tweepy import string def filter_unique(tweets): uniques = set() for tweet in tweets: if not isinstance(tweet, tweepy.Status): raise TypeError('Each element must be of tweepy.Status object') try: tweet = tweet.retweeted_status except: pass if tweet.id not in uniques: uniques.add(tweet.id) yield tweet def clean_text(text): punct = string.punctuation printable = string.printable whitespace = string.whitespace table = text.maketrans({key: None for key in printable}) undef = set(text.translate(table)) table = text.maketrans({key: None for key in undef}) removed_undef = text.translate(table) table = text.maketrans({key: None for key in punct}) cleaned = removed_undef.translate(table) table = text.maketrans({key: ' ' for key in whitespace}) cleaned = cleaned.translate(table) return cleaned def split_texts(texts, naive): if naive: for text in texts: yield text.split() else: for text in texts: yield clean_text(text).split() def total_rts(tweets, string_inclusion = False, naive = True): result = 0 if not string_inclusion : result = sum([tweet.retweet_count for tweet in tweets]); else: if naive: try: result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in tweet.full_text.split()]) except: result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in tweet.text.split()]) else: try: result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in clean_text(tweet.full_text).split()]) except: result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in clean_text(tweet.text).split()]) return result </code></pre>
[]
[ { "body": "<p>A few obligatory <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8 rules</a>:</p>\n\n<ul>\n<li><p>Imports should be grouped in the following order:</p>\n\n<ol>\n<li>standard library imports</li>\n<li>related third party imports</li>\n<li>local application/libr...
{ "AcceptedAnswerId": "201510", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T16:40:27.140", "Id": "201466", "Score": "3", "Tags": [ "python", "strings", "functional-programming", "twitter" ], "Title": "Utility functions for processing tweets or texts" }
201466
<p>Is there the possibility to improve the code below?</p> <p>I am sure the result I got can be achieved with shorter code.</p> <h3>Code</h3> <pre><code>awk -F, '{a[$2$7]+=$4}{b[$2$7]+=$5}{c[$2$7]+=$6}END{for(i in a)print i,a[i],b[i],c[i]}' tmp3 | sort -t, -k1n | awk 'BEGIN{ print (&quot;\tCODE-1T COD-Area CODE-1 CODE-S CODE-T&quot;) printf (&quot;\t------------------------------------------------------------\n&quot;) } { sum2 += $2; sum3 += $3; sum4 += $4; sum5 = sum2 + sum3 + sum4; printf (&quot;\t%9s%10s%12s%12d%16d\n&quot;,substr($0,1,9),substr($0,10,5),$2,$3,$4) } END { printf (&quot;\t------------------------------------------------------------------------\n&quot;) printf (&quot;\tTotal:\t%23d\t%11d\t%11d\t%4d\n&quot;,sum2,sum3,sum4,sum5) printf (&quot;\t------------------------------------------------------------------------\n&quot;) }' </code></pre> <h3>Input</h3> <pre><code>032118,333000004,3213,11,10,142,SS/RR 032118,333000004,3214,11,0,42,AS/RR 032118,333000004,3215,11,0,761,AS/RR 032118,333000005,3216,7,2,762,SS/RR 032118,333000005,3217,6,2,876,SS/RR 032118,333000005,3218,6,0,876,ST/RR 032118,333000005,3222,5,3,258,ST/RR 032118,333000006,3223,5,3,258,ST/RR 032118,333000006,3224,4,4,870,SS/RR 032118,333000006,3225,3,5,870,SS/RR 032118,333000007,3226,3,34,876,SX/RR 032118,333000007,3227,2,55,876,SS/RR 032218,333000007,3208,2,4,36,SS/RR 032218,333000007,3209,1,3,879,ST/RR 032218,333000007,3210,2,2,803,ST/RR </code></pre> <h3>Output</h3> <pre><code>CODE-1T COD-Area CODE-1 CODE-S CODE-T ------------------------------------------------------------ 333000004 AS/RR 22 0 803 333000004 SS/RR 11 10 142 333000005 SS/RR 13 4 1638 333000005 ST/RR 11 3 1134 333000006 SS/RR 7 9 1740 333000006 ST/RR 5 3 258 333000007 SS/RR 4 59 912 333000007 ST/RR 3 5 1682 333000007 SX/RR 3 34 876 ------------------------------------------------------------------------ Total: 79 127 9185 9391 ------------------------------------------------------------------------ </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T16:54:52.473", "Id": "201467", "Score": "4", "Tags": [ "csv", "awk" ], "Title": "Summary data using CSV file" }
201467
<p>I have been trying to solve <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">this question</a>. </p> <blockquote> <p>Given an unordered array consisting of consecutive integers [1, 2, 3, …, <em>n</em>], find the minimum number of two-element swaps to sort the array.</p> </blockquote> <p>I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.</p> <pre><code>function findIndice(arr,i){ let iterator=0 while(arr[iterator]!==i+1){ iterator++ } return iterator } function swap(arr,x,y){ let temp=arr[x] arr[x]=arr[y] arr[y]=temp } function minimumSwaps(arr){ let i=0; let counter=0; let size=arr.length; for(i=0;i&lt;size-1;i++){ if(arr[i]!==i+1){ let index=findIndice(arr,i) swap(arr,index,i) counter++ } } return counter } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T02:26:50.053", "Id": "388012", "Score": "0", "body": "This is a totally different question... @Gerrit0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T02:48:44.143", "Id": "388013", "Score": "...
[ { "body": "<p>Your algorithm can be summarized by the pseudocode:</p>\n\n<pre><code>for each position in the array\n if a position is occupied by the wrong number\n find the number that fits into the position\n perform a swap\n</code></pre>\n\n<p>A better algorithm would be:</p>\n\n<pre><code>f...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:11:55.113", "Id": "201470", "Score": "6", "Tags": [ "javascript", "algorithm", "sorting", "time-limit-exceeded", "interview-questions" ], "Title": "Minimum swaps algorithm terminated due to timeout" }
201470
<p>Anyone remember "War games?"</p> <p>I have a very long way to go, but I thought it would be interesting to make a version of Tic Tac Toe which plays itself. At present the AI is "choose a random available space" (i.e nonexistent). I will build on that later, but for now I would value some feedback on my basic approach. I've used an object literal pattern, which seems to make sense for the task. I'm curious to learn about any improvements I could make in terms of the structure and implementation. Also, what did I do well please? Is there anything obviously amateurish about my approach?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const TicTacToe = { setup: function() { this.player1 = { name: "Crosses", symbol: "X" }; this.player2 = { name: "Naughts", symbol: "0" }; this.restart(); }, restart: function() { this.board = [ [ "", "", "" ], [ "", "", "" ], [ "", "", "" ] ]; this.currentPlayer = Math.floor( Math.random() * 2 ) == 0 ? this.player1 : this.player2; this.playRound(); }, playRound: function() { console.log( this.currentPlayer.name + " start." ); while ( !this.isWinningCombination( this.player1.symbol, this.board ) &amp;&amp; !this.isWinningCombination( this.player2.symbol, this.board ) &amp;&amp; !this.isDraw( this.board ) ) { this.sleep( 500 ); this.playerTurn( this.currentPlayer ); } }, playerTurn: function( player ) { while ( true ) { let pos = [ Math.floor( Math.random() * 3 ), Math.floor( Math.random() * 3 ) ]; if ( this.board[ pos[ 0 ] ][ pos[ 1 ] ] == "" ) { this.board[ pos[ 0 ] ][ pos[ 1 ] ] = player.symbol; this.displayBoard( this.board ); if ( this.isWinningCombination( player.symbol, this.board ) ) { console.log( this.currentPlayer.name + " win!" ) this.playAgainDialogue(); } else if ( this.isDraw( this.board ) ) { console.log( "It's a draw" ); this.playAgainDialogue(); } this.currentPlayer = this.currentPlayer == this.player1 ? this.player2 : this.player1; break; } continue; } }, displayBoard: function( board ) { display = ""; // First row display += board[ 0 ][ 0 ] == "" ? " " : ` ${board[0][0]}`; display += "|"; display += board[ 0 ][ 1 ] == "" ? " " : `${board[0][1]}`; display += "|"; display += board[ 0 ][ 2 ] == "" ? " \n" : `${board[0][2]}\n`; // Filler display += "--|-|--\n"; // Second row display += board[ 1 ][ 0 ] == "" ? " " : ` ${board[1][0]}`; display += "|"; display += board[ 1 ][ 1 ] == "" ? " " : `${board[1][1]}`; display += "|"; display += board[ 1 ][ 2 ] == "" ? " \n" : `${board[1][2]}\n`; // Filler display += "--|-|--\n"; // Third row display += board[ 2 ][ 0 ] == "" ? " " : ` ${board[2][0]}`; display += "|"; display += board[ 2 ][ 1 ] == "" ? " " : `${board[2][1]}`; display += "|"; display += board[ 2 ][ 2 ] == "" ? " \n" : `${board[2][2]}\n`; console.log( display ); console.log( "" ); }, // Check for win isWinningCombination: function( symbol, board ) { return [ // Rows board[ 0 ][ 0 ] === symbol &amp;&amp; board[ 0 ][ 1 ] === symbol &amp;&amp; board[ 0 ][ 2 ] === symbol, board[ 1 ][ 0 ] === symbol &amp;&amp; board[ 1 ][ 1 ] === symbol &amp;&amp; board[ 1 ][ 2 ] === symbol, board[ 2 ][ 0 ] === symbol &amp;&amp; board[ 2 ][ 1 ] === symbol &amp;&amp; board[ 2 ][ 2 ] === symbol, // Columns board[ 0 ][ 0 ] === symbol &amp;&amp; board[ 1 ][ 0 ] === symbol &amp;&amp; board[ 2 ][ 0 ] === symbol, board[ 0 ][ 1 ] === symbol &amp;&amp; board[ 1 ][ 1 ] === symbol &amp;&amp; board[ 2 ][ 1 ] === symbol, board[ 0 ][ 2 ] === symbol &amp;&amp; board[ 1 ][ 2 ] === symbol &amp;&amp; board[ 2 ][ 2 ] === symbol, // Diagonals board[ 0 ][ 0 ] === symbol &amp;&amp; board[ 1 ][ 1 ] === symbol &amp;&amp; board[ 2 ][ 2 ] === symbol, board[ 0 ][ 2 ] === symbol &amp;&amp; board[ 1 ][ 1 ] === symbol &amp;&amp; board[ 2 ][ 0 ] === symbol ]. includes( true ); }, isDraw: function( board ) { return !this.isWinningCombination( this.player1.symbol, board ) &amp;&amp; !this.isWinningCombination( this.player2.symbol, board ) &amp;&amp; !this.board.some( row =&gt; row.includes( "" ) ); }, // Terrible practice, they say. sleep: function( delay ) { const start = new Date().getTime(); while ( new Date().getTime() &lt; start + delay ); }, playAgainDialogue : function(){ console.log("Type TicTacToe.restart() to play again"); } }; TicTacToe.setup();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;Please open your console to start&lt;/h1&gt;</code></pre> </div> </div> </p> <p>Please note the snippet behaves differently to running in a browser (no "sleep" functionality).</p>
[]
[ { "body": "<h3>What you did right</h3>\n\n<p>It's good that you designed an object,\nand that you separated some operations to functions.\nI think it would be good to go further:\nmore dedicated objects,\nsmaller functions,\nhelper functions.\nMore on all that below.</p>\n\n<h3>Decompose to smaller functions</h...
{ "AcceptedAnswerId": "201477", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:17:56.387", "Id": "201471", "Score": "4", "Tags": [ "javascript", "object-oriented", "console", "tic-tac-toe" ], "Title": "Tic Tac Toe in Browser Console" }
201471
<p>I'm very new to python (been coding for about two days) and have created a programme that simulates blackjack games so that I can work out optimal strategy over many iterations.</p> <p>The problem is that when I run it, my CPU goes to about 99.8% and it freezes (I run in terminal) - Does anybody have any suggestions on how I can change my code so that it is less CPU intensive? - I'm looking to learn about what I've done wrong, the code is just a bit of fun!</p> <p>As I said I'm new to this and as such the code isn't very elegant, but it works just fine.</p> <pre><code>import random q = 0 #simple counter that will record the score of games over time win_count = 0 draw_count = 0 lose_count = 0 bust_count = 0 #User input for when the game is run, it will allow them to choose the number of games to be played (iterations) and also the score at which the player will hold. iterations = input('Number of iterations: ') hold_score = input('Hold score for the player: ') #defining the card values, suits and decks. for x in range(0, iterations): s2 = 2 s3 = 3 s4 = 4 s5 = 5 s6 = 6 s7 = 7 s8 = 8 s9 = 9 s10 = 10 sj = 10 sq = 10 sk = 10 sa = 11 c2 = 2 c3 = 3 c4 = 4 c5 = 5 c6 = 6 c7 = 7 c8 = 8 c9 = 9 c10 = 10 cj = 10 cq = 10 ck = 10 ca = 11 d2 = 2 d3 = 3 d4 = 4 d5 = 5 d6 = 6 d7 = 7 d8 = 8 d9 = 9 d10 = 10 dj = 10 dq = 10 dk = 10 da = 11 h2 = 2 h3 = 3 h4 = 4 h5 = 5 h6 = 6 h7 = 7 h8 = 8 h9 = 9 h10 = 10 hj = 10 hq = 10 hk = 10 ha = 11 spades = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa] clubs = [c2, c3, c4, c5, c6, c7, c7, c8, c9, c10, cj, cq, ck, ca] diamonds = [d2, d3, d4, d5, d6, d7, d8, d9, d10, dj, dq, dk, da] hearts = [h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] deck = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa, c2, c3, c4, c5, c6, c7, c8, c9, c10, cj, cq, ck, ca, d2, d3, d4, d5, d6, d7, d7, d8, d9, d10, dj, dq, dk, da, h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] deck_standard = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa, c2, c3, c4, c5, c6, c7, c8, c9, c10, cj, cq, ck, ca, d2, d3, d4, d5, d6, d7, d7, d8, d9, d10, dj, dq, dk, da, h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] #List for the cards the dealer and player holds dealer = [] user_1 = [] #Randomly gives the player and dealer two cards each - and then remove these cards from the deck of cards so it cannot be used again. card_1 = random.choice(deck) deck.remove(card_1) user_1.append(card_1) card_2 = random.choice(deck) deck.remove(card_2) dealer.append(card_2) card_3 = random.choice(deck) deck.remove(card_3) user_1.append(card_3) card_4 = random.choice(deck) deck.remove(card_4) dealer.append(card_4) #Calculates the number of cards the player/dealer has - also defines their scores to be zero. dealer_card_count = len(dealer) user_1_card_count = len(user_1) dealer_score = 0 user_1_score = 0 #Looks at the two cards each player has and calculates their score - then adds this score to their score. for x in range(0, dealer_card_count): dealer_score = dealer_score + int(dealer[x]) for x in range(0, user_1_card_count): user_1_score = user_1_score + int(user_1[x]) #code to say that if the user has less cards than the pre-defined hold score - give them another card and add that card to their score. while (int(user_1_score) &lt;= int(hold_score)): if (int(user_1_card_count)&lt;6): card_5 = random.choice(deck) deck.remove(card_5) user_1.append(card_5) user_1_score = 0 user_1_card_count = len(user_1) for x in range(0, user_1_card_count): user_1_score = user_1_score + int(user_1[x]) # sets the hold score for the dealer as that of the user (so that the dealer knows how high he has to aim for) hold_score_dealer = user_1_score # Same as above - but for the dealer. if (int(user_1_score) &lt; int(21)): while (int(dealer_score) &lt;= int(hold_score_dealer)): if (int(dealer_card_count)&lt;6): card_6 = random.choice(deck) deck.remove(card_6) dealer.append(card_6) dealer_score = 0 dealer_card_count = len(dealer) for x in range(0, dealer_card_count): dealer_score = dealer_score + int(dealer[x]) #code so that if the user or the dealer have 5 cards they win automatically (5 card rule) if (int(user_1_card_count) ==5): if (int(dealer_card_count) !=5): if (int(user_1_score)) &lt;22: win_count = win_count + 1 if (int(user_1_card_count) == 5): if (int(dealer_card_count) == 5): if (int(user_1_score) &lt; 22): if (int(dealer_score) &lt;22): draw_count = draw_count + 1 elif (int(user_1_score) &gt; 22): bust_count = bust_count + 1 if (int(dealer_card_count) == 5): if(int(user_1_card_count) != 5): if (int(dealer_score) &lt;22): lose_count = lose_count + 1 #Code to deal with all possible outcomes (assuming they don't have 5 cards) - and add to the counter. if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) &gt; int(dealer_score)): if (int(user_1_score) &lt; int(22)): win_count = win_count + 1 elif (int(user_1_score) &gt; int(21)): if (int(dealer_score) &lt; int(22)): lose_count = lose_count + 1 elif (int(user_1_score) &gt; int(21)): if (int(dealer_score) &gt; int (21)): draw_count = draw_count + 1 bust_count = bust_count + 1 elif (int(user_1_score) &lt; int(dealer_score)): if(int(user_1_score) &gt; 21): draw_count = draw_count + 1 bust_count = bust_count + 1 if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) == int(dealer_score)): if (int(user_1_score)) &lt; int(22): draw_count = draw_count + 1 elif (int(user_1_score) &gt; 21): draw_count = draw_count + 1 bust_count = bust_count + 1 if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) &lt; int(dealer_score)): if (int(dealer_score) &lt; int(22)): lose_count = lose_count + 1 elif (int(dealer_score) &gt; int(21)): if (int(user_1_score) &lt; int(22)): win_count = win_count + 1 #Code to print the progress of the iterations over time if (q == iterations * 0.2): print "20%" if (q == iterations * 0.4): print "40%" if (q == iterations * 0.6): print "60%" if (q == iterations * 0.8): print "80%" if (q == iterations * 1): print "100%" gc.collect() print q q = q + 1 # Code to print the final scores after all iterations are complete. print "Total iterations: " + str(iterations) print "*****" print "Win count : " + str(win_count) +" ("+ str((float(win_count))/float(iterations)*100) +"%)" print "Draw count : " + str(draw_count) +" ("+ str((float(draw_count))/float(iterations)*100) +"%)" print "Lose count : " + str(lose_count) +" ("+ str((float(lose_count))/float(iterations)*100) +"%)" print "Bust count : " + str(bust_count) +" ("+ str((float(bust_count))/float(iterations)*100) +"%)" print "" </code></pre>
[]
[ { "body": "<p>Take a look at these lines:</p>\n\n<pre><code>while (int(user_1_score) &lt;= int(hold_score)):\n if (int(user_1_card_count)&lt;6):\n</code></pre>\n\n<p>what happens if the player draws six cards and their score is still less than or equal to the hold score? For example, suppose the hold score i...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:01:28.373", "Id": "201472", "Score": "0", "Tags": [ "python", "python-3.x", "time-limit-exceeded", "playing-cards", "simulation" ], "Title": "Blackjack strategy simulation" }
201472
<blockquote> <p>You will be given an integer k and a list of integers. Count the number of distinct valid pair of integers (a,b) in the list for which a+k=b.</p> <p>For example, the array [1,1,1,2] has two different valid pairs:(1,1) and (1,2). Note that the three possible instances od pair (1,1) count as a single valid pair, as do the three possible instances of the pair (1,2). if k=1, then this means we have total of one 1 valid pair which satisfies a+k=b=>1+1=2, the pair (1,2).</p> </blockquote> <p>My code:</p> <pre><code>public class PairArrayStream { public static void main(String[] args) { int k =1; List&lt;Integer&gt; input = Arrays.asList(1,1,1,2); HashSet&lt;HashSet&gt; hs = new HashSet&lt;HashSet&gt;(); IntStream.range(0, input.size()) .forEach(i -&gt; IntStream.range(0, input.size()) .filter(j -&gt; i != j &amp;&amp; input.get(i) - input.get(j) == k) .forEach(j -&gt; { HashSet inner = new HashSet&lt;&gt;(); inner.add(input.get(j)); inner.add(input.get(i)); hs.add(inner); }) ); System.out.println("OutPut "+hs.size()); } } </code></pre> <p>Without java 8 features::</p> <pre><code>int k =1; List&lt;Integer&gt; input = Arrays.asList(1,1,1,2); HashSet&lt;HashSet&gt; hs = new HashSet&lt;HashSet&gt;(); for(int i =0 ; i&lt;numbers.size();i++){ for(int j = i; j&lt;numbers.size();j++){ if(Math.abs(numbers.get(j)-numbers.get(i)) == k){ HashSet inner = new HashSet&lt;&gt;(); inner.add(numbers.get(j)); inner.add(numbers.get(i)); hs.add(inner); } } } </code></pre> <p>Well, I am getting the correct output but 40% of the test cases gives me a timeout. Opinions and tactics are welcomed to make the code better and fast.</p>
[]
[ { "body": "<p>I can't make comment on the java, but I do have a couple of comments on the algorithm.</p>\n\n<p>You pose the problem as <code>a+k=b</code>, but you use <code>i</code>, <code>j</code> in your code. The logical naming paradigm would be to stick with <code>a</code>, <code>b</code>. You also don't us...
{ "AcceptedAnswerId": "201561", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:27:38.610", "Id": "201473", "Score": "3", "Tags": [ "java", "algorithm", "time-limit-exceeded", "k-sum" ], "Title": "Counting pairs that have a given difference in Java" }
201473
<p>I'm developing an audio recorder app for android using AudioRecord class to have a low level access to audio samples.</p> <pre><code>mRecordingThread = new Thread(new Runnable() { @Override public void run() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); try { FileChannel fileChannel = new FileOutputStream("/foo/bar/temp.wav").getChannel(); ByteBuffer audioBuffer = ByteBuffer.allocateDirect(mBufferSize).order(ByteOrder.nativeOrder()); mAudioRecord.startRecording(); mIsRecording = true; while (mIsRecording) { int readSize = mAudioRecord.read(audioBuffer, audioBuffer.capacity()); if (readSize == AudioRecord.ERROR_INVALID_OPERATION || readSize == AudioRecord.ERROR_BAD_VALUE) { Logger.getInstance().e("Could not read audio data."); break; } try { audioBuffer.limit(readSize); fileChannel.write(audioBuffer); audioBuffer.rewind(); // set buffer's position to 0. mAudioDataReceiver.onAudioDataReceived(audioBuffer, mConfig.getSampleWidth()); audioBuffer.clear(); // set buffer's limit to its capacity, set position to 0. } catch (IOException e) { Logger.getInstance().e(e); } } fileChannel.close(); } catch (IOException e) { Logger.getInstance().e(e); // ... } } }); mRecordingThread.start(); </code></pre> <p>As shown in the above code, i'm writing the samples to a file as well as passing them to another function <code>mAudioDataReceiver.onAudioDataReceived</code> for visualisation (generate waveform, analyse loudness, etc.). I'm using ByteBuffer as container so i can easily convert it to other type (ShortBuffer or FloatBuffer, depending on the given sample width) before processing the samples</p> <pre><code>public void onAudioDataReceived(ByteBuffer buffer, int sampleWidth) { switch (sampleWidth) { case 8: // 8-bit = 1 byte per sample onAudioDataReceived(buffer); break; case 16: // 16-bit = 2 bytes per sample onAudioDataReceived(buffer.asShortBuffer()); break; case 32: // 32-bit = 4 bytes per sample onAudioDataReceived(buffer.asFloatBuffer()); break; } } </code></pre> <p>Question: This line is kinda worrying to me:</p> <pre><code>ByteBuffer audioBuffer = ByteBuffer.allocateDirect(mBufferSize).order(ByteOrder.nativeOrder()); </code></pre> <p>Is it right to set the byte ordering to native order? Will this work with every device?</p> <p>Also, is there anything wrong in my code that would potentially mess up the quality of the audio?</p> <p>Sorry if my questions sound silly, i'm relatively new to android/java development/audio processing, so please bear with me. Thanks</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:56:57.823", "Id": "201475", "Score": "6", "Tags": [ "java", "android", "audio" ], "Title": "Android audio recording using AudioRecord and ByteBuffer" }
201475
<p>I was trying to solve this problem from Leetcode:</p> <blockquote> <p>Given a string, find the length of the longest substring without repeating characters.</p> <p>Examples:</p> <p>Given "abcabcbb", the answer is "abc", which the length is 3.</p> <p>Given "bbbbb", the answer is "b", with the length of 1.</p> <p>Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.</p> </blockquote> <p>I would like to get some code review for the following solution:</p> <pre><code>class Solution: def lengthOfLongestSubstring(self, s): dict = {} start, end, curr_length, max_length = 0, 0, 0, 0 while ( end &lt; len(s)): char = s[end] if char not in dict: curr_length += 1 else: start = max(dict[char], start) max_length = max(max_length, end - start + 1) dict[char] = end + 1 end += 1 return max_length """ my logic is that * 1) Initialize a hashmap/dictionary/object that will map characters to their index. * 2) Initialize `start`, `end`, and `answer` * 3) Loop through the string while `end` is less than `length` of string * 4) Check if character at `end` is in hashmap * a) If so, repeating character exists between `start` and `end`. Set `start` to be the `max_length` between the value of character in the hashmap, and `start` """ </code></pre> <p>And it passes all of the leetcode tests.</p>
[]
[ { "body": "<p>Nice solution, please find a few thoughts below:</p>\n\n<ol>\n<li><p>Do you need to wrap it in class for leetcode? It's unnecessary otherwise.</p></li>\n<li><p>Function names use <code>snake_case</code> and not <code>camelCase</code>, check <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T22:12:17.700", "Id": "201483", "Score": "3", "Tags": [ "python" ], "Title": "\"Longest Substring Without Repeating Characters\" in Python" }
201483
<p>Since I am self taught, I would greatly appreciate some input on my code for this JS calculator:</p> <ol> <li>What redundancies i'm failing to see and remove?</li> <li>How is my naming for var's and functions? Is it clear or vague?</li> <li>How is my overall readability? Is what i'm writing even clear, or is it hard to decipher? </li> <li>Are my comments helpful or redundant?</li> <li>What stands out to you that needs to be fixed the most? </li> </ol> <p>Just fyi, this code wont run on its own as i have not included the HTML/CSS that accompanies this. I would like to not worry about the front end design in this particular post. All input in appreciated.</p> <pre><code>const buttons = ['CE', 'AC', 'x', '7', '8', '9', '/', '4', '5', '6', '-', '1', '2', '3', '+', '0', '.', '=' ]; var currentEntry = [], totalEntry = []; var equals = true; //const testNum = /[0-9]/g; const regexOperands = /[+\-\/x=]/; const totalArea = document.getElementById("totalArea"); const currentArea = document.getElementById("currentArea"); const numberArea = document.getElementById("numberArea"); const faceHappy = document.getElementById("face-happy"); window.onload = () =&gt; { makeButtons(); } function applyClick(userInput) { //all our clicking behaviors for buttons let btn = document.getElementById("b" + userInput); btn.onclick = () =&gt; { let totalAreaLength = totalArea.textContent.length; //first we clear the face changeDisplay(userInput); if (equals) { //clear after =, or for first entry if (!isNaN(userInput)) { //if there is pre-existing numbers after hitting equals then delete currentArea.textContent = ''; } else { //places total from previous calculation as first entry currentArea.textContent = totalEntry; } totalArea.textContent = ''; currentEntry = []; totalEntry = []; equals = false; } //first we restrict input length to 17 if (currentArea.textContent.length &gt; 17 || totalArea.textContent.length &gt; 17) { alert("Number Limit Reached!"); currentArea.textContent = ""; totalArea.textContent = ""; equals = true; } else if (!isNaN(userInput)) { //test for number equals = false; currentArea.textContent = (currentArea.textContent == "0") ? userInput : currentArea.textContent + userInput; } else if (isNaN(userInput)) { //**for all non numerics**\\ if (equals) { //restricts equals being pressed twice return; } else { if (userInput === "=") { //to get answer currentEntry = filterUserInput(userInput); let saveUserInput = currentArea.textContent; operateOnEntry(currentEntry); equals = true; totalEntry = currentEntry[0]; //will save answer for next calculation currentArea.textContent = saveUserInput; //will display equation totalArea.textContent = currentEntry; //will display answer } else if (userInput === ".") { let lastEntry = filterUserInput(userInput); if (!lastEntry.includes(".")) { //test for pre-existing period currentArea.textContent = currentArea.textContent + userInput; } } else if (userInput === "AC" || userInput === "CE") { if (userInput === "AC") { changeDisplay(userInput); currentArea.textContent = ""; totalArea.textContent = ""; } else if (userInput === "CE") { let clearedLastEntry = filterUserInput(userInput); currentArea.textContent = clearedLastEntry.join(''); } } else { //this is default operator behavior let lastEntry = filterUserInput(userInput); //limits operators from printing if there is a pre-existing operator as last user input currentArea.textContent = (regexOperands.test(lastEntry)) ? currentArea.textContent : currentArea.textContent + userInput; } } } } } function operateOnEntry(userEntry) { //this is where the calculations occur when hitting = let a, b, c, index; if (userEntry.includes("x")) { index = userEntry.indexOf('x'); a = Number(userEntry[index - 1]); b = Number(userEntry[index + 1]); c = a * b; userEntry.splice((index - 1), 3, c); return operateOnEntry(userEntry); } else if (userEntry.includes("/")) { index = userEntry.indexOf('/'); a = Number(userEntry[index - 1]); b = Number(userEntry[index + 1]); c = a / b; userEntry.splice((index - 1), 3, c); return operateOnEntry(userEntry); } else if (currentEntry.includes("+") || currentEntry.includes("-")) { index = userEntry[1]; a = Number(userEntry[0]); b = Number(userEntry[2]); console.log("index: " + index); if (index == '+') { c = a + b; userEntry.splice(0, 3, c); return operateOnEntry(userEntry); } else { c = a - b; userEntry.splice(0, 3, c); return operateOnEntry(userEntry); } } return userEntry; } function filterUserInput(userInput) { //this function converts the user input into an array let testCurrentEntry; if (userInput === ".") { testCurrentEntry = currentArea.textContent.split(regexOperands); return testCurrentEntry.pop(); } else if (userInput === "=") { testCurrentEntry = currentArea.textContent; //.split(regexOperands) testCurrentEntry = testCurrentEntry.split(/([+\-\/x=])/g); return testCurrentEntry; } else if (userInput === "CE") { testCurrentEntry = currentArea.textContent.split(""); testCurrentEntry.pop() return testCurrentEntry; } else { testCurrentEntry = currentArea.textContent.split(''); return testCurrentEntry.pop(); } } function changeDisplay(userInput) { numberArea.style.display = 'block'; if (userInput == 'AC') { numberArea.style.display = 'none'; faceHappy.style.display = "block"; } } function makeButtons() { for (var i = 0; i &lt; buttons.length; i++) { var btn = document.createElement("BUTTON"); var t = document.createTextNode(buttons[i]); var container = document.getElementById('container'); btn.id = "b" + buttons[i]; btn.className = "button"; btn.appendChild(t); container.appendChild(btn); applyClick(buttons[i]); } } </code></pre>
[]
[ { "body": "<p>First thing that feels off is that you're mixing using var together with let and const (check here: <a href=\"https://softwareengineering.stackexchange.com/questions/274342/is-there-any-reason-to-use-the-var-keyword-in-es6\">var in es-6</a>)</p>\n\n<p>As for names of variables, don't be afraid to ...
{ "AcceptedAnswerId": "201503", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T04:19:57.043", "Id": "201490", "Score": "4", "Tags": [ "javascript", "beginner", "calculator" ], "Title": "Vanilla JS calculator for learning coding fundamentals" }
201490
<p>I implemented an iterator pattern for C# using <code>IEnumerator</code> and <code>IEnumerable</code>. The goal of the implementation is to traverse a binary tree.</p> <pre><code>using System.Collections; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DesignPatternsQuestions { [TestClass] public class TreeNodeTest { [TestMethod] public void IteratorTreeNodeTest() { TreeNode&lt;int&gt; treeNodeList = new TreeNode&lt;int&gt;(); TreeNode&lt;int&gt; left = new TreeNode&lt;int&gt; { Value = 2 }; TreeNode&lt;int&gt; leftLeft = new TreeNode&lt;int&gt; { Value = 4 }; TreeNode&lt;int&gt; leftRight = new TreeNode&lt;int&gt; { Value = 5 }; left.Left = leftLeft; left.Right = leftRight; TreeNode&lt;int&gt; right = new TreeNode&lt;int&gt; { Value = 3 }; TreeNode&lt;int&gt; rightLeft = new TreeNode&lt;int&gt; { Value = 6 }; TreeNode&lt;int&gt; rightRight = new TreeNode&lt;int&gt; { Value = 7 }; right.Right = rightRight; right.Left = rightLeft; treeNodeList.Value = 1; treeNodeList.Right = right; treeNodeList.Left = left; List&lt;int&gt; result = new List&lt;int&gt;(); foreach (var currentNode in treeNodeList) { result.Add(currentNode); } for (int i = 0; i &lt; result.Count; i++) { Assert.AreEqual(i+1, result[i]); } } } public class TreeNode&lt;T&gt; : IEnumerable&lt;T&gt; { public TreeNode&lt;T&gt; Left { get; set; } public TreeNode&lt;T&gt; Right { get; set; } public T Value { get; set; } public IEnumerator&lt;T&gt; GetEnumerator() { return new TreeNodeIterator&lt;T&gt;(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class TreeNodeIterator&lt;T&gt; : IEnumerator&lt;T&gt; { private TreeNode&lt;T&gt; _tree; private TreeNode&lt;T&gt; _current; private Queue&lt;TreeNode&lt;T&gt;&gt; Q = new Queue&lt;TreeNode&lt;T&gt;&gt;(); public TreeNodeIterator(TreeNode&lt;T&gt; treeNode) { _tree = treeNode; if (_tree != null) { Q.Enqueue(_tree); } } public bool MoveNext() { if (_tree == null) { Reset(); return true; } else { while (Q.Count &gt; 0) { _current = Q.Dequeue(); if (_current.Left != null) { Q.Enqueue(_current.Left); } if (_current.Right != null) { Q.Enqueue(_current.Right); } return true; } } return false; } public void Reset() { _current = null; } public void Dispose() { } object IEnumerator.Current { get { return Current; } } public T Current { get { return _current.Value; } } } } </code></pre> <hr> <p>Just for comparison, here is code from a PluralSight design pattern course that I used as a model for my solution, but with children() function and different type of Queue nodes. Don't review the pluralsight code.</p> <p>They are very close however I wanted to know what would you prefer, thinking about code simplicity and also pretending that this is a 30-minute interview question?</p> <p>What I like about the Plural sight code is that it calls children function which is good also not only for binary tree. What I do not like about his code is the fact that you store a Queue of <code>IEnumerator&lt;DemoTree&lt;T&gt;&gt;</code>. I think that in a real coding interview you can do a lot of mistakes with this approach.</p> <p>Please also comment on style or anything else you find critical for job interviews.</p> <blockquote> <pre><code>using System; using System.Collections; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DesignPatternsQuestions { //implement the iterator interface and use it for traversing a binary tree //this is how the plural sight guy did it [TestClass] public class IteratorPatternTest { [TestMethod] public void PrintBinaryTreeTest() { DemoTree&lt;int&gt; treeNodeList = new DemoTree&lt;int&gt;(); DemoTree&lt;int&gt; left = new DemoTree&lt;int&gt; { Value = 2 }; DemoTree&lt;int&gt; leftLeft = new DemoTree&lt;int&gt; { Value = 4 }; DemoTree&lt;int&gt; leftRight = new DemoTree&lt;int&gt; { Value = 5 }; left.Left = leftLeft; left.Right = leftRight; DemoTree&lt;int&gt; right = new DemoTree&lt;int&gt; { Value = 3 }; DemoTree&lt;int&gt; rightLeft = new DemoTree&lt;int&gt; { Value = 6 }; DemoTree&lt;int&gt; rightRight = new DemoTree&lt;int&gt; { Value = 7 }; right.Right = rightRight; right.Left = rightLeft; treeNodeList.Value = 1; treeNodeList.Right = right; treeNodeList.Left = left; List&lt;int&gt; result = new List&lt;int&gt;(); foreach (var currentNode in treeNodeList) { result.Add(currentNode); } for (int i = 0; i &lt; result.Count; i++) { Assert.AreEqual(i+1, result[i]); } } } public class DemoTreeIterator&lt;T&gt; : IEnumerator&lt;T&gt; { private readonly DemoTree&lt;T&gt; _tree; private DemoTree&lt;T&gt; _current; public Queue&lt;IEnumerator&lt;DemoTree&lt;T&gt;&gt;&gt; Q = new Queue&lt;IEnumerator&lt;DemoTree&lt;T&gt;&gt;&gt;(); //must have a ctor to passing tree to the Iterator public DemoTreeIterator(DemoTree&lt;T&gt; tree) { _tree = tree; } public bool MoveNext() { if (_current == null) { Reset(); _current = _tree; Q.Enqueue(_current.Childern().GetEnumerator()); return true; } while (Q.Count &gt; 0) { var enumerator = Q.Peek(); if (enumerator.MoveNext()) { _current = enumerator.Current; Q.Enqueue(_current.Childern().GetEnumerator()); return true; } else { Q.Dequeue(); } } return false; } public void Reset() { _current = null; } public void Dispose() { } public T Current { get { return _current.Value; } } object IEnumerator.Current { get { return Current; } } } public class DemoTree&lt;T&gt; : IEnumerable&lt;T&gt; { public T Value { get; set; } public DemoTree&lt;T&gt; Left { get; set; } public DemoTree&lt;T&gt; Right { get; set; } public IEnumerator&lt;T&gt; GetEnumerator() { return new DemoTreeIterator&lt;T&gt;(this); } //backward compatible without Generic IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } //a way to return all the children public IEnumerable&lt;DemoTree&lt;T&gt;&gt; Childern() { if (Left != null) { yield return Left; } if (Right != null) { yield return Right; } yield break; } } } </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T08:13:31.233", "Id": "388028", "Score": "0", "body": "You named the two versions in the wrong order... and we cannot review the code from Pluralsight... you have quote it. I don't think this would be even possible as a comparative-r...
[ { "body": "<p>I'll ignore the 'PluralSight' code.</p>\n\n<p>Note that you have implemented a breadth-first traversal. As far as I'm concerned, a spec which doesn't specify how the tree is traversed is insufficient, but you must document this behaviour (e.g. with inline documentation (<code>///</code>), or other...
{ "AcceptedAnswerId": "201502", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T08:05:47.420", "Id": "201498", "Score": "7", "Tags": [ "c#", "tree", "interview-questions", "iterator", "breadth-first-search" ], "Title": "Iterator for BFS binary tree traversal" }
201498
<p>I wrote this program in Python 3.I would like to know if there is some more functionality that could be added/removed/is missing.Any comments would be helpful!</p> <pre><code>#Steps from user : """ Enter Input P1 and P2 Each time for input will be preceded by a printed board. The game will continue until an input matches a win combination. """ win_combinations = [ [1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]] tot_list = [1,2,3,4,5,6,7,8,9] def board(): print ("{}|{}|{}".format(tot_list[0],tot_list[1],tot_list[2])) print ("{}|{}|{}".format(tot_list[3],tot_list[4],tot_list[5])) print ("{}|{}|{}".format(tot_list[6],tot_list[7],tot_list[8])) p1 = 0 p2 = 0 def player_input(): global p1 global p2 while True: try: print("\n\n") board() print("\n") p1 = int(input("P1(X): Enter your Input:")) print("\n") p2 = int(input("P2(O): Enter your Input:")) if 0 &lt; p1 &lt; 10 and 0 &lt; p2 &lt; 10 : assign_values(p1,p2) break print("Re-enter valid input") except: print("Invalid input") continue def assign_values(player1,player2): if type(tot_list[player1-1]) == str() or type(tot_list[player2-1]) == str(): print("Re-enter valid input") player_input() if player1 in tot_list: tot_list[player1-1] = "X" if player2 in tot_list: tot_list[player2-1] = "O" p1_win = False p2_win = False tie = False def default_values(): global tot_list global p1 global p2 global p1_win global p2_win global tie tot_list = [1,2,3,4,5,6,7,8,9] p1 = 0 p2 = 0 p1_win = False p2_win = False tie = False def play(): global p1_win global p2_win global tie global tot_list while True: player_input() for i in win_combinations: if tot_list[i[0]-1] == "X" and tot_list[i[1]-1] == "X" and tot_list[i[2]-1] == "X": p1_win = True break elif tot_list[i[0]-1] == "O" and tot_list[i[1]-1] == "O" and tot_list[i[2]-1] == "O": p2_win = True break if all(isinstance(i,str) for i in tot_list) == True: tie == False if p1_win==True: print("P1 has won!") break elif p2_win==True: print("P2 has won!") break elif tie == True: print("Its a tie!") break play_again = input("Play Again?(y/n)") if play_again == "y": default_values() play() else: print("Ciao") if __name__ == '__main__': play() </code></pre>
[]
[ { "body": "<p>Your code doesn't work like in real life. For example, when I play:</p>\n\n<pre><code>1|2|3\n4|5|6\n7|8|9\n\nP1(X): Enter your Input:1\n\nP2(O): Enter your Input:1\n\nX|2|3\n4|5|6\n7|8|9\n</code></pre>\n\n<p>There is no error generated. Both players cannot request the same location. Also, playing ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T10:38:54.290", "Id": "201506", "Score": "4", "Tags": [ "python", "python-3.x", "tic-tac-toe" ], "Title": "TicTacToe game in Python 3" }
201506
<p>My project has many different objects from different classes, and I want each object to have a unique ID. IDs should be unique within each class type, but can be the same among different classes. For example Foo object1 and Foo object2 must have different unique IDs, but Foo object1 can have the same ID number as Bar object1. </p> <p>Here is what I thought of doing, and I would appreciate feedback on whether this is a good solution, or whether I should try to implement this through a class instead of a function.</p> <pre><code>template &lt;typename T&gt; void giveID(T&amp; obj) { static int id = 1; obj.id = id++; } struct Foo { Foo() { giveID(*this); }; int id; }; struct Bar { Bar() { giveID(*this); }; int id; }; int main() { Foo foo1; // ID = 1 Foo foo2; // ID = 2 Bar bar1; // ID = 1 Bar bar2; // ID = 2 } </code></pre> <p>Also, let's say an object gets ID number 5, and then the object is deleted, the ID counter that assigns IDs might be up to ID 10. ID number 5 is unused. Is it a good idea to assign IDs that were once used but are no longer? In other words would it be a good idea to search through available unused ID numbers and assign that, or to simply keep the counter incrementing and having certain ID numbers unassigned? </p> <p>Thanks for any feedback.</p> <p>Edit: I've come up with another way using a templated class. Note, static inline class members are a C++17 feature:</p> <pre><code>template &lt;typename T&gt; struct giveID { giveID(T&amp; obj) { obj.id = id++; } static inline int id = 1; }; struct Foo { Foo() { giveID&lt;Foo&gt;(*this); } int id; }; struct Bar { Bar() { giveID&lt;Bar&gt;(*this); } int id; }; int main() { Foo foo1; // ID = 1 Foo foo2; // ID = 2 Bar bar1; // ID = 1 Bar bar2; // ID = 2 return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T14:34:13.953", "Id": "388060", "Score": "0", "body": "@Incomputable The second version seems to compile fine. Sorry, which return type is missing? The second version just creates a temporary and assigns the ID through the temporary'...
[ { "body": "<p>The first question: yes, acceptable (putting aside questions like should an architecture that requires unique ids be restructured—there's no such thing as universal solution after all.) Note that it probably makes sense to return an id rather than assign it by reference, as the latter allows to as...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T13:46:24.653", "Id": "201509", "Score": "-2", "Tags": [ "c++", "template" ], "Title": "Is this a good/bad/ugly way of assigning unique IDs to objects in C++?" }
201509
<p>I have made a replica of the game 2048. It works exactly how the game should work. However I was just looking to know where I could've possibly cleaned up my code or make it more efficient. </p> <pre><code>import random board =([0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]) def pieces_test(board): places = find_non_zeros(board) print(places) def combine_numbers(board, value, new_y, new_x, del_y, del_x): value *= 2 board[new_y][new_x] = value board[del_y][del_x] = 0 return board def find_zeros(board): good_places = [] for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == 0: good_places.append([i,j]) return good_places def find_non_zeros(board): good_places = [] for i in range(len(board)): for j in range(len(board[i])): if board[i][j] != 0: good_places.append([i,j]) return good_places def start_of_game(board): for i in range(2): places = find_zeros(board) new_coord = random.choice(places) board[new_coord[0]][new_coord[1]] = 2 return board def move_left(board): not_left = True unusable_pieces = [] while not_left: not_left = False pieces_positions = find_non_zeros(board) #pieces_positions = [[piece1_y, piece1_x],[piece2_y, piece2_x]...] for i in range(len(pieces_positions)): if pieces_positions[i][1] != 0: if board[pieces_positions[i][0]][pieces_positions[i][1]-1] == 0: if [pieces_positions[i][0],pieces_positions[i][1]] in unusable_pieces: index_value = unusable_pieces.index([pieces_positions[i][0],pieces_positions[i][1]]) unusable_pieces[index_value][1] -= 1 value = board[pieces_positions[i][0]][pieces_positions[i][1]] board[pieces_positions[i][0]][pieces_positions[i][1]-1] = value board[pieces_positions[i][0]][pieces_positions[i][1]] = 0 not_left = True elif board[pieces_positions[i][0]][pieces_positions[i][1]-1] == board[pieces_positions[i][0]][pieces_positions[i][1]]: if [pieces_positions[i][0],pieces_positions[i][1]] not in unusable_pieces: if [pieces_positions[i][0], pieces_positions[i][1]-1] not in unusable_pieces: value = board[pieces_positions[i][0]][pieces_positions[i][1]] combine_numbers(board, value, pieces_positions[i][0], pieces_positions[i][1]-1, pieces_positions[i][0], pieces_positions[i][1]) unusable_pieces.append([pieces_positions[i][0], pieces_positions[i][1]-1]) not_left = True # combine_numbers(board, value_of_board_pieces, new_y, new_x, del_y, del_x) return board def move_right(board): not_right = True unusable_pieces = [] while not_right: not_right = False pieces_positions = find_non_zeros(board) pieces_positions = pieces_positions[::-1] #pieces_positions = [[piece1_y, piece1_x],[piece2_y, piece2_x]...] for i in range(len(pieces_positions)): if pieces_positions[i][1] != 3: if board[pieces_positions[i][0]][pieces_positions[i][1]+1] == 0: if [pieces_positions[i][0],pieces_positions[i][1]] in unusable_pieces: index_value = unusable_pieces.index([pieces_positions[i][0],pieces_positions[i][1]]) unusable_pieces[index_value][1] += 1 value = board[pieces_positions[i][0]][pieces_positions[i][1]] board[pieces_positions[i][0]][pieces_positions[i][1]+1] = value board[pieces_positions[i][0]][pieces_positions[i][1]] = 0 not_right = True elif board[pieces_positions[i][0]][pieces_positions[i][1]+1] == board[pieces_positions[i][0]][pieces_positions[i][1]]: if [pieces_positions[i][0],pieces_positions[i][1]] not in unusable_pieces: if [pieces_positions[i][0], pieces_positions[i][1]+1] not in unusable_pieces: value = board[pieces_positions[i][0]][pieces_positions[i][1]] combine_numbers(board, value, pieces_positions[i][0], pieces_positions[i][1]+1, pieces_positions[i][0], pieces_positions[i][1]) unusable_pieces.append([pieces_positions[i][0], pieces_positions[i][1]+1]) not_right = True return board def move_up(board): not_up = True unusable_pieces = [] while not_up: not_up = False pieces_positions = find_non_zeros(board) #pieces_positions = [[piece1_y, piece1_x],[piece2_y, piece2_x]...] for i in range(len(pieces_positions)): if pieces_positions[i][0] != 0: if board[pieces_positions[i][0]-1][pieces_positions[i][1]] == 0: if [pieces_positions[i][0],pieces_positions[i][1]] in unusable_pieces: index_value = unusable_pieces.index([pieces_positions[i][0],pieces_positions[i][1]]) unusable_pieces[index_value][0] -= 1 value = board[pieces_positions[i][0]][pieces_positions[i][1]] board[pieces_positions[i][0]-1][pieces_positions[i][1]] = value board[pieces_positions[i][0]][pieces_positions[i][1]] = 0 not_up = True elif board[pieces_positions[i][0]-1][pieces_positions[i][1]] == board[pieces_positions[i][0]][pieces_positions[i][1]]: if [pieces_positions[i][0],pieces_positions[i][1]] not in unusable_pieces: if [pieces_positions[i][0]-1, pieces_positions[i][1]] not in unusable_pieces: value = board[pieces_positions[i][0]][pieces_positions[i][1]] combine_numbers(board, value, pieces_positions[i][0]-1, pieces_positions[i][1], pieces_positions[i][0], pieces_positions[i][1]) unusable_pieces.append([pieces_positions[i][0]-1, pieces_positions[i][1]]) not_up = True return board def move_down(board): not_down = True unusable_pieces = [] while not_down: not_down = False pieces_positions = find_non_zeros(board) pieces_positions = pieces_positions[::-1] #pieces_positions = [[piece1_y, piece1_x],[piece2_y, piece2_x]...] for i in range(len(pieces_positions)): if pieces_positions[i][0] != 3: if board[pieces_positions[i][0]+1][pieces_positions[i][1]] == 0: if [pieces_positions[i][0],pieces_positions[i][1]] in unusable_pieces: index_value = unusable_pieces.index([pieces_positions[i][0],pieces_positions[i][1]]) unusable_pieces[index_value][0] += 1 value = board[pieces_positions[i][0]][pieces_positions[i][1]] board[pieces_positions[i][0]+1][pieces_positions[i][1]] = value board[pieces_positions[i][0]][pieces_positions[i][1]] = 0 not_down = True elif board[pieces_positions[i][0]+1][pieces_positions[i][1]] == board[pieces_positions[i][0]][pieces_positions[i][1]]: if [pieces_positions[i][0],pieces_positions[i][1]] not in unusable_pieces: if [pieces_positions[i][0]+1, pieces_positions[i][1]] not in unusable_pieces: value = board[pieces_positions[i][0]][pieces_positions[i][1]] combine_numbers(board, value, pieces_positions[i][0]+1, pieces_positions[i][1], pieces_positions[i][0], pieces_positions[i][1]) unusable_pieces.append([pieces_positions[i][0]+1, pieces_positions[i][1]]) not_down = True return board def add_piece(board): free_spots = find_zeros(board) chosen_spot = random.choice(free_spots) board[chosen_spot[0]][chosen_spot[1]] = 2 return board def main(board): board = start_of_game(board) game_finished= False while game_finished == False: if find_zeros(board) == []: game_finished = True continue print(board[0],"\n",board[1],"\n",board[2],"\n",board[3]) move = input("do you want to move up, down, left or right") if move == "up": move_up(board) if move == "down": move_down(board) if move == "left": move_left(board) if move == "right": move_right(board) board = add_piece(board) main(board) </code></pre>
[]
[ { "body": "<p>The thing that jumps out when reading this is the use of indexers: a snippet like this:</p>\n\n<pre><code> if board[pieces_positions[i][0]][pieces_positions[i][1]-1] == 0:\n if [pieces_positions[i][0],pieces_positions[i][1]] in unusable_pieces:\n index_value = unusable_pieces.index([piec...
{ "AcceptedAnswerId": "201531", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T15:10:14.967", "Id": "201515", "Score": "5", "Tags": [ "python", "python-3.x", "2048" ], "Title": "2048 style game" }
201515
<p>I was asked about this question by my friend, so I decided to implement it recursively. I would like to get some code review.</p> <pre><code># Create a BinarySearchTree class # # The BinarySearchTree class should contain the following # properties: # # root: {Node} (initially root Node) # # The BinarySearchTree class should also contain the following # methods: # # put: A method that takes takes an integer value, and # creates a node with the given input. The method # will then find the correct place to add the new # node. Values larger than the current node node go # to the right, and smaller values go to the left. # # Input: value {Integer} # Output: {None} # # contain: A method that searches if a value exists with a # exists within the tree and returns true if found. # # Input: value {Integer} # Output: {Boolean} # import unittest class Node: def __init__(self, value=None, left=None, right=None): self.value = value self.left = left self.right = right class BinarySearchTree(): def __init__(self): #self.root = None self.root = Node() self.size = 0 def put(self, value): self._put(value, self.root) def _put(self, value, node): if node.value is None: node.value = value else: if value &lt; node.value: if node.left is None: node.left = Node() self._put(value, node.left) else: if node.right is None: node.right = Node() self._put(value, node.right) def contains(self, value): return self._contains(value, self.root) def _contains(self, value, node): if node is None or node.value is None: return False else: if value == node.value: return True elif value &lt; node.value: return self._contains(value, node.left) else: return self._contains(value, node.right) def in_order_traversal(self): acc = list() self._in_order_traversal(self.root, acc) return acc def _in_order_traversal(self, node, acc): if node is None or node.value is None: return self._in_order_traversal(node.left, acc) acc.append(node.value) self._in_order_traversal(node.right, acc) </code></pre> <p>I also added 5 unit tests, and they all pass:</p> <pre><code>import unittest class TestBST(unittest.TestCase): def setUp(self): self.search_tree = BinarySearchTree() def test_bst(self): self.search_tree.put(3) self.search_tree.put(1) self.search_tree.put(2) self.search_tree.put(5) self.assertFalse(self.search_tree.contains(0)) self.assertTrue(self.search_tree.contains(1)) self.assertTrue(self.search_tree.contains(2)) self.assertTrue(self.search_tree.contains(3)) self.assertFalse(self.search_tree.contains(4)) self.assertTrue(self.search_tree.contains(5)) self.assertFalse(self.search_tree.contains(6)) self.assertEqual(self.search_tree.in_order_traversal(), [1, 2, 3, 5]) def test_empty(self): self.assertEqual(self.search_tree.in_order_traversal(), []) def test_negative(self): self.search_tree.put(-1) self.search_tree.put(11) self.search_tree.put(-10) self.search_tree.put(50) self.assertTrue(self.search_tree.contains(-1)) self.assertTrue(self.search_tree.contains(11)) self.assertTrue(self.search_tree.contains(-10)) self.assertTrue(self.search_tree.contains(50)) self.assertEqual(self.search_tree.in_order_traversal(), [-10, -1, 11, 50]) def test_dupes(self): self.search_tree.put(1) self.search_tree.put(2) self.search_tree.put(1) self.search_tree.put(2) self.assertTrue(self.search_tree.contains(1)) self.assertTrue(self.search_tree.contains(2)) self.assertEqual(self.search_tree.in_order_traversal(), [1, 1, 2, 2]) def test_none(self): self.search_tree.put(None) self.assertFalse(self.search_tree.contains(None)) self.assertEqual(self.search_tree.in_order_traversal(), []) </code></pre>
[]
[ { "body": "<p>Here's what I think is the main drawback of your design. You can think of a tree as being either:</p>\n\n<ol>\n<li>An (empty) leaf</li>\n<li>A node containing a value and having left and right branches which are themselves trees</li>\n</ol>\n\n<p>It would be nice if these two possibilities were c...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T15:47:06.800", "Id": "201517", "Score": "1", "Tags": [ "python", "binary-search" ], "Title": "BST implementation for insert (put) and contain (search) in Python" }
201517
<p>I have the following function which takes in an input and validates if that input is an Armstrong number or not:</p> <blockquote> <p>An Armstrong Number is a number such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3 ** 3 + 7 ** 3 + 1 ** 3 = 371.</p> </blockquote> <p><a href="https://codepen.io/Oguntoye/pen/KBJyOB/" rel="nofollow noreferrer" title="Armstrong number validator - codepen">Here's a link to the program on codepen</a>.</p> <pre><code>const isArmstrong = input =&gt; { const expandedInputExpression = ` ${input[0]} ** 3 + ${input[1]} ** 3 + ${input[2]} ** 3`; const expandedInputValue = Array.from(input) .map(digit =&gt; digit) .reduce((total, currentDigit) =&gt; total + currentDigit ** 3, 0); if (expandedInputValue === parseInt(input)) { console.log(`${input} is an Armstrong number since ${expandedInputExpression} = ${input}`); return true; } else { console.log(` ${input} is not an Armstrong number because ${expandedInputExpression}( ${expandedInputValue}) is not equal to ${input}`); return false; } }; </code></pre> <p>Is there any way to refactor and simplify the function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T16:23:25.973", "Id": "388087", "Score": "0", "body": "`outputDiv` and outputText are not defined here so this function has an unstated side effect. Perhaps they should be passed in as an argument. Also, you've duplicated `outputDi...
[ { "body": "<ol>\n<li><p>Being called <code>isArmstrong</code>, it should just return a boolean value, and not have side effects of setting any sort of DOM. That can be done in a separate function by the caller. </p></li>\n<li><p><code>expandedInputValue</code> can probably have a better name. Maybe <code>digitT...
{ "AcceptedAnswerId": "201552", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T15:50:59.480", "Id": "201518", "Score": "0", "Tags": [ "javascript", "ecmascript-6" ], "Title": "JavaScript Armstrong Number Validator (ES6)" }
201518
<p>I have written a small library for C that implements the Huffman coding algorithm as outlined in <a href="http://compression.ru/download/articles/huff/huffman_1952_minimum-redundancy-codes.pdf" rel="nofollow noreferrer">David Huffman's paper on Minimum-Redundancy Codes</a>, and a small test program to implement it. The library consists of two primary functions, <code>huffman_encode()</code> and <code>huffman_decode()</code>, and a series of helper functions. <s>The program also uses a linked list library which I have written and included below although I am not looking for a review of the linked list in this question.</s> Edit: The linked list library has been fully removed from the latest version of the code</p> <p>Here is what I would like critiqued:</p> <ul> <li>Current runtime memory usage is quite high (my test program allocates &gt;60kb), how can I reduce on this? Are there redundancies I can get rid of or can I improve my implementation of the algorithm? I'm fairly sure I can ditch the linked list...</li> <li>What are some ways I can reduce the header size to improve the compression ratios?</li> <li>I feel like my code is over-engineered, how could I simplify things without losing performance?</li> <li>How is my documentation/commenting (Particularly in <code>huffman.c</code>)? I know that the code is quite obfuscated in places but I was wondering if it made the library easy enough to understand</li> <li>Are there any general performance chokes that can be removed?</li> <li>Would there be any major issues porting my code to other systems? I have never used bit level operations before and I've heard that endianness can be a problem when using them</li> <li>Are there any bugs you can find? I have tested it extensively but there's always the chance that I've missed something. Are there any input strings that can break my code?</li> </ul> <p>I compiled this code on the latest version of Debian Linux (4.9.88-1+deb9u1) using:</p> <p><code>clang *.c -o huffman -std=c11 -Wall -Wextra -Wpedantic -O2</code></p> <p><strong>huffman.h</strong></p> <pre><code>#ifndef HUFFMAN_H #define HUFFMAN_H /* Header files */ #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; /* Return values */ #define EXIT_SUCCESS 0 #define MEM_ERROR 1 #define INPUT_ERROR 2 /* Node identifiers, might change to enumeration */ #define INTERNAL_NODE 0 #define CHARACTER_NODE 1 /* Size of the header with no characters stored */ #define HEADER_BASE_SIZE 10 /* Huffman Tree node */ typedef struct huffman_node_t { size_t freq; struct huffman_node_t * child[2]; char c; } huffman_node_t; /* User Functions */ int huffman_decode(uint8_t * input, char ** output); int huffman_encode(char * input, uint8_t ** output); /* Helper Functions */ /* Encoding */ int huff_tree_from_freq(size_t * freq, huffman_node_t ** head_node); int node_compare(const void * first_node, const void * second_node); int node_compare_priority(const void * first_node, const void * second_node); void code_array_from_tree(huffman_node_t * node, uint8_t huffman_array[256][2], uint8_t bits_set); /* Decoding */ char is_char_node(uint8_t byte, uint8_t bits_left, huffman_node_t * node); int huff_tree_from_codes(huffman_node_t ** head_node, uint8_t huffman_array[256][2]); int add_char_to_tree(huffman_node_t * node, char c, uint8_t byte, uint8_t bits_left, uint8_t curr_bit); /* Universal */ huffman_node_t * create_char_node(char c, size_t freq); huffman_node_t * create_internal_node(huffman_node_t * first_child, huffman_node_t * second_child); void destroy_huff_tree(huffman_node_t * node); void node_print(const void * element); #endif </code></pre> <p><strong>huffman.c</strong></p> <pre><code>/* * Filename: huffman.c * Author: Jess Turner * Date: 17/07/18 * Licence: GNU GPL V3 * * Encodes and decodes a byte stream using huffman coding * * Return/exit codes: * EXIT_SUCCESS - No error * MEM_ERROR - Memory allocation error * INPUT_ERROR - No input given * * User Functions: * - huffman_encode() - Encodes a string using Huffman coding * - huffman_decode() - Decodes a Huffman encoded string * * Helper Functions: * * Encoding: * - huff_tree_from_freq() - Generate a Huffman tree from a frequency analysis * - code_array_from_tree() - Generate a &quot;code array&quot; from the huffman tree, used for fast encoding * - node_compare() - Calculate the difference in frequency between two nodes * - node_compare_priority() - Modified version of node_compare() which prioritises character nodes over internal nodes when frequencies are equal * * Decoding: * - huff_tree_from_codes() - Generates a Huffman tree from a stored &quot;code array&quot; * - is_char_node() - Determine if a given byte is a character node in a Huffman tree * - add_char_to_tree() - Adds a character and its encoding byte to a Huffman tree * * Universal: * - create_char_node() - Generate a character node * - create_internal_node() - Generate an internal node * - destroy_huff_tree() - Traverses the tree and frees all memory associated with it * - node_print() - Debugging function used to print information about a node, can be passed to dlist_operate() to print all nodes in the priority queue * * Data structures: * * Code array: * - Fast way to encode data using the information generated from a Huffman tree and an easy way to store a representation of the tree * - 2D array that represents each byte to be encoded and how it is encoded allowing for O(1) time to determine how a given byte is encoded * - Position in the array (i.e. code_array[0-255]) represents the byte to be encoded * - The first element at each position (i.e. code_array[byte][0]) represents the way the byte is encoded * - The seconde element at each position (i.e. code_array[byte][1]) represents the number of bits that encode the byte * * Huffman tree: * - Binary tree that operates much like any other Huffman tree * - Contains two types of nodes, internal nodes and character nodes * - Every node contains either the frequency of the character it represents or the combined frequencies of its child nodes * * Encoded data format: * * - Header * - Compressed string length (uint32_t stored as 4 uint8_t's) * - Decompressed string length (uint32_t stored as 4 uint8_t's) * - Header size (uint16_t stored as 2 uint8_t's) * - Huffman tree stored as a &quot;code array&quot; (3 bytes per character: encoded character, encoding byte, number of bits set) * - Encoded data * * The future: * - (Possibly) Modify decoding algorithm to use a hash table lookup rather than tree recursion, might be faster * - Find way to reduce header size, possibly using the huffman algorithm twice to encode the header? * - Look into using a terminator byte instead of storing length, might reduce total size * - Combine with duplicate string removal and make full LZW compression * */ #include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &quot;dlist_library.h&quot; #include &quot;huffman.h&quot; int huff_tree_from_freq(size_t * freq, huffman_node_t ** head_node) { dlist_t * node_queue; huffman_node_t * char_node_list[256] = { NULL }; huffman_node_t * first_temp_node, * second_temp_node, * internal_node; size_t node_count = 0; if(!(node_queue = dlist_init(sizeof(huffman_node_t *)))) return MEM_ERROR; for(uint16_t i = 0; i &lt; 256; i++) if(freq[i] &amp;&amp; !(char_node_list[node_count++] = create_char_node(i - 128, freq[i]))) return MEM_ERROR; for(size_t i = 0; i &lt; node_count; i++) if(dlist_push(&amp;char_node_list[i], node_queue) != LIST_OK) return MEM_ERROR; dlist_sort(&amp;node_compare, node_queue); while(node_count-- &gt; 1) { dlist_pop(&amp;first_temp_node, node_queue); dlist_pop(&amp;second_temp_node, node_queue); if(!(internal_node = create_internal_node(first_temp_node, second_temp_node))) return MEM_ERROR; if(dlist_push(&amp;internal_node, node_queue) != LIST_OK) return MEM_ERROR; dlist_sort(&amp;node_compare_priority, node_queue); } dlist_pop(head_node, node_queue); dlist_destroy(node_queue); return EXIT_SUCCESS; } void destroy_huff_tree(huffman_node_t * node) { if(node-&gt;child[0]) { destroy_huff_tree(node-&gt;child[0]); destroy_huff_tree(node-&gt;child[1]); } free(node); return; } int huffman_encode(char * input, uint8_t ** output) { size_t freq[256] = { 0 }; uint16_t header_size = HEADER_BASE_SIZE; uint32_t length = strlen(input); for(size_t i = 0; i &lt; length; i++) freq[input[i] + 128]++; for(uint16_t i = 0; i &lt; 256; i++) if(freq[i]) header_size += 3; /* Handle strings with either one unique byte or zero bytes */ if(header_size == HEADER_BASE_SIZE) { return INPUT_ERROR; } else if(header_size == HEADER_BASE_SIZE + 3) { for(uint16_t i = 0; i &lt; 256; i++) if(freq[i]) ++freq[i &gt; 0 ? i - 1 : i + 1]; header_size += 3; } huffman_node_t * head_node = NULL; if(huff_tree_from_freq(freq, &amp;head_node) != EXIT_SUCCESS) return MEM_ERROR; uint8_t codes[256][2] = {{ 0 }}; code_array_from_tree(head_node, codes, 0); destroy_huff_tree(head_node); size_t encoded_bit_len = 0; /* Use the generated code array to calculate the byte length of the output */ for(size_t i = 0; i &lt; length; i++) encoded_bit_len += codes[input[i] + 128][1]; size_t encoded_byte_len = (encoded_bit_len &gt;&gt; 3) + !!(encoded_bit_len &amp; 0x7); /* Calculate bit length / 8, add one if there's a remainder */ uint8_t * str_out = NULL; if(!(str_out = calloc(encoded_byte_len + header_size + 1, sizeof(uint8_t)))) return MEM_ERROR; /* Write header information */ /* Bit level hack to store uint32_t's and uint16_t's in an array of uint8_t's */ str_out[0] = (uint8_t)length; str_out[1] = (uint8_t)(length &gt;&gt; 0x8); str_out[2] = (uint8_t)(length &gt;&gt; 0x10); str_out[3] = (uint8_t)(length &gt;&gt; 0x18); str_out[4] = (uint8_t)encoded_byte_len; str_out[5] = (uint8_t)(encoded_byte_len &gt;&gt; 0x8); str_out[6] = (uint8_t)(encoded_byte_len &gt;&gt; 0x10); str_out[7] = (uint8_t)(encoded_byte_len &gt;&gt; 0x18); str_out[8] = (uint8_t)header_size; str_out[9] = (uint8_t)(header_size &gt;&gt; 0x8); size_t byte_pos = HEADER_BASE_SIZE; /* Store the encoding information */ for(uint16_t i = 0; i &lt; 256; i++) { if(codes[i][1]) { str_out[byte_pos++] = i; str_out[byte_pos++] = codes[i][0]; str_out[byte_pos++] = codes[i][1]; } } /* Encode output stream */ for(size_t i = 0, bit_pos = 0; i &lt; length; i++) { for(size_t j = 0; j &lt; codes[input[i] + 128][1]; j++) { str_out[byte_pos] |= ((codes[input[i] + 128][0] &gt;&gt; j) &amp; 0x1) &lt;&lt; bit_pos; if(++bit_pos == 8) { bit_pos = 0; byte_pos++; } } } *output = str_out; return EXIT_SUCCESS; } int huffman_decode(uint8_t * input, char ** output) { size_t byte_pos = 0; uint8_t bit_pos = 0; uint8_t min_length = 8; uint8_t codes[256][2] = {{ 0 }}; uint32_t char_count = 0; /* Extract header information and build code array */ uint32_t length = * (uint32_t *) &amp;input[0]; uint16_t header_size = * (uint16_t *) &amp;input[8]; for(byte_pos = HEADER_BASE_SIZE; byte_pos &lt; header_size; byte_pos += 3) { codes[input[byte_pos]][0] = input[byte_pos + 1]; codes[input[byte_pos]][1] = input[byte_pos + 2]; if(codes[input[byte_pos]][1] &lt; min_length) min_length = codes[input[byte_pos]][1]; /* By knowing the smallest encoding length we can speed up the recursive decoding */ } char * str_out = NULL; if(!(str_out = calloc(length + 1, sizeof(char)))) return MEM_ERROR; huffman_node_t * head_node = NULL; if(huff_tree_from_codes(&amp;head_node, codes) == MEM_ERROR) return MEM_ERROR; /* Decode input stream */ while(char_count &lt; length) { for(uint8_t i = 0, byte = 0; i &lt; 8; i++) { byte |= ((input[byte_pos] &gt;&gt; bit_pos) &amp; 0x1) &lt;&lt; i; if(++bit_pos == 8) { bit_pos = 0; byte_pos++; } if(i + 1 &gt;= min_length &amp;&amp; (str_out[char_count] = is_char_node(byte, i + 1, head_node)) != '\0') { char_count++; break; } } } destroy_huff_tree(head_node); str_out[char_count] = '\0'; *output = str_out; return EXIT_SUCCESS; } char is_char_node(uint8_t byte, uint8_t bits_left, huffman_node_t * node) { static uint8_t bit_pos = 0; return (!bits_left) ? (bit_pos = 0, !node-&gt;child[0]) ? node-&gt;c : '\0' : is_char_node(byte, bits_left - 1, node-&gt;child[((byte &gt;&gt; bit_pos++) &amp; 0x1)]); /* This return is the best and worst line of code I've ever written */ } void code_array_from_tree(huffman_node_t * node, uint8_t huffman_array[256][2], uint8_t bits_set) { static uint8_t byte = '\0'; if(node-&gt;child[0]) { byte &amp;= ~(0x1 &lt;&lt; bits_set); code_array_from_tree(node-&gt;child[0], huffman_array, bits_set + 1); byte |= 0x1 &lt;&lt; bits_set; code_array_from_tree(node-&gt;child[1], huffman_array, bits_set + 1); } else { huffman_array[node-&gt;c + 128][0] = byte; huffman_array[node-&gt;c + 128][1] = bits_set; } } int huff_tree_from_codes(huffman_node_t ** head_node, uint8_t huffman_array[256][2]) { if(!(*head_node = malloc(sizeof(huffman_node_t)))) return MEM_ERROR; (*head_node)-&gt;child[0] = NULL; (*head_node)-&gt;child[1] = NULL; for(uint16_t i = 0; i &lt; 256; i++) if(huffman_array[i][1]) if(add_char_to_tree(*head_node, (char)(i - 128), huffman_array[i][0], huffman_array[i][1] - 1, 0) != EXIT_SUCCESS) return MEM_ERROR; return EXIT_SUCCESS; } int add_char_to_tree(huffman_node_t * node, char c, uint8_t byte, uint8_t bits_left, uint8_t curr_bit) { const uint8_t branch = (byte &gt;&gt; curr_bit) &amp; 0x1; if(!node-&gt;child[branch]) { if(!(node-&gt;child[branch] = malloc(sizeof(huffman_node_t)))) return MEM_ERROR; node-&gt;child[branch]-&gt;child[0] = NULL; node-&gt;child[branch]-&gt;child[1] = NULL; } if(bits_left) { return add_char_to_tree(node-&gt;child[branch], c, byte, bits_left - 1, curr_bit + 1); } else { node-&gt;child[branch]-&gt;c = c; return EXIT_SUCCESS; } } huffman_node_t * create_char_node(char c, size_t freq) { huffman_node_t * node; if(!(node = malloc(sizeof(huffman_node_t)))) return NULL; node-&gt;freq = freq; node-&gt;child[0] = NULL; node-&gt;child[1] = NULL; node-&gt;c = c; return node; } huffman_node_t * create_internal_node(huffman_node_t * first_child, huffman_node_t * second_child) { huffman_node_t * node; if(!(node = malloc(sizeof(huffman_node_t)))) return NULL; node-&gt;freq = first_child-&gt;freq + second_child-&gt;freq; node-&gt;child[0] = first_child; node-&gt;child[1] = second_child; return node; } int node_compare_priority(const void * first_node, const void * second_node) { return !((*(huffman_node_t **)first_node)-&gt;freq - (*(huffman_node_t **)second_node)-&gt;freq) ? 0 : (*(huffman_node_t **)second_node)-&gt;child[0] ? -1 : 0; } int node_compare(const void * first_node, const void * second_node) { return (*(huffman_node_t **)first_node)-&gt;freq - (*(huffman_node_t **)second_node)-&gt;freq; } void node_print(const void * element) { printf(&quot;Frequency: %zu\n&quot;, (*(huffman_node_t **)(element))-&gt;freq); if((*(huffman_node_t **)(element))-&gt;child[0]) printf(&quot;Node has children...\n&quot;); else printf(&quot;Node has no children, character is \&quot;%c\&quot;\n&quot;, (*(huffman_node_t **)(element))-&gt;c); } </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &quot;huffman.h&quot; int main() { uint8_t * encoded = NULL; char * decoded = NULL; char * test_strings[] = { &quot;test string&quot;, &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!\&quot;£$%^&amp;*()-=_+\\|,./&lt;&gt;?[]{}'#@~`¬\n&quot;, &quot;test&quot;, &quot;Hello, world!&quot;, &quot;This is a test string&quot;, &quot;My name is Jeff&quot;, &quot;Test&quot;, &quot;tteesstt&quot;, &quot;test&quot;, &quot;ab&quot;, &quot;Ω≈ç√∫˜µ≤≥÷&quot;, &quot;ЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя&quot;, &quot;If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you.&quot;, &quot;a&quot;, &quot;aaaaaaaaaaaaaa&quot;, &quot;\0&quot;, &quot;Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗&quot;, &quot;Hello, world! This is a test string test string If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you. tteesstt&quot; }; for(size_t i = 0; i &lt; sizeof(test_strings) / sizeof(char *); i++) { printf(&quot;\nEncoding string %zu...&quot;, i); fflush(stdout); if(huffman_encode(test_strings[i], &amp;encoded) != EXIT_SUCCESS) { fprintf(stderr, &quot;\nError: Failed to encode string \&quot;%s\&quot;!\n&quot;, test_strings[i]); continue; } printf(&quot;Done!\nAttempting to decode...&quot;); fflush(stdout); if(huffman_decode(encoded, &amp;decoded) != EXIT_SUCCESS) { fprintf(stderr, &quot;\nError: Failed to decode string!\nEncoded string was \&quot;%s\&quot;\n&quot;, test_strings[i]); free(encoded); continue; } printf(&quot;Done!\nValidating...&quot;); if(!strcmp(test_strings[i], decoded)) printf(&quot;Success!\n&quot;); else printf(&quot;Failed! Got \&quot;%s\&quot;!\n&quot;, decoded); free(decoded); free(encoded); } return 0; } </code></pre> <p><strong>Note:</strong> I am not looking for a review of any code below here in this question, I am saving this section for another review but I'm including it here because the rest of the code relies on it.</p> <p><strong>Edit:</strong> Since I wrote this code I was able to refactor it to completely remove this section</p> <p><strong>dlist_library.h</strong></p> <pre><code>#ifndef DLIST_H #define DLIST_H #include &lt;stdlib.h&gt; /* Needed for size_t */ /* Return values */ #define LIST_OK 0 #define MEM_ERROR 1 /* Memory allocation error */ #define SIZE_ERROR 2 /* list dimension error */ #define INDEX_ERROR 3 /* No data at given index */ /* List element data structure */ typedef struct list_element_t { void * data; /* Contains the data stored at this node */ struct list_element_t * next; /* Contains the pointer to the next element, or NULL if it's the tail node */ } dlist_element_t; /* List master data structure */ typedef struct { dlist_element_t * head; /* Pointer to the head of the list */ dlist_element_t * tail; /* Pointer to the tail of the list */ size_t data_width; /* The size of each element in the list */ int status; } dlist_t; /* User Functions */ dlist_element_t * dlist_search(void const * const data, int (*compare)(const void * first_element, const void * second_element), dlist_t * list); /* Search the list for an occurance of a given data value using a user defined comparison function */ dlist_t * dlist_init(size_t data_size); /* Initialise the list data structure */ int dlist_insert_before(void const * const data, dlist_element_t * element, dlist_t * list); /* Insert an element into the list at the position before a specified element */ int dlist_insert_after(void const * const data, dlist_element_t * element, dlist_t * list); /* Insert an element into the list at the position after a specified element */ int dlist_peek(void * const data, dlist_t * list); /* Check the contents of the element at the end of the list without popping the list */ int dlist_pop(void * const data, dlist_t * list); /* Pop an element from the front of the list, deals with cleanup when the head node is empty */ int dlist_push(void const * const data, dlist_t * list); /* Push an element to the back of the list, creates a new block when tail node is full */ int dlist_remove(dlist_element_t * element, dlist_t * list); /* Remove an element from the list and connect the two elements next to it */ void dlist_destroy(dlist_t * list); /* Destroy the list data structure and any associated nodes */ void dlist_operate(void(*operation)(const void * element), dlist_t * list); /* Perform a user defined action on every single element stored in the list */ void dlist_sort(int (*compare)(const void * first_element, const void * second_element), dlist_t * list); /* Sort all elements in the list using a merge sort */ /* Internal Functions */ dlist_element_t * dlist_merge_sorted(int (*compare)(const void * first_element, const void * second_element), dlist_element_t * head, dlist_element_t * second_head); void dlist_sort_split(dlist_element_t * source, dlist_element_t ** front, dlist_element_t ** back); void dlist_sort_internal(int (*compare)(const void * first_element, const void * second_element), dlist_element_t ** head); #endif </code></pre> <p><strong>dlist_library.c</strong></p> <pre><code>/* * Filename: dlist_library.c * Author: Jess Turner * Date: 10/08/18 * Licence: GNU GPL V3 * * Library for a generic, dynamically allocated singly linked list * * Return/exit codes: * LIST_OK - No error * SIZE_ERROR - list size error (invalid block size or number of datas) * MEM_ERROR - Memory allocation error * INDEX_ERROR - Couldn't pop data from the list * * All functions returning pointers will return NULL on memory allocation faliure, else they will specify an error in list-&gt;status for the user to handle * * Todo: * - Add secure versions of dlist_destroy(), dlist_pop(), and dlist_remove() to overwrite memory blocks that are no longer in use * - Add a parameter to dlist_destroy() and dlist_remove() containing a function pointer detailing how to delete the data stored in each node */ #include &lt;dlist_library.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; dlist_t * dlist_init(size_t data_width) { dlist_t * list; if(!(list = malloc(sizeof(dlist_t)))) return NULL; list-&gt;tail = NULL; list-&gt;head = NULL; list-&gt;data_width = data_width; list-&gt;status = LIST_OK; return list; } void dlist_destroy(dlist_t * list) { if(list == NULL) return; while(list-&gt;head) { dlist_element_t * temp = list-&gt;head-&gt;next; free(list-&gt;head); list-&gt;head = temp; } list-&gt;status = 0; list-&gt;data_width = 0; list-&gt;tail = NULL; free(list); } int dlist_push(void const * const data, dlist_t * list) { dlist_element_t * new_element; if(!(new_element = malloc(sizeof(dlist_element_t))) || !(new_element-&gt;data = malloc(list-&gt;data_width))) { if(new_element) free(new_element); return list-&gt;status = MEM_ERROR; } memcpy(new_element-&gt;data, data, list-&gt;data_width); if(list-&gt;head == NULL) list-&gt;head = new_element; else list-&gt;tail-&gt;next = new_element; list-&gt;tail = new_element; list-&gt;tail-&gt;next = NULL; return list-&gt;status = LIST_OK; } int dlist_pop(void * const data, dlist_t * list) { if(list-&gt;head == NULL) return list-&gt;status = INDEX_ERROR; memcpy(data, list-&gt;head-&gt;data, list-&gt;data_width); free(list-&gt;head-&gt;data); dlist_element_t * temp = list-&gt;head; list-&gt;head = list-&gt;head-&gt;next; free(temp); return list-&gt;status = LIST_OK; } int dlist_remove(dlist_element_t * element, dlist_t * list) { if(element == NULL || list-&gt;head == NULL) return list-&gt;status = INDEX_ERROR; if(list-&gt;head == element) { list-&gt;head = list-&gt;head-&gt;next; return list-&gt;status = LIST_OK; } dlist_element_t * prev = NULL; dlist_element_t * curr = list-&gt;head; while(curr != element) { prev = curr; curr = curr-&gt;next; if(curr == NULL) return list-&gt;status = INDEX_ERROR; } prev-&gt;next = curr-&gt;next; return list-&gt;status = LIST_OK; } int dlist_insert_after(void const * const data, dlist_element_t * element, dlist_t * list) { if(list-&gt;head == NULL) return dlist_push(data, list); dlist_element_t * new_element; if(!(new_element = malloc(sizeof(dlist_element_t))) || !(new_element-&gt;data = malloc(list-&gt;data_width))) { if(new_element) free(new_element); return list-&gt;status = MEM_ERROR; } memcpy(new_element-&gt;data, data, list-&gt;data_width); new_element-&gt;next = element-&gt;next; element-&gt;next = new_element; if(element == list-&gt;tail) list-&gt;tail = new_element; return list-&gt;status = LIST_OK; } int dlist_insert_before(void const * const data, dlist_element_t * element, dlist_t * list) { if(list-&gt;head == NULL) return dlist_push(data, list); dlist_element_t * prev = list-&gt;head; dlist_element_t * curr = prev-&gt;next; while(curr != NULL &amp;&amp; curr != element) { curr = curr-&gt;next; prev = prev-&gt;next; } if(curr == NULL) return list-&gt;status = INDEX_ERROR; dlist_element_t * new_element; if(!(new_element = malloc(sizeof(dlist_element_t))) || !(new_element-&gt;data = malloc(list-&gt;data_width))) { if(new_element) free(new_element); return list-&gt;status = MEM_ERROR; } memcpy(new_element-&gt;data, data, list-&gt;data_width); if(curr == list-&gt;head) { new_element-&gt;next = curr; list-&gt;head = new_element; } else { new_element-&gt;next = prev-&gt;next; prev-&gt;next = new_element; } return list-&gt;status = LIST_OK; } dlist_element_t * dlist_search(void const * const data, int (*compare)(const void * first_element, const void * second_element), dlist_t * list) { dlist_element_t * curr; for(curr = list-&gt;head; curr != NULL; curr = curr-&gt;next) if(!(*compare)(curr-&gt;data, data)) return curr; list-&gt;status = INDEX_ERROR; return NULL; } int dlist_peek(void * const data, dlist_t * list) { if(list-&gt;head == NULL) return list-&gt;status = INDEX_ERROR; memcpy(data, list-&gt;head-&gt;data, list-&gt;data_width); return list-&gt;status = LIST_OK; } void dlist_sort_split(dlist_element_t * source, dlist_element_t ** front, dlist_element_t ** back) { dlist_element_t * slow = source; dlist_element_t * fast = source-&gt;next; while(fast != NULL) { fast = fast-&gt;next; if(fast != NULL) { slow = slow-&gt;next; fast = fast-&gt;next; } } *front = source; *back = slow-&gt;next; slow-&gt;next = NULL; } dlist_element_t * dlist_merge_sorted(int (*compare)(const void * first_element, const void * second_element), dlist_element_t * head, dlist_element_t * second_head) { dlist_element_t * result = NULL; if(head == NULL) return second_head; else if(second_head == NULL) return head; if(compare(head-&gt;data, second_head-&gt;data) &lt; 0) { result = head; result-&gt;next = dlist_merge_sorted(compare, head-&gt;next, second_head); } else { result = second_head; result-&gt;next = dlist_merge_sorted(compare, head, second_head-&gt;next); } return result; } void dlist_sort_internal(int (*compare)(const void * first_element, const void * second_element), dlist_element_t ** head) { dlist_element_t * back = NULL; dlist_element_t * front = NULL; if(*head == NULL || (*head)-&gt;next == NULL) return; dlist_sort_split(*head, &amp;front, &amp;back); dlist_sort_internal(compare, &amp;front); dlist_sort_internal(compare, &amp;back); *head = dlist_merge_sorted(compare, front, back); } void dlist_sort(int (*compare)(const void * first_element, const void * second_element), dlist_t * list) { if(list-&gt;head == NULL) list-&gt;status = INDEX_ERROR; dlist_sort_internal(compare, &amp;list-&gt;head); for(dlist_element_t * curr = list-&gt;head; curr != NULL; curr = curr-&gt;next) if(curr-&gt;next == NULL) list-&gt;tail = curr; } void dlist_operate(void(*operation)(const void * element), dlist_t * list) { for(dlist_element_t * curr = list-&gt;head; curr != NULL; curr = curr-&gt;next) operation(curr-&gt;data); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T00:22:49.590", "Id": "483157", "Score": "1", "body": "My [feedback from last time](https://codereview.stackexchange.com/a/245441/25834) - much of that still applies here." }, { "ContentLicense": "CC BY-SA 4.0", "Creation...
[ { "body": "<p>There is a lot here, so I only address a couple of points.</p>\n\n<blockquote>\n <p>What are some ways I can reduce the header size to improve the compression ratios?</p>\n</blockquote>\n\n<p>An effective trick is switching to using <a href=\"https://en.wikipedia.org/wiki/Canonical_Huffman_code\"...
{ "AcceptedAnswerId": "201533", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T16:38:29.173", "Id": "201521", "Score": "8", "Tags": [ "performance", "c", "memory-management", "compression", "memory-optimization" ], "Title": "Huffman Coding library implemented in C" }
201521
<p>I'm writing a basic program that calculates the total base resources needed to craft items in Minecraft. It's intended to be modular for support for modded versions of Minecraft (new items or different recipe's).</p> <p>To start, I created an Item class that will function as a base resource. A base resource is something I have determined to be harvestable in Minecraft (such as planks or coal) or something that is easily craftable and does not warrant its own recipe (such as an iron ingot, easily obtained by smelting iron ore).</p> <pre><code>public class Item { String name; int count; boolean isPopulated; boolean isItem; public Item() { this.name = ""; this.count = 1; this.isPopulated = false; this.isItem = true; } public Item(String name) { this.name = name; this.count = 1; this.isPopulated = false; this.isItem = true; } public Item(int count) { this.name = ""; this.count = count; this.isPopulated = false; this.isItem = true; } public Item(int count, String name) { this.name = name; this.count = count; this.isPopulated = false; this.isItem = true; } public String getName() { return this.name; } public int getCount() { return this.count; } public void setName(String name) { this.name = name; } public void setcount(int count) { this.count = count; } } </code></pre> <p>Here's an example of an Item class:</p> <pre><code>public class IronIngot extends Item{ public IronIngot(int count) { super(count); this.name = "Iron Ingot"; } } </code></pre> <p>Next is the tricky part (at least for me): I created a Recipe class that has a list of items (or other recipe's) that are used to craft a craftable item. I was able to use some form of recursion to account for craftable items whose recipe has craftable items in them</p> <pre><code>public class Recipe extends Item { List&lt;Item&gt; components; List&lt;Item&gt; materials; public Recipe() { this.components = new ArrayList&lt;&gt;(); this.materials = new ArrayList&lt;&gt;(); this.isItem = false; } public Recipe(int count) { super(count); this.components = new ArrayList&lt;&gt;(); this.materials = new ArrayList&lt;&gt;(); this.isItem = false; } public void printRecipe() { System.out.println("Recipe for " + this.name + ":"); this.components.forEach((item) -&gt; { System.out.println("\t" + item.name + ": " + item.count); }); System.out.println(); } public void printMaterials() { populateMaterials(); System.out.println("Materials needed for " + this.name + ":"); this.materials.forEach((item) -&gt; { System.out.println("\t" + item.name + ": " + item.count); }); System.out.println(); } public void populateMaterials() { this.components.forEach((item) -&gt; { if (!item.isPopulated) { if (item.isItem) { this.addMaterial(item); } else { Recipe tempRecipe = (Recipe) item; } } }); } public void addMaterial(Item item) { this.materials.forEach((material) -&gt; { if (material.name.equals(item.name)) { item.isPopulated = true; material.count += item.count; } }); if (!item.isPopulated) { item.isPopulated = true; this.materials.add(item); } } public void addMaterials(List&lt;Item&gt; materials) { materials.forEach((material) -&gt; { if (!material.isItem) { Recipe tempRecipe = (Recipe) material; this.addMaterials(tempRecipe.getMaterials()); } else { this.addMaterial((Item) material); } }); } public List getItems() { return this.components; } public List getMaterials() { populateMaterials(); this.materials.forEach((material) -&gt; { material.isPopulated = false; }); return this.materials; } } </code></pre> <p>Here's an example of a recipe class:</p> <pre><code>public class CopperCoilBlock extends Recipe{ public CopperCoilBlock(){ this.name = "Copper Coil Block"; this.components.add(new LVWireCoil(8)); this.components.add(new IronIngot(1)); } public CopperCoilBlock(int count){ super(count); this.name = "Copper Coil Block"; this.components.add(new LVWireCoil(8)); this.components.add(new IronIngot(1)); } } </code></pre> <p>My problem is this: how do I account for the resource cost of crafting recipe's that yield multiple items? For example, to make a Power cell(low) I need to have a copper coil block. To make a copper coil block I need 8 LV Wire coils and 1 iron ingot. The recipe for LV wire coils is that 4 copper wires and 1 stick yields 4 LV wire coils. This means that to make a copper coil block I need 8 copper wires and 2 sticks. My initial thought was to solve this using the count integer present in every item but I don't know how to implement it or if this is even the best process. Here is what the LVWireCoil class looks like:</p> <pre><code>public class LVWireCoil extends Recipe { public LVWireCoil(int count) { super(4); this.name = "LV Wire Coil"; this.components.add(new CopperWire(4)); this.components.add(new Sticks(1)); } } </code></pre> <p>Also, I have quite a bit to learn with java so any constructive criticism (code conventions, logic, etc) would be welcome!</p>
[]
[ { "body": "<p>Here are my comments:</p>\n\n<h2><code>Item</code> common super class of itself and <code>Recipe</code></h2>\n\n<p>I understand this design decision stems from the requirement that Recipes are Items of other Recipes. and this is the cause of the confusing <code>isItem</code> property of the <code>...
{ "AcceptedAnswerId": "201573", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T17:50:57.817", "Id": "201525", "Score": "1", "Tags": [ "java", "minecraft" ], "Title": "Minecraft resource calculator" }
201525
<p>I've written a Powershell script that uses Robocopy to get the full path of all files on a drive and then run it through a foreach loop to get the owner for each file and generate it in a CSV. The code works, but is very slow when I run it against so many items. Can someone help me make it as efficient as possible? I also use "File System Security PowerShell Module 4.2.3" to use Get-NTFSOwner which gets me around the 256 character limit, which is also why I use Robocopy to generate the paths.</p> <pre><code>Import-Module NTFSSecurity #Gets initial file and folder list $Folderpath = "G:\DEPT" $Folders = Get-Childitem $Folderpath ForEach ($Folder in $Folders) {Start-Job -ScriptBlock { Param($Folder,$Folderpath) robocopy "$FolderPath\$Folder" NULL /L /S /NJH /FP /NC /XJ /NS /NJH /NC /NJS /LOG:D:\AutoAssign\Data\RoboLogs\$Folder.txt } -ArgumentList $Folder,$Folderpath} #Wait unitl all jobs are finished Get-Job | Wait-Job #Trims out white space and empty lines $Folderpath = "D:\AutoAssign\Data\RoboLogs" $Files = Get-Childitem $Folderpath ForEach ($File in $Files) {Start-Job -ScriptBlock { Param($File,$Folderpath,$Files) $Trim = Get-Content "$Folderpath\$File" $Trim.trim() | Where { $_ } | Out-File "$Folderpath\$File" } -ArgumentList $File,$Folderpath,$Files } #Wait unitl all jobs are finished Get-Job | Wait-Job #Gets Owner for each file And Create CSV $Dir = "D:\AutoAssign\Data\RoboLogs" $Files = Get-ChildItem $Dir ForEach ($File in $Files){ Start-Job -ScriptBlock { Param($Dir,$Files,$File) $OutputFile = "D:\AutoAssign\Data\Final\$File.csv" $Results = @() $Paths = Get-Content $Dir\$File ForEach ($Path in $Paths){ $Owner = get-ntfsowner $Path | Select Owner | ft -hidetableheaders | Out-String $Owner = $Owner.Trim() $Properties = @{ Path = $Path Owner = $Owner } If ($Owner -ne "BUILTIN\Administrators" -and $Owner -ne $null-and $Owner -ne "Domain\Domain Admins" -and $Owner -notlike "S-1*"){ $Results += New-Object psobject -Property $properties} } $Results | Export-Csv -notypeinformation -Path $OutputFile } -ArgumentList $Dir,$Files,$File #Ends Initial ForEach } #Ends Job Script Block #Wait unitl all jobs are finished Get-Job | Wait-Job #Merge all files into one CSV Get-ChildItem D:\AutoAssign\Data\Final | Select-Object -ExpandProperty FullName | Import-Csv | Export-Csv D:\AutoAssign\Data\G.csv -NoTypeInformation -Append #Delete all original files Get-ChildItem D:\AutoAssign\Data\RoboLogs | Remove-Item Get-ChildItem D:\AutoAssign\Data\Final | Remove-Item </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T20:35:56.797", "Id": "388124", "Score": "0", "body": "What PowerShell Version ? I'd avoid using `$Result+=` as it rebuilds the whole array each time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T22...
[ { "body": "<p>Your robocopy command lists <code>/NC</code> and <code>/NJH</code> twice.</p>\n\n<p><code>$Folders</code> and <code>$Folder</code> contain objects with properties, use these instead of treating them as strings (which implicit casts them as such) or pipe to <code>Select-Object -ExpandProperty FullN...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T19:12:32.213", "Id": "201527", "Score": "3", "Tags": [ "time-limit-exceeded", "csv", "file-system", "powershell" ], "Title": "Get owner of ~5 million files and folders using Powershell and Robocopy" }
201527
<p>This is a non-deterministic finite state automata (NFA) meant to be used with a Regex engine. To show some example usage, suppose you wanted to construct an NFA for the regex <code>(ad|[0-9])*</code>. It might look something like this:</p> <pre><code>ad_literal = NFA.from_string('ad') number_set = NFA.from_set({str(x) for x in range(10)}) union = ad_literal.union(number_set) final_nfa = union.kleene() final_nfa.match('adbeadf') &gt;&gt;&gt; ad </code></pre> <p>I'm mainly hoping for pointers for making this more organized and readable. I'm pretty happy with how the public functions turned out, but it seems like all the helpers are a bit of a mess. I think maybe there's another class hiding somewhere, but since it's all a light wrapper around a list anyway, I don't see anywhere to draw the line.</p> <pre><code>import string class DFA(object): def __init__(self, table, terminals): self._table = table self._terminals = terminals def match(self, pattern: str) -&gt; str: match_string = '' state = 0 last_match = '' for char in pattern: try: state = self._table[state][ord(char)] if state == -1: return last_match if char in string.printable: match_string += char if state in self._terminals: last_match = match_string except KeyError: return last_match return last_match class NFA(object): def __init__(self): self._initial_state = 0 self._terminal_state = 0 self._table = [] self._dfa = None # type: DFA def match(self, source: str) -&gt; str: if not self._dfa: self._dfa = self.to_dfa() return self._dfa.match(source) def concat(self, other: 'NFA') -&gt; 'NFA': new_nfa = NFA() new_nfa._table = [x.copy() for x in self._table] self._copy_table(other._table, new_nfa._table, lambda s: s + self._terminal_state) new_nfa._terminal_state = len(new_nfa._table) return new_nfa def kleene(self): new_table = [self._empty_row()] self._set_transition(new_table[0], '\0', {1, self._terminal_state + 1}) self._copy_table(self._table, new_table, lambda s: s + 1) # Add null transition to new terminal state, or to beginning new_table.append(self._empty_row()) self._set_transition(new_table[-1], '\0', {self._terminal_state + 2, 1}) new_nfa = NFA() new_nfa._table = new_table new_nfa._terminal_state = self._terminal_state + 2 return new_nfa def union(self, other: 'NFA'): new_terminal_state = self._terminal_state + other._terminal_state + 1 new_table = [self._empty_row()] new_table[0][ord('\0')] = {1, self._terminal_state + 1} self._copy_table(self._table, new_table, lambda s: new_terminal_state if s == self._terminal_state else s + 1) self._copy_table(other._table, new_table, lambda s: (new_terminal_state if s == other._terminal_state else s + 1 + self._terminal_state)) new_nfa = NFA() new_nfa._table = new_table new_nfa._terminal_state = new_terminal_state return new_nfa def to_dfa(self) -&gt; DFA: characters = [chr(i) for i in range(128)] start_state = frozenset(self._epsilon_closure({self._initial_state})) dfa_states = self._collect_nfa_states(characters, start_state) nfa_to_dfa_state_map = {start_state: 0} for i, state in enumerate(dfa_states.difference({start_state})): nfa_to_dfa_state_map[state] = i + 1 nfa_to_dfa_state_map[frozenset()] = -1 # Just invert it dfa_to_nfa_state_map = {v: k for k, v in nfa_to_dfa_state_map.items()} dfa_table = [[-1 for _ in characters] for _ in dfa_states] for dfa_state in dfa_to_nfa_state_map: if dfa_state == -1: continue nfa_state = dfa_to_nfa_state_map[dfa_state] for char in characters: if char == '\0': continue next_nfa_state = frozenset(self._epsilon_closure(self._next_states(nfa_state, char))) next_dfa_state = (nfa_to_dfa_state_map[next_nfa_state] if next_nfa_state in nfa_to_dfa_state_map else -1) dfa_table[dfa_state][ord(char)] = next_dfa_state terminal_nfa_states = {state for state in dfa_states if self._terminal_state in state} terminal_dfa_states = {nfa_to_dfa_state_map[state] for state in terminal_nfa_states} return DFA(dfa_table, terminal_dfa_states) def _collect_nfa_states(self, characters, start_state): dfa_states = {start_state} checked_dfa_states = set() while dfa_states: current_state = dfa_states.pop() new_states = set() for char in characters: next_state = frozenset(self._epsilon_closure(self._next_states(current_state, char))) checked_dfa_states.add(current_state) if next_state and next_state not in checked_dfa_states: new_states.add(next_state) dfa_states.update(new_states) return checked_dfa_states def _next_states(self, states: {int}, char: str) -&gt; {int}: result = set() for state in states: result.update(self._at(state, char)) return result def _single_state_closure(self, state: int) -&gt; {int}: return self._at(state, '\0') def _epsilon_closure(self, state: {int}) -&gt; {int}: if not state: return set() to_check = state.copy() checked = set() closure = state.copy() iteration = set() while to_check: # Copy states to current iteration while to_check: iteration.add(to_check.pop()) for state in iteration: next_states = self._single_state_closure(state) if state not in checked: checked.add(state) to_check.update(next_states) closure.update(next_states) return closure def _at(self, state: int, char: str): if state &gt;= len(self._table): return set() return self._table[state][ord(char)] def _add_row(self, row_number): while row_number &gt;= len(self._table): self._table.append(self._empty_row()) def _add_transition(self, start_state: int, next_state: int, char: str) -&gt; None: assert len(char) == 1 if start_state &gt;= len(self._table): self._add_row(start_state) self._table[start_state][ord(char)].add(next_state) @staticmethod def _empty_row(): return [set() for _ in range(128)] @staticmethod def _set_transition(row: [set], character: str, states: {int}): row[ord(character)] = states @staticmethod def from_string(pattern: str) -&gt; 'NFA': nfa = NFA() current_state = nfa._initial_state for char in pattern: nfa._add_transition(current_state, current_state + 1, char) current_state += 1 nfa._terminal_state = len(pattern) return nfa @staticmethod def from_set(union: {str}) -&gt; 'NFA': nfa = NFA() nfa._add_row(0) for char in union: nfa._table[0][ord(char)] = {1} nfa._add_transition(1, 2, '\0') nfa._terminal_state = 2 return nfa @staticmethod def _copy_table(source, dest, state_function): for row in source: row_copy = [] for state_set in row: row_copy.append({state_function(state) for state in state_set}) dest.append(row_copy) </code></pre> <p>Below are some more usage examples. Here are some simple unit tests:</p> <pre><code>import unittest from automata import NFA class TestNfa(unittest.TestCase): def test_union(self): nfa = NFA.from_string('abc') nfa = nfa.union(NFA.from_string('def')) self.assertEqual(nfa.match('abc'), 'abc') self.assertEqual(nfa.match('def'), 'def') self.assertEqual(nfa.match('de'), '') def test_kleene(self): nfa = NFA.from_string('abc') nfa = nfa.kleene() self.assertEqual(nfa.match(''), '') self.assertEqual(nfa.match('abc'), 'abc') self.assertEqual(nfa.match('abcabc'), 'abcabc') self.assertEqual(nfa.match('abcDabc'), 'abc') def test_concat(self): nfa = NFA.from_string('ab') nfa = nfa.concat(NFA.from_string('cd')) self.assertEqual(nfa.match('abcd'), 'abcd') self.assertEqual(nfa.match('abcde'), 'abcd') self.assertEqual(nfa.match('abc'), '') </code></pre> <p>And here is a (non-runnable) excerpt from my Regex class which shows the usage in context:</p> <pre><code>def parse_basic_re(self): """ &lt;elementary-re&gt; "*" | &lt;elementary-re&gt; "+" | &lt;elementary-re&gt; """ nfa = self.parse_elementary_re() if not nfa: return None next_match = self._lexer.peek() if not next_match or next_match.token != Token.METACHAR: return nfa if next_match.lexeme == '*': self._lexer.eat_metachar('*') return nfa.kleene() if next_match.lexeme == '+': self._lexer.eat_metachar('+') return nfa.union(nfa.kleene()) return nfa </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T05:45:43.160", "Id": "388158", "Score": "0", "body": "Do you have any tests? I'd be interested in seeing how your tests can expand upon your comment at the top, when you talk about how you use the NFA, and test against some real-lif...
[ { "body": "<p>Just reviewing <code>DFA</code>.</p>\n\n<ol>\n<li><p>There are no docstrings. What does an object belonging to this class represent? What arguments do I pass to the constructor? What does the <code>match</code> method do?</p></li>\n<li><p>In Python 3, all classes inherit from <code>object</code> s...
{ "AcceptedAnswerId": "201731", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T19:49:55.040", "Id": "201528", "Score": "6", "Tags": [ "python", "python-3.x", "regex", "state-machine" ], "Title": "Finite state automata" }
201528
<p>This is a recursive approach using DFS to counting the number of islands. However, I would like to improve performance, while keeping the code clean concise and readable. Better yet can this be solved using bitwise operations?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var numIslands = function(grid) { const search = (row, col, grid) =&gt; { if (row &lt; 0 || col &lt; 0 || row &gt; grid.length - 1 || col &gt; grid[row].length - 1 || grid[row][col] === '0') { return; } grid[row][col] = '0'; search(row - 1, col, grid); search(row, col - 1, grid); search(row + 1, col, grid); search(row, col + 1, grid); } let count = 0; grid.forEach((row, index) =&gt; { row.forEach((value, i) =&gt; { if (value === "1") { search(index, i, grid) count++ } }) }) return count } console.log(numIslands([ ["1", "1", "1"], ["1", "1", "0"], ["1", "1", "1"], ["0", "1", "0"], ["1", "1", "1"] ])) console.log(numIslands([ ["1", "1", "1"], ["0", "0", "0"], ["1", "1", "1"], ["0", "0", "0"], ["1", "1", "1"] ]))</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-17T20:09:10.083", "Id": "421097", "Score": "0", "body": "Instead of using `console.log` you should rather write real unit tests. The main point is that these unit tests not only contain the input data but also the expected output data....
[ { "body": "<p>So the logic I used was to check if a cell is part of an existing island either to above (n) or to the left (w). I came up with three possibilities:</p>\n\n<ul>\n<li>Neither n nor w is an island so start a new island, record the islands number and increment the count.</li>\n<li>Only one of the adj...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T20:21:40.743", "Id": "201530", "Score": "1", "Tags": [ "javascript", "algorithm", "recursion", "depth-first-search" ], "Title": "Count number of islands 2d grid" }
201530
<pre><code>#include &lt;iterator&gt; #include &lt;memory&gt; #include &lt;algorithm&gt; template&lt;typename RandomIt&gt; void sub_merge(RandomIt begin, RandomIt mid, RandomIt end) { // create copy of input array; const auto left_size = std::distance(begin, mid); const auto right_size = std::distance(mid, end); auto left = std::make_unique&lt;typename std::iterator_traits&lt;RandomIt&gt;::value_type[]&gt;(left_size); auto right = std::make_unique&lt;typename std::iterator_traits&lt;RandomIt&gt;::value_type[]&gt;(right_size); const auto left_begin = left.get(); const auto left_end = left_begin + left_size; const auto right_begin = right.get(); const auto right_end = right_begin + right_size; std::copy(begin, mid, left_begin); std::copy(mid, end, right_begin); // merge until one array is completed auto left_iter = left_begin; auto right_iter = right_begin; auto arr_iter = begin; while (left_iter &lt; left_end &amp;&amp; right_iter &lt; right_end) { if (*left_iter &lt; *right_iter) { *arr_iter = *left_iter; left_iter++; } else { *arr_iter = *right_iter; right_iter++; } arr_iter++; } // copy remaining array over std::copy(right_iter, right_end, arr_iter); std::copy(left_iter, left_end, arr_iter); } template&lt;typename RandomIt&gt; void merge_sort(RandomIt begin, RandomIt end) { if (begin &lt; end - 1) { const auto mid = begin + std::distance(begin, end) / 2; merge_sort(begin, mid); merge_sort(mid, end); sub_merge(begin, mid, end); } } </code></pre> <p>My testing shows this to be correctly implemented, however I want to know if there is anywhere I could be more efficient. I also have no way to prove if my templates are used correctly. I also do not know which Iterator type is appropriate for this. STL uses RandomIterator so I went with that but I think InputIterator or possibly ForwardIterator would be suitable.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T01:26:47.727", "Id": "388136", "Score": "0", "body": "Which version of C++ is this targeting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T01:28:01.287", "Id": "388137", "Score": "0", "...
[ { "body": "<p>Well, interesting.</p>\n\n<ol>\n<li><p>There's a bug in <code>merge_sort()</code>: Subtracting <code>1</code> from <code>end</code>, without knowing whether the range is empty, is Undefined Behavior. Subtract the iterators and compare the difference instead. While you are at it, use <code>std::dis...
{ "AcceptedAnswerId": "201540", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T23:55:22.317", "Id": "201534", "Score": "7", "Tags": [ "c++", "iterator", "mergesort" ], "Title": "Merge Sort implemented using iterators" }
201534
<p>Here's my attempt at a C++2a Standard Library–friendly "<a href="https://en.wikipedia.org/wiki/Topological_sorting" rel="nofollow noreferrer">topological sort</a>" algorithm. There are several areas of interest here:</p> <ul> <li><p>The algorithm is comparison-based and in-place, just like <code>std::sort</code>. This makes it something like \$\mathcal{O}(n^3)\$, which is certainly worse than it ought to be. Can we speed it up somehow without requiring any extra memory? </p></li> <li><p>Is my use of <code>operator&lt;=&gt;</code>, <code>partial_ordering</code>, etc. idiomatic? (Obviously we're still in the process of developing these idioms, but I think it'd be good to start talking about them.)</p></li> <li><p>I threw in an "optimization" for comparison categories other than <code>partial_ordering</code> (namely <code>strong_ordering</code> and <code>weak_ordering</code>). Is this safe? Is this smart? Is this <em>sufficiently</em> smart?</p></li> </ul> <hr> <pre><code>#include &lt;algorithm&gt; #include &lt;compare&gt; #include &lt;iterator&gt; #include &lt;type_traits&gt; // Some helpers that should be standard but aren't. template&lt;class It&gt; using iterator_category_t = typename std::iterator_traits&lt;It&gt;::iterator_category; template&lt;class It&gt; using iterator_value_type_t = typename std::iterator_traits&lt;It&gt;::value_type; template&lt;class It&gt; struct is_forward_iterator : std::is_base_of&lt;std::forward_iterator_tag, iterator_category_t&lt;It&gt;&gt; {}; template&lt;class It&gt; inline constexpr bool is_forward_iterator_v = is_forward_iterator&lt;It&gt;::value; template&lt;class It&gt; struct is_random_access_iterator : std::is_base_of&lt;std::random_access_iterator_tag, iterator_category_t&lt;It&gt;&gt; {}; template&lt;class It&gt; inline constexpr bool is_random_access_iterator_v = is_random_access_iterator&lt;It&gt;::value; template&lt;class T&gt; struct is_weak_ordering : std::is_convertible&lt;T, std::weak_ordering&gt; {}; template&lt;class T&gt; inline constexpr bool is_weak_ordering_v = is_weak_ordering&lt;T&gt;::value; // One more helper that WILL be standard but isn't. template&lt;class T = void&gt; struct spaceship { constexpr auto operator()(const T&amp; a, const T&amp; b) const -&gt; decltype(a &lt;=&gt; b) { return a &lt;=&gt; b; } }; template&lt;&gt; struct spaceship&lt;void&gt; { template&lt;class T, class U&gt; constexpr auto operator()(T&amp;&amp; t, U&amp;&amp; u) const -&gt; decltype(std::forward&lt;T&gt;(t) &lt;=&gt; std::forward&lt;U&gt;(u)) { return (std::forward&lt;T&gt;(t) &lt;=&gt; std::forward&lt;U&gt;(u)); } using is_transparent = void; }; // Here's the topological sorting algorithm itself. template&lt;class FwdIt, class Comparator = spaceship&lt;iterator_value_type_t&lt;FwdIt&gt;&gt;&gt; void topological_sort(FwdIt first, FwdIt last, Comparator cmp = Comparator{}) { if constexpr ( is_random_access_iterator_v&lt;FwdIt&gt; &amp;&amp; is_weak_ordering_v&lt;decltype(cmp(*first, *first))&gt; ) { std::sort(first, last, [&amp;](const auto&amp; a, const auto&amp; b) { return cmp(a, b) &lt; 0; }); } else { for (auto mark = first; mark != last; ++mark) { auto current_min = mark; auto last_min = current_min; while (true) { for (auto it = mark; it != last; ++it) { if (cmp(*it, *current_min) &lt; 0) { current_min = it; } } if (last_min == current_min) break; last_min = current_min; } if (current_min != mark) { using std::swap; swap(*current_min, *mark); } } } } </code></pre> <p>Finally, here's some quick-and-dirty testing code. The <code>Task</code> example is cribbed from one of the answers to <a href="https://stackoverflow.com/questions/11230881/stable-topological-sort">https://stackoverflow.com/questions/11230881/stable-topological-sort</a> .</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;vector&gt; struct Task { char k; Task(char k): k(k) {} bool operator==(Task rhs) const { return k == rhs.k; } bool operator!=(Task rhs) const { return k != rhs.k; } bool depends_on(Task rhs) const { if (k == 'A' &amp;&amp; rhs.k == 'B') return true; if (k == 'B' &amp;&amp; rhs.k == 'D') return true; return false; } struct order { std::partial_ordering operator()(Task a, Task b) const { if (a == b) return std::partial_ordering::equivalent; if (b.depends_on(a)) return std::partial_ordering::less; if (a.depends_on(b)) return std::partial_ordering::greater; return std::partial_ordering::unordered; } }; }; float nan() { return 0./0.; } int main() { std::vector&lt;int&gt; vi {3, 1, 4, 1, 5, 9, 2, 6, 5}; topological_sort(vi.begin(), vi.end()); for (auto&amp;&amp; elt : vi) { std::cout &lt;&lt; elt &lt;&lt; std::endl; } std::vector&lt;float&gt; vec {3, nan(), 1, 4, 1, 5, nan(), 2, 6, nan()}; topological_sort(vec.begin(), vec.end()); for (auto&amp;&amp; elt : vec) { std::cout &lt;&lt; elt &lt;&lt; std::endl; } std::list&lt;Task&gt; tasks { 'A','B','C','D','E','F' }; topological_sort(tasks.begin(), tasks.end(), Task::order{}); for (auto&amp;&amp; elt : tasks) { std::cout &lt;&lt; elt.k &lt;&lt; std::endl; } } </code></pre> <p><a href="https://godbolt.org/g/pvMpHQ" rel="nofollow noreferrer">Here's the complete code on Godbolt.</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T07:46:49.120", "Id": "388170", "Score": "0", "body": "It seems like the DFS approach from the linked wikipedia article could be worked into a general \\$\\mathcal{O}(n^2)\\$ topological sort (well, by using stack space for recursion...
[ { "body": "<h2>What's \"C++2a-friendly\" anyway?</h2>\n\n<p>I'm not sure what you mean by C++2a-friendly. The spaceship operator isn't out yet, and will be part of the next standard. So it isn't C++2a-friendly, it's C++2a period, or what don't I understand?</p>\n\n<p>If by C++2a-friendly you mean: using availab...
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T03:36:58.550", "Id": "201544", "Score": "7", "Tags": [ "c++", "algorithm", "sorting", "generics", "c++20" ], "Title": "C++2a comparison-based topological sort algorithm" }
201544
<p>A good friend of mine had the challenge of trying to build a schedule using all available times and classes through a spreadsheet... by hand. He asked me if I could build a program to generate valid schedules, and with search algorithms being one of my favorite things to do, I accepted the task.</p> <p>At first glance through my research, I believed this to be an Interval Scheduling problem; however, since the courses have unique timespans on multiple days, I needed a better way to represent my data. Ultimately I constructed a graph where the vertices are the sections of a class and the neighbors are compatible sections. This allowed me to use a DFS-like algorithm to find schedules.</p> <p>I have never asked for a code review since I am yet to take CS classes, but I would like to know where I stand with my organization, usage of data structures, and general approaches. One thing I also want an opinion on is commenting, something I <em>rarely</em> do and one day it will come back to haunt me. This is actually the first time I wrote docstrings, which I hope you will find useful in understanding the code.</p> <p>Anyways, I exported a spreadsheet of the valid courses into a .csv file. Below is the Python code I wrote to parse the file and generate schedules:</p> <p><strong>scheduler.py</strong></p> <pre><code>import csv from collections import defaultdict from enum import Enum class Days(Enum): """ Shorthand for retrieving days by name or value """ Monday = 0 Tuesday = 1 Wednesday = 2 Thursday = 3 Friday = 4 class Graph: """ A simple graph which contains all vertices and their edges; in this case, the class and other compatible classes :param vertices: A number representing the amount of classes """ def __init__(self, vertices): self.vertices = vertices self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) class Section: """ Used to manage different sections of a class Includes all times and days for a particular section :param section_str: A string used to parse the times at which the class meets Includes weekday, start time, and end time Format as follows: Monday,7:00,9:30/Tuesday,3:30,5:30/Wednesday,5:30,6:50 :param class_name: The name used to refer to the class (course) :param preferred: Preferred classes will be weighted more heavily in the search :param required: Search will force this class to be in the schedule """ def __init__(self, section_str, class_name='Constraint', preferred=False, required=False): self.name = class_name self.preferred = preferred self.required = required self.days = [] for course in section_str.rstrip('/').split('/'): d = {} data = course.split(',') day_mins = Days[data[0]].value * (60 * 24) d['start_time'] = self.get_time_mins(data[1]) + day_mins d['end_time'] = self.get_time_mins(data[2]) + day_mins self.days.append(d) """ Parses a time into minutes since Monday at 00:00 by assuming no class starts before 7:00am :param time_str: A string containing time in hh:mm :returns: Number of minutes since Monday 00:00 """ @staticmethod def get_time_mins(time_str): time = time_str.split(':') h = int(time[0]) if h &lt; 7: h += 12 return 60 * h + int(time[1]) """ A (messy) method used to display the section in a readable format :param start_num: minutes from Monday 00:00 until the class starts :param end_num: minutes from Monday 00:00 until the class ends :returns: A string representing the timespan """ @staticmethod def time_from_mins(start_num, end_num): # 1440 is the number of minutes in one day (60 * 24) # This is probably the least clean part of the code? day = Days(start_num // 1440).name start_hour = (start_num // 60) % 24 start_min = (start_num % 1440) - (start_hour * 60) start_min = '00' if start_min == 0 else start_min start_format = 'am' end_hour = (end_num // 60) % 24 end_min = (end_num % 1440) - (end_hour * 60) end_min = '00' if end_min == 0 else end_min end_format = 'am' if start_hour &gt; 12: start_hour -= 12 start_format = 'pm' time = f'{day} {start_hour}:{start_min}{start_format} =&gt; ' if end_hour &gt; 12: end_hour -= 12 end_format = 'pm' time += f'{end_hour}:{end_min}{end_format}' return time """ Checks to see if two time ranges overlap each other :param other: Another section object to compare :returns: boolean of whether the sections overlap """ def is_overlapping(self, other): for range_1 in self.days: for range_2 in other.days: if range_1['end_time'] &gt; range_2['start_time'] and range_2['end_time'] &gt; range_1['start_time']: return True return False def __repr__(self): strs = [] for day in self.days: strs.append(self.time_from_mins(day['start_time'], day['end_time'])) return '\n'.join(strs) class Scheduler: """ This class powers the actual search for the schedule It makes sure to fill all requirements and uses a search algorithm to find optimal schedules :param graph: Instance of a Graph object :param num_courses: A constraint on the number of courses that the schedule should have :param num_required: A number to keep track of the amount of required classes """ def __init__(self, graph, num_courses=5, num_required=1): self.graph = graph.graph self.paths = [] self.num_courses = num_courses self.num_required = num_required self.schedule_num = 1 """ A recursive search algorithm to create schedules Nodes are Section objects, with their neighbors being compatible courses :param u: The starting node in the search :param visited: A boolean list to keep track of visited nodes :param path: List passed through recursion to keep track of the path :returns: None (modifies object properties for use in __repr__ below) """ def search(self, u, visited, path): num_courses = self.num_courses visited[u] = True path.append(u) if len(self.paths) &gt; 1000: return if len(path) == num_courses and len([x for x in path if x.required is True]) == self.num_required: self.paths.append(list(path)) else: for section in self.graph[u]: if visited[section] == False and not any((x.is_overlapping(section) or (x.name == section.name)) for x in path): self.search(section, visited, path) path.pop() visited[u] = False def __repr__(self): out = '' for section in self.paths[self.schedule_num - 1]: out += f'{section.name}\n{"=" * len(section.name)}\n{repr(section)}\n\n' return out def main(): """ Setup all data exported into a .csv file, and prepare it for search """ data = {} # Parse csv file into raw data with open('classes.csv') as csvfile: csv_data = csv.reader(csvfile, dialect='excel') class_names = [] for j, row in enumerate(csv_data): for i, item in enumerate(row): if j == 0: if i % 3 == 0: # I believe there is a better way to read by columns name = item.strip('*') class_names.append(name) # Preferred classes are labelled with one asterisk, required with two preferred = item.count('*') == 1 required = item.count('*') == 2 data[name] = { 'sections_raw': [], 'sections': [], 'preferred': preferred, 'required': required } else: class_index = i // 3 data_ = data[class_names[class_index]] data_['sections_raw'].append(item) # Create Section objects which can be compared for overlaps for _class in data: # Personally class is more natural for me than course or lecture, but I could replace it sections_raw = data[_class]['sections_raw'] sections = [] cur_str = '' # Section strings are always in groups of three (class name, start time, end time) for i in range(0, len(sections_raw), 3): if sections_raw[i] != '': for x in range(3): cur_str += sections_raw[i + x] + ',' cur_str += '/' else: if cur_str != '': sections.append(Section(cur_str, _class, data[_class]['preferred'], data[_class]['required'])) cur_str = '' else: if cur_str != '': sections.append(Section(cur_str, _class, data[_class]['preferred'], data[_class]['required'])) cur_str = '' data[_class]['sections'] = sections # A friend asked me to prevent the scheduler from joining classes at specific times # I used my Section object as a constraint through the is_overlapping method constraint = Section('Monday,4:00,6:00/' + 'Tuesday,7:00,9:30/Tuesday,3:30,5:30/' + 'Wednesday,4:00,6:00/' + 'Thursday,7:00,9:30/Thursday,3:30,5:30/' + 'Friday,7:00,10:00') section_data = [] # Here we extract the compatible courses given the constraint for x in data.values(): for s in x['sections']: if not s.is_overlapping(constraint): section_data.append(s) graph = Graph(len(section_data)) for section in section_data: graph.graph[section] = [] start = None # Now we populate the graph, not allowing any incompatible edges for section in section_data: if start is None: start = section for vertex in graph.graph: if not section.is_overlapping(vertex) and section.name != vertex.name: graph.add_edge(vertex, section) scheduler = Scheduler(graph) visited = defaultdict(bool) scheduler.search(u=start, visited=visited, path=[]) # We use our search algorithm with courses as nodes # The scheduler doesn't actually weight the preferred classes, so we sort all our valid schedules using # the lambda function and reverse the order to show schedules with preferred classes first scheduler.paths = sorted(scheduler.paths, key= lambda path: (len([p for p in path if p.preferred])), reverse=True) return scheduler if __name__ == '__main__': # The scheduler object is created, and now we need a way for the user to view one of their schedules scheduler = main() n = int(input(f'There are {len(scheduler.paths)} found.\nWhich schedule would you like to see?\n#: ')) if not 1 &lt;= n &lt;= len(scheduler.paths): print(f'Enter a number between 1-{scheduler.paths}.') else: scheduler.schedule_num = n print(scheduler) </code></pre> <p>The .csv file is generated from a spreadsheet that uses the following layout (visualizing it will help with understanding how I parse it):</p> <p><a href="https://i.stack.imgur.com/orvEx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/orvEx.png" alt="Spreadsheet with class data"></a></p> <p><strong>classes.csv</strong></p> <pre class="lang-none prettyprint-override"><code>SPAN 201,Start,End,POLS 110*,Start,End,ENVS 130,Start,End,ACT 210,Start,End,FSEM**,Start,End,QTM 100*,Start,End Tuesday,9:00,9:50,Tuesday,1:00,2:15,Tuesday,11:30,12:45,Monday,1:00,2:15,Tuesday,10:00,11:15,Monday,4:00,5:15 Thursday,9:00,9:50,Thursday,1:00,2:15,Thursday,11:30,12:45,Wednesday,1:00,2:15,Thursday,10:00,11:15,Wednesday,4:00,5:15 Friday,9:00,9:50,,,,,,,,,,,,,Friday,9:00,9:50 ,,,,,,,,,Monday,2:30,3:45,Monday,1:00,2:15,,, Tuesday,10:00,10:50,,,,,,,Wednesday,2:30,3:45,Wednesday,1:00,2:15,Monday,4:00,5:15 Thursday,10:00,10:50,,,,,,,,,,,,,Wednesday,4:00,5:15 Friday,10:00,10:50,,,,,,,Monday,4:00,5:15,Monday,10:00,10:50,Friday,11:00,11:50 ,,,,,,,,,Wednesday,4:00,5:15,Wednesday,10:00,10:50,,, Tuesday,12:00,12:50,,,,,,,,,,Friday,10:00,10:50,Monday,4:00,5:15 Thursday,12:00,12:50,,,,,,,Tuesday,8:30,9:45,,,,Wednesday,4:00,5:15 Friday,12:00,12:50,,,,,,,Thursday,8:30,9:45,,,,Friday,1:00,1:50 ,,,,,,,,,,,,,,,,, Tuesday,1:00,1:50,,,,,,,Tuesday,10:00,11:15,,,,Tuesday,8:30,9:45 Thursday,1:00,1:50,,,,,,,Thursday,10:00,11:15,,,,Thursday,8:30,9:45 Friday,1:00,1:50,,,,,,,,,,,,,Friday,10:00,10:50 ,,,,,,,,,Tuesday,1:00,2:15,,,,,, Tuesday,2:00,2:50,,,,,,,Thursday,1:00,2:15,,,,Tuesday,8:30,9:45 Thursday,2:00,2:50,,,,,,,,,,,,,Thursday,8:30,9:45 Friday,2:00,2:50,,,,,,,,,,,,,Friday,12:00,12:50 ,,,,,,,,,,,,,,,,, Tuesday,3:00,3:50,,,,,,,,,,,,,Tuesday,8:30,9:45 Thursday,3:00,3:50,,,,,,,,,,,,,Thursday,8:30,9:45 Friday,3:00,3:50,,,,,,,,,,,,,Friday,2:00,2:50 ,,,,,,,,,,,,,,,,, Monday,10:00,10:50,,,,,,,,,,,,,Tuesday,10:00,11:15 Wednesday,10:00,10:50,,,,,,,,,,,,,Thursday,10:00,11:15 Friday,10:00,10:50,,,,,,,,,,,,,Friday,11:00,11:50 ,,,,,,,,,,,,,,,,, Monday,9:00,9:50,,,,,,,,,,,,,Tuesday,10:00,11:15 Wednesday,9:00,9:50,,,,,,,,,,,,,Thursday,10:00,11:15 Friday,9:00,9:50,,,,,,,,,,,,,Friday,1:00,1:50 ,,,,,,,,,,,,,,,,, Monday,2:00,2:50,,,,,,,,,,,,,Monday,2:30,3:45 Wednesday,2:00,2:50,,,,,,,,,,,,,Wednesday,2:30,3:45 Friday,2:00,2:50,,,,,,,,,,,,,Friday,10:00,10:50 ,,,,,,,,,,,,,,,,, Monday,3:00,3:50,,,,,,,,,,,,,Monday,2:30,3:45 Wednesday,3:00,3:50,,,,,,,,,,,,,Wednesday,2:30,3:45 Friday,3:00,3:50,,,,,,,,,,,,,Friday,2:00,2:50 ,,,,,,,,,,,,,,,,, Monday,4:00,4:50,,,,,,,,,,,,,,, Wednesday,4:00,4:50,,,,,,,,,,,,,,, Friday,4:00,4:50,,,,,,,,,,,,,,, </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-11T05:21:24.503", "Id": "420200", "Score": "0", "body": "Is there any reason for putting the docstrings above methods and not inside 'em? Looks really weird this way" } ]
[ { "body": "<p>one thing is sure, there's too much logic going on in your main. your main should be clean, i.e. presenting only functions or methods and minimal logic, as, at a glance we can figure out what's going on when the main function is called</p>\n\n<p>the blocks of code handle way too much related logic...
{ "AcceptedAnswerId": "201604", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T04:27:16.497", "Id": "201546", "Score": "6", "Tags": [ "python", "csv", "search" ], "Title": "Personal School Course Scheduler" }
201546
<p>I am trying to continuously get the position of a div on screen and update the new position each time a "click" event listener is clicked. At the moment my code works but feels redundant and could be simplified into a single function to move the div around the screen. </p> <p>Any suggestions on how to approach this issue?</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-js lang-js prettyprint-override"><code>// Init .innerHTML for circle let startText = document.querySelector('.circle').innerHTML = "click"; let circle = document.querySelector('.circle'); var x = 0; let titleContainer = document.querySelector('.circle'); let progressContainer = document.querySelector('.progress-container'); let avatar = document.querySelector('.avatar'); let avatarSize = document.querySelector('.avatar').clientWidth; let totalLevels = 5; // Listen for events circle.addEventListener('click', mainClickMaze); // Start position of smaller circle on progressContainer function moveAvatarForward() { let progressContainerWidth = progressContainer.clientWidth; let sum = Math.round(progressContainerWidth / totalLevels); console.log(sum); requestAnimationFrame(frame); let pos = 0; function frame() { if (pos != sum) { pos++; avatar.style.marginLeft = pos + "px"; requestAnimationFrame(frame); } } } // Move the avatar based on its previous location function locationOfAvatar() { let pos = avatar.style.marginLeft; // Remove "px" from pos pos = pos.substring(0, pos.length - 2); pos = parseInt(pos); let progressContainerWidth = progressContainer.clientWidth; let sum = Math.round(progressContainerWidth / totalLevels); let movePos = pos + sum; console.log(movePos); requestAnimationFrame(frame); function frame() { if (pos != movePos) { pos++; avatar.style.marginLeft = pos + "px"; requestAnimationFrame(frame); } } } // Avatar gets moved to the end of the continer function endOfAvatar() { let pos = avatar.style.marginLeft; pos = pos.substring(0, pos.length - 2); pos = parseInt(pos); // Get size of small circle in progressContainer so that avatarSize does not exceed the bounds of progressContainer let avatarSize = document.querySelector('.avatar').clientWidth; let progressContainerWidth = progressContainer.clientWidth; let sum = progressContainerWidth - avatarSize; console.log(sum); requestAnimationFrame(frame); function frame() { if (pos != sum) { pos++; avatar.style.marginLeft = pos + "px"; requestAnimationFrame(frame); } } } let click = 0; function mainClickMaze(event) { titleContainer.innerHTML = ++click; console.log('click:', click) if (click == 1) { progressContainer.style.display = 'flex'; } else if (click == 2) { moveAvatarForward(); } else if (click == 3) { locationOfAvatar(); } else if (click == 4) { locationOfAvatar(); } else if (click == totalLevels) { // Remove event listener circle.removeEventListener('click', mainClickMaze); titleContainer.innerHTML = 'Disabled'; endOfAvatar(); } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { padding: 0; margin: 0; } .container { display: flex; flex-direction: column; align-items: center; justify-content: center; margin-top: 33.3vh; margin-bottom: 33.3vh; } .circle { display: flex; width: 20vw; height: 20vw; background-color: red; border-radius: 50%; color: white; align-items: center; justify-content: center; text-align: center; font-size: 24px; cursor: pointer; } .move-container { display: flex; margin-top: 5vh; font-size: 24px; display: none; } .move-back { display: flex; align-items: center; justify-content: center; margin-right: 10vw; cursor: pointer; width: 10vw; padding: 10px; background-color: grey; border-radius: 25px; color: white; } .move-forward { display: flex; align-items: center; justify-content: center; margin-left: 10vw; cursor: pointer; width: 10vw; padding: 10px; background-color: grey; border-radius: 25px; color: white; } .progress-container { position: fixed; display: none; align-items: center; width: 90%; height: 2px; background-color: red; bottom: 5vh; } .avatar { width: 2vw; height: 2vw; background-color: blue; border-radius: 50%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="circle"&gt;&lt;/div&gt; &lt;div class="move-container"&gt; &lt;div class="move-back user-click"&gt;Back&lt;/div&gt; &lt;div class="move-forward user-click"&gt;Forward&lt;/div&gt; &lt;/div&gt; &lt;div class="progress-container"&gt; &lt;div class="avatar"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Lastly here is a jsfiddle for easier reference: <a href="http://jsfiddle.net/wh4nac91/2/" rel="nofollow noreferrer">Update position of div</a></p>
[]
[ { "body": "<h2>Simplifying the functions into one</h2>\n\n<p>Yes the three functions can be combined into one. To start, the <code>pos</code> variable can be simplified to default to 0 when no <em>left</em> style has been applied using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
{ "AcceptedAnswerId": "201819", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T05:39:01.917", "Id": "201548", "Score": "1", "Tags": [ "javascript", "html", "css", "animation", "dom" ], "Title": "Continuously update position of div with click event" }
201548
<p>I want to implement a <em>cumulative all</em> through R's C interface. I was able to hack something together that produces the correct results, but I have little idea what idiomatic C should look like. The code should be easy to understand, even if you don't know about R.</p> <h2>Description</h2> <p>The <em>cumulative all</em> takes a <code>LGLSXP</code> (logical S-expression) input. The function should output a <code>LGLSXP</code> of the same length as the input, where each element represents whether all values up to this point were <code>true</code>. </p> <p>The three valued logic works like this: <code>(true &amp; false) -&gt; false</code>, <code>(true &amp; na) -&gt; na</code>, <code>(false &amp; na) -&gt; false</code></p> <h3>LGLSXP</h3> <p>A <code>LGLSXP</code> is a pointer to a struct that contains an <code>int</code> array that represents 3 valued logic with <code>0</code> as <code>false</code>, <code>INT_MIN</code> as <code>NA</code> and <code>1</code> as <code>true</code>. This array can be accessed with <code>LOGICAL()</code>. You can read about SEXPs <a href="https://cran.r-project.org/doc/manuals/r-release/R-ints.html#SEXPs" rel="nofollow noreferrer">here</a>.</p> <h1>Code</h1> <pre><code>#include &lt;R.h&gt; #include &lt;Rinternals.h&gt; SEXP cumall_impl(SEXP x) { SEXP res = PROTECT(allocVector(LGLSXP, XLENGTH(x))); R_xlen_t n = XLENGTH(x); if (n == 0){ UNPROTECT(1); return(res); } else { memset(LOGICAL(res), 0, n * sizeof(int)); } int *p_x = LOGICAL(x); int *p_res = LOGICAL(res); p_res[0] = p_x[0]; for (R_xlen_t i = 1; i &lt; n; i++) { if (p_x[i] == TRUE) p_res[i] = p_res[i - 1]; else if (p_x[i] == NA_LOGICAL) p_res[i] = NA_LOGICAL; else break; } UNPROTECT(1); return res; } </code></pre> <h2>Remarks</h2> <ul> <li><code>PROTECT()</code> and <code>UNPROTECT()</code> are necessary to prevent R's garbage collector from interfering</li> <li><code>LOGICAL()</code> accesses the underlying array of a <code>LGLSXP</code></li> <li><code>TRUE</code>, <code>NA_LOGICAL</code> etc are provided by the headers.</li> </ul> <h2>Headers</h2> <ul> <li>The most important definitions are in <a href="https://svn.r-project.org/R/trunk/src/include/Rinternals.h" rel="nofollow noreferrer">Rinternals.h</a> and <a href="https://svn.r-project.org/R/trunk/src/include/R.h" rel="nofollow noreferrer">R.h</a>. </li> <li>The <code>NA_LOGICAL</code> is defined in <a href="https://svn.r-project.org/R/trunk/src/include/R_ext/Arith.h" rel="nofollow noreferrer">Arith.h</a> and <a href="https://svn.r-project.org/R/trunk/src/main/arithmetic.c" rel="nofollow noreferrer">arithmetic.c</a></li> <li>I am not sure where/how <code>TRUE</code> and <code>FALSE</code> are really defined. Likely sources are <a href="https://svn.r-project.org/R/trunk/src/include/R_ext/Boolean.h" rel="nofollow noreferrer">Boolean.h</a> and <a href="https://svn.r-project.org/R/trunk/src/include/Rdefines.h" rel="nofollow noreferrer">Rdefines.h</a></li> </ul> <p>I am thankful for all suggestions, be it coding style, variable naming or critique to how I formulated my question</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-15T01:29:07.927", "Id": "388438", "Score": "0", "body": "\"everything else as true\" and `if (p_x[i] == TRUE)` seems wrong. I'd expect all values that are neither `NA_LOGICAL` nor `FALSE`, not just the one `TRUE`, to cause that `if()`...
[ { "body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Use variables effectively</h2>\n\n<p>The code begins with this:</p>\n\n<pre><code>SEXP cumall_impl(SEXP x) {\n SEXP res = PROTECT(allocVector(LGLSXP, XLENGTH(x)));\n R_xlen_t n = XLENGTH(x);\n</code></pre>\n\n<p>However, there...
{ "AcceptedAnswerId": "201579", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T05:53:26.597", "Id": "201551", "Score": "5", "Tags": [ "c", "r", "native-code" ], "Title": "Plain C implementation of 'Cumulative All' operation for R" }
201551
<p>For answering this question of stackoverflow I have written the code <a href="https://stackoverflow.com/questions/12033188/how-would-you-implement-your-own-reader-writer-lock-in-c11">https://stackoverflow.com/questions/12033188/how-would-you-implement-your-own-reader-writer-lock-in-c11</a></p> <p>Can someone review it - so that I can understand the possible problems in the code.</p> <pre><code>#include &lt;condition_variable&gt; #include &lt;iostream&gt; #include &lt;shared_mutex&gt; #include &lt;thread&gt; #include &lt;unistd.h&gt; #define NR_THREADS 10 #include &lt;mutex&gt; class MySharedLock { public: void read_lock() { std::unique_lock&lt;std::mutex&gt; lk(rw_mutex); std::cout &lt;&lt; "\nReader Lock Writers are " &lt;&lt; writers &lt;&lt; std::flush; if (writers != 0) { rw_cv.wait(lk, [this]() { return (this-&gt;writers == 0); }); } readers++; lk.unlock(); } void write_lock() { std::unique_lock&lt;std::mutex&gt; lk(rw_mutex); std::cout &lt;&lt; "\nWriter Lock Writers are " &lt;&lt; writers &lt;&lt; " Readers are " &lt;&lt; readers &lt;&lt; std::flush; if (readers == 0 &amp;&amp; writers == 0) { std::cout &lt;&lt; "\nWriter Lock Writers are " &lt;&lt; writers &lt;&lt; std::flush; } else { rw_cv.wait( lk, [this]() { return (this-&gt;writers == 0 &amp;&amp; this-&gt;readers == 0); }); } writers++; lk.unlock(); } void write_unlock() { std::lock_guard&lt;std::mutex&gt; lk(rw_mutex); writers--; rw_cv.notify_all(); } void read_unlock() { std::lock_guard&lt;std::mutex&gt; lk(rw_mutex); if (readers == 1) { // I am the last one. rw_cv.notify_all(); } readers--; } explicit MySharedLock() {} private: std::mutex rw_mutex; std::condition_variable rw_cv; uintmax_t readers = {0}, writers = {0}; }; </code></pre>
[]
[ { "body": "<p>First, I suppose it would be cheating to just use a <a href=\"https://en.cppreference.com/w/cpp/thread/shared_mutex\" rel=\"noreferrer\"><code>std::shared_mutex</code></a>, right? :)</p>\n\n<p>Second, it seems a little weird to declare <code>uintmax_t writers</code> for a variable that can only ev...
{ "AcceptedAnswerId": "201562", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T07:26:10.920", "Id": "201556", "Score": "4", "Tags": [ "c++", "c++11", "thread-safety", "locking" ], "Title": "Simple rwlock implementation in c++11" }
201556
<p>I have been really into chess lately so I decided to program the game in PHP for practice. I want to get more comfortable with classes.</p> <p>Part 1 of the project is complete. I have a working ASCII board that displays the pieces, and I have an import tool that can import a board. (In chess, they use <a href="https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation" rel="nofollow noreferrer">FEN Notation</a> for importing boards)</p> <p>I decided to create 2 classes: ChessGame and ChessPiece. I experimented with making classes like Bishop, Knight, etc. that extended ChessPiece, but it ended up being messy so I deleted them.</p> <p>I'm looking for feedback on how I structured the classes, and feedback on how I should structure classes that I add later. For example, I am going to make the game playable, so I need to program in all the piece movement rules somewhere. Should that get its own class? Should I program that all into ChessGame? Can I program the movement rules into a class for each piece instead, without making my code hard to read and disorganized?</p> <p>Also, feel free to suggest any other tips you might have to make my code better organized and more readable.</p> <p>If this Code Review is well received, I will post additional code later on for gameplay/piece movement, list of legal moves, GUI improvements, and eventually porting the game to C# and JavaScript so I can practice coding in those languages.</p> <h2>Website</h2> <p><a href="http://admiraladama.dreamhosters.com/PHPChess" rel="nofollow noreferrer">http://admiraladama.dreamhosters.com/PHPChess</a></p> <h2>Screenshot</h2> <p><a href="https://i.stack.imgur.com/rkUSR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rkUSR.png" alt="AdmiralAdama chess screenshot"></a></p> <h2>index.php</h2> <pre><code>&lt;?php error_reporting(-1); ini_set('display_errors', 'On'); require_once('classes.php'); $game = new ChessGame(); if ( isset($_POST['fen']) &amp;&amp; isset($_POST['import_fen']) ) { $game-&gt;set_fen($_POST['fen']); } $fen = $game-&gt;get_fen(); $ascii_board = $game-&gt;get_ascii_board(); ?&gt;&lt;!DOCTYPE html&gt; &lt;html lang="en-us"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt; AdmiralAdama Chess &lt;/title&gt; &lt;style&gt; input[name="fen"] { width:56em; } textarea[name="ascii_board"] { font-family:"Arial Unicode MS", "Lucida Console", Courier, monospace; font-size:26pt; width:325px; height:435px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; AdmiralAdama Chess &lt;/h1&gt; &lt;form method="post"&gt; &lt;p&gt; FEN:&lt;br /&gt; &lt;input type="text" name="fen" value="&lt;?php echo $fen; ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="submit" name="import_fen" value="Import FEN" /&gt; &lt;/p&gt; &lt;p&gt; ASCII board:&lt;br /&gt; &lt;textarea name="ascii_board" rows="9"&gt;&lt;?php echo $ascii_board; ?&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>classes.php</h2> <pre><code>&lt;?php function number_to_file($number) { $dictionary = array( 1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd', 5 =&gt; 'e', 6 =&gt; 'f', 7 =&gt; 'g', 8 =&gt; 'h' ); return $dictionary[$number]; } function invert_rank_or_file_number($number) { $dictionary = array( 1 =&gt; 8, 2 =&gt; 7, 3 =&gt; 6, 4 =&gt; 5, 5 =&gt; 4, 6 =&gt; 3, 7 =&gt; 2, 8 =&gt; 1 ); return $dictionary[$number]; } class ChessGame { const DEFAULT_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'; const VALID_COLORS = array('white', 'black'); const VALID_SQUARES = array( 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8' ); const UNICODE_EMPTY_SQUARE = '&amp;#9633;'; // $board[y][x], or in this case, $board[rank][file] var $board = array(); var $color_to_move; var $white_can_castle_kingside; var $white_can_castle_queenside; var $black_can_castle_kingside; var $black_can_castle_queenside; var $en_passant_target_square = NULL; var $halfmove_clock; // Not sure why this is in a FEN. I googled it and the answer is... // "Full move counter is common in chess books where the games start from a diagram." var $fullmove_number; function __construct() { $this-&gt;set_fen(self::DEFAULT_FEN); } function set_fen($fen) { $fen = trim($fen); // Basic format check. This won't catch everything, but it will catch a lot of stuff. // TODO: Make this stricter so that it catches everything. $valid_fen = preg_match('/^([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8}) ([bw]{1}) ([-KQkq]{1,4}) ([a-h1-8-]{1,2}) (\d{1,2}) (\d{1,4})$/', $fen, $matches); if ( ! $valid_fen ) { throw new Exception('ChessBoard Class - Invalid FEN'); } // ******* CREATE PIECES AND ASSIGN THEM TO SQUARES ******* // Set all board squares to NULL. That way we don't have to blank them in the loop below. We can just overwrite the NULL with a piece. for ( $i = 1; $i &lt;= 8; $i++ ) { for ( $j = 1; $j &lt;= 8; $j++ ) { $this-&gt;board[$i][$j] = NULL; } } // Create $rank variables with strings that look like this // rnbqkbnr // pppppppp // 8 // PPPPPPPP // RNBQKBNR // 2p5 // The numbers are the # of blank squares from left to right $rank = array(); for ( $i = 1; $i &lt;= 8; $i++ ) { // Match string = 1, but rank = 8. Fix it here to avoid headaches. $rank = invert_rank_or_file_number($i); $rank_string[$rank] = $matches[$i]; } // Process $rank variable strings, convert to pieces and add them to $this-&gt;board[][] foreach ( $rank_string as $rank =&gt; $string ) { $file = 1; for ( $i = 1; $i &lt;= strlen($string); $i++ ) { $char = substr($string, $i - 1, 1); // Don't use is_int here. $char is a string. Use is_numeric instead. if ( is_numeric($char) ) { $file = $file + $char; } else { $square = number_to_file($file) . $rank; if ( ctype_upper($char) ) { $color = 'white'; } else { $color = 'black'; } $dictionary = array( 'p' =&gt; 'pawn', 'n' =&gt; 'knight', 'b' =&gt; 'bishop', 'r' =&gt; 'rook', 'q' =&gt; 'queen', 'k' =&gt; 'king' ); $type = $dictionary[strtolower($char)]; $this-&gt;board[$rank][$file] = new ChessPiece($color, $square, $type); $file++; } } } // ******* SET COLOR TO MOVE ******* if ( $matches[9] == 'w' ) { $this-&gt;color_to_move = 'white'; } elseif ( $matches[9] == 'b' ) { $this-&gt;color_to_move = 'black'; } else { throw new Exception('ChessBoard Class - Invalid FEN - Invalid Color To Move'); } // Set all castling to false. Only set to true if letter is present in FEN. Prevents bugs. $this-&gt;white_can_castle_kingside = FALSE; $this-&gt;white_can_castle_queenside = FALSE; $this-&gt;black_can_castle_kingside = FALSE; $this-&gt;black_can_castle_queenside = FALSE; // ******* SET CASTLING POSSIBILITIES ******* // strpos is case sensitive, so that's good if ( strpos($matches[10], 'K') !== FALSE ) { $this-&gt;white_can_castle_kingside = TRUE; } if ( strpos($matches[10], 'Q') !== FALSE ) { $this-&gt;white_can_castle_queenside = TRUE; } if ( strpos($matches[10], 'k') !== FALSE ) { $this-&gt;black_can_castle_kingside = TRUE; } if ( strpos($matches[10], 'q') !== FALSE ) { $this-&gt;black_can_castle_queenside = TRUE; } // ******* SET EN PASSANT TARGET SQUARE ******* if ( $matches[11] == '-' ) { $this-&gt;en_passant_target_square = FALSE; } elseif ( in_array($matches[11], self::VALID_SQUARES) ) { $this-&gt;en_passant_target_square = $matches[11]; } else { throw new Exception('ChessPiece Class - Invalid FEN - Invalid En Passant Target Square'); } // ******* SET HALFMOVE CLOCK ******* $this-&gt;halfmove_clock = $matches[12]; // ******* SET FULLMOVE NUMBER ******* $this-&gt;fullmove_number = $matches[13]; } function get_fen() { $string = ''; // A chessboard looks like this // a8 b8 c8 d8 // a7 b7 c7 d7 // etc. // But we want to print them starting with row 8 first. // So we need to adjust the loops a bit. for ( $rank = 8; $rank &gt;= 1; $rank-- ) { $empty_squares = 0; for ( $file = 1; $file &lt;= 8; $file++ ) { $square = $this-&gt;board[$rank][$file]; if ( ! $square ) { $empty_squares++; } else { if ( $empty_squares ) { $string .= $empty_squares; $empty_squares = 0; } $string .= $this-&gt;board[$rank][$file]-&gt;get_fen_symbol(); } } if ( $empty_squares ) { $string .= $empty_squares; } if ( $rank != 1 ) { $string .= "/"; } } if ( $this-&gt;color_to_move == 'white' ) { $string .= " w "; } elseif ( $this-&gt;color_to_move == 'black' ) { $string .= " b "; } if ( $this-&gt;white_can_castle_kingside ) { $string .= "K"; } if ( $this-&gt;white_can_castle_queenside ) { $string .= "Q"; } if ( $this-&gt;black_can_castle_kingside ) { $string .= "k"; } if ( $this-&gt;black_can_castle_queenside ) { $string .= "q"; } if ( ! $this-&gt;white_can_castle_kingside &amp;&amp; ! $this-&gt;white_can_castle_queenside &amp;&amp; ! $this-&gt;black_can_castle_kingside &amp;&amp; ! $this-&gt;black_can_castle_queenside ) { $string .= "-"; } if ( $this-&gt;en_passant_target_square ) { $string .= " " . $this-&gt;en_passant_target_square; } else { $string .= " -"; } $string .= " " . $this-&gt;halfmove_clock . ' ' . $this-&gt;fullmove_number; return $string; } function get_ascii_board() { $string = ''; if ( $this-&gt;color_to_move == 'white' ) { $string .= "White To Move"; } elseif ( $this-&gt;color_to_move == 'black' ) { $string .= "Black To Move"; } // A chessboard looks like this // a8 b8 c8 d8 // a7 b7 c7 d7 // etc. // But we want to print them starting with row 8 first. // So we need to adjust the loops a bit. for ( $rank = 8; $rank &gt;= 1; $rank-- ) { $string .= "\r\n"; for ( $file = 1; $file &lt;= 8; $file++ ) { $square = $this-&gt;board[$rank][$file]; if ( ! $square ) { $string .= self::UNICODE_EMPTY_SQUARE; } else { $string .= $this-&gt;board[$rank][$file]-&gt;get_unicode_symbol(); } } } return $string; } } class ChessPiece { var $point_value; var $color; var $type; var $square; const VALID_COLORS = array('white', 'black'); const VALID_SQUARES = array( 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8' ); const VALID_TYPES = array('pawn', 'knight', 'bishop', 'rook', 'queen', 'king'); const UNICODE_CHESS_PIECES = array( 'white_king' =&gt; '&amp;#9812;', 'white_queen' =&gt; '&amp;#9813;', 'white_rook' =&gt; '&amp;#9814;', 'white_bishop' =&gt; '&amp;#9815;', 'white_knight' =&gt; '&amp;#9816;', 'white_pawn' =&gt; '&amp;#9817;', 'black_king' =&gt; '&amp;#9818;', 'black_queen' =&gt; '&amp;#9819;', 'black_rook' =&gt; '&amp;#9820;', 'black_bishop' =&gt; '&amp;#9821;', 'black_knight' =&gt; '&amp;#9822;', 'black_pawn' =&gt; '&amp;#9823;' ); const FEN_CHESS_PIECES = array( 'white_king' =&gt; 'K', 'white_queen' =&gt; 'Q', 'white_rook' =&gt; 'R', 'white_bishop' =&gt; 'B', 'white_knight' =&gt; 'N', 'white_pawn' =&gt; 'P', 'black_king' =&gt; 'k', 'black_queen' =&gt; 'q', 'black_rook' =&gt; 'r', 'black_bishop' =&gt; 'b', 'black_knight' =&gt; 'n', 'black_pawn' =&gt; 'p' ); function __construct($color, $square, $type) { if ( in_array($color, self::VALID_COLORS) ) { $this-&gt;color = $color; } else { throw new Exception('ChessPiece Class - Invalid Color'); } if ( in_array($square, self::VALID_SQUARES) ) { $this-&gt;square = $square; } else { throw new Exception('ChessPiece Class - Invalid Square'); } if ( in_array($type, self::VALID_TYPES) ) { $this-&gt;type = $type; } else { throw new Exception('ChessPiece Class - Invalid Type'); } } function print_basic_info() { $basic_info = ''; $basic_info .= 'Point Value: ' . $this-&gt;point_value . "&lt;br /&gt;"; $basic_info .= 'Color: ' . $this-&gt;color . "&lt;br /&gt;"; $basic_info .= 'Type: ' . $this-&gt;type . "&lt;br /&gt;"; $basic_info .= 'Square: ' . $this-&gt;square . "&lt;br /&gt;"; echo($basic_info); } function get_unicode_symbol() { $dictionary_key = $this-&gt;color . '_' . $this-&gt;type; return self::UNICODE_CHESS_PIECES[$dictionary_key]; } function get_fen_symbol() { $dictionary_key = $this-&gt;color . '_' . $this-&gt;type; return self::FEN_CHESS_PIECES[$dictionary_key]; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T07:34:03.873", "Id": "201557", "Score": "1", "Tags": [ "php", "chess" ], "Title": "PHP Chess Part 1 - ASCII Board & Import Position" }
201557
<p>I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by adding numbers from a certain set, where any number in the set can be used <em>N</em> times.</p> <p>It is like if I have the number 10 and I want to find out how many ways <strong>10</strong> can be generated using [<strong>2,3,5</strong>]</p> <ol> <li>2+2+2+2+2 = 10 </li> <li>5+3+2 = 10</li> <li>2+2+3+3 = 10 </li> <li>5+5 = 10</li> </ol> <p>to solve it I made this function:</p> <pre><code>function getNumberOfWays($money, $coins) { static $level = 0; if (!$level) { sort($coins); } if ($level &amp;&amp; !$money) { return 1; } elseif (!$level &amp;&amp; !$money) { return 0; } if ($money === 1 &amp;&amp; array_search(1, $coins) !== false) { return 1; } elseif ($money === 1 &amp;&amp; array_search(1, $coins) === false) { return 0; } $r = 0; $tmpCoins = $coins; foreach ($coins as $index =&gt; $coin) { if (!$coin || $coin &gt; $money) { continue; } $tmpCoins[$index] = 0; $tmpMoney = $money; do { $tmpMoney -= $coin; if ($tmpMoney &gt;= 0) { $level++; $r += getNumberOfWays($tmpMoney, $tmpCoins); $level--; } elseif (!$tmpMoney) { $r++; } } while ($tmpMoney &gt;= 0); } return $r; } </code></pre> <p>This function works correctly: it returns the right value.</p> <p>Can I improve it in any way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T11:10:47.923", "Id": "388197", "Score": "2", "body": "`10` is also equal to `2 * 5`. But it seems like you only consider addition. Can you confirm?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T12:1...
[ { "body": "<p>I'm assuming in this answer that you have infinite quantities of the designated numbers at your disposal, since that appears to be the way your code works. With that condition, this problem is the <strong><a href=\"https://projecteuler.net/problem=31\" rel=\"nofollow noreferrer\">coin sums problem...
{ "AcceptedAnswerId": "201701", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T10:58:20.963", "Id": "201564", "Score": "1", "Tags": [ "php", "recursion" ], "Title": "Recursive function to find the number of ways a number can be generated out of a set of numbers" }
201564
<p>following the answer I got from t3chb0t last time </p> <p><a href="https://codereview.stackexchange.com/questions/177167/news-reading-application-using-the-observer-pattern">News-reading application using the Observer pattern</a></p> <p>and also following the example here<br> <a href="https://msdn.microsoft.com/en-us/library/dd990377(v=vs.110).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/dd990377(v=vs.110).aspx</a></p> <p>I implemented a the answer to the following question <br></p> <blockquote> <p>Design a kind of kindle fire application where we can subscribe NewsChannel channel and read the NewsChannel from all publishers as a digital format.</p> </blockquote> <p>Please comment on the implementation of the design pattern observer and the code style. you can ignore the unit test it is just for understanding how to use the code. Thanks </p> <pre><code>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DesignPatternsQuestions { /// &lt;summary&gt; /// Design a kind of kindle fire application where we can subscribe /// NewsChannel channel and read the NewsChannel from all publishers as a digital format. /// &lt;/summary&gt; [TestClass] public class ObserverPatternTest { [TestMethod] public void ObeserverPatternTest() { NewsChannel newsChannel1 = new NewsChannel(); NewsChannel newsChannel2 = new NewsChannel(); KindleApp kindle = new KindleApp(); kindle.Subscribe(newsChannel1); kindle.Subscribe(newsChannel2); newsChannel1.SendMessage(new Image(1920, 1080)); newsChannel2.SendMessage(new TextMessage("News Channel 2")); newsChannel1.EndMessages(); newsChannel1.SendMessage(new TextMessage("News Channel 1 done")); } } public interface IMessage { string Print(); } public class TextMessage : IMessage { private readonly string _text; public TextMessage(string text) { _text = text; } public string Print() { return _text; } } public class Image : IMessage { private readonly uint _width; private readonly uint _height; public Image(uint width, uint height ) { _width = width; _height = height; } public string Print() { return string.Format("Image width:{0} height {1}", _width, _height); } } /// &lt;summary&gt; /// this class handles all of the different observers, observers listen to IObservables.. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; public class NewsChannel : IObservable&lt;IMessage&gt; { private readonly List&lt;IObserver&lt;IMessage&gt;&gt; _observers; public NewsChannel() { _observers = new List&lt;IObserver&lt;IMessage&gt;&gt;(); } public IDisposable Subscribe(IObserver&lt;IMessage&gt; observer) { if (!_observers.Contains(observer)) { _observers.Add(observer); } return new Unsubscriber&lt;IMessage&gt;(_observers, observer); } /// &lt;summary&gt; /// send a message of certain type to all of the observers /// &lt;/summary&gt; /// &lt;param name="message"&gt;&lt;/param&gt; public void SendMessage(IMessage message) { foreach (var observer in _observers) { if (message != null) { observer.OnNext(message); } else { observer.OnError(new ArgumentNullException()); } } } public void EndMessages() { foreach (var observer in _observers) { observer.OnCompleted(); } _observers.Clear(); } } /// &lt;summary&gt; /// this also can be a private class inside the NewsChannel class /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; public class Unsubscriber&lt;T&gt; : IDisposable { private List&lt;IObserver&lt;T&gt;&gt; _observers; private IObserver&lt;T&gt; _observer; public Unsubscriber(List&lt;IObserver&lt;T&gt;&gt; observers, IObserver&lt;T&gt; observer) { this._observers = observers; this._observer = observer; } public void Dispose() { if (_observer != null &amp;&amp; _observers.Contains(_observer)) { _observers.Remove(_observer); } } } public class KindleApp : IObserver&lt;IMessage&gt; { private IDisposable _unsubscriber; public virtual void Subscribe(IObservable&lt;IMessage&gt; provider) { if (provider != null) { _unsubscriber = provider.Subscribe(this); } } public virtual void Unsubscribe() { _unsubscriber.Dispose(); } //print the message public void OnNext(IMessage value) { Console.WriteLine(value.Print()); } public void OnError(Exception error) { Console.WriteLine("can't handle error"); } public void OnCompleted() { Console.WriteLine("on complete"); this.Unsubscribe(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T12:59:07.690", "Id": "388208", "Score": "0", "body": "For sure spacing between methods and I would also avoid using magic numbers. You could put 1920 and 1080 at the top of the class so we know what they represent at a business leve...
[ { "body": "<p>You were interested in a review in both the pattern as code style.</p>\n\n<p><sub>Note: I'm addressing subscribers also as listeners and observers in this review.</sub></p>\n\n<hr>\n\n<h2>Code Style</h2>\n\n<ul>\n<li>Prefer <code>var</code> when the type of the instance is known: <code>NewsChannel...
{ "AcceptedAnswerId": "226693", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T11:39:46.000", "Id": "201565", "Score": "5", "Tags": [ "c#", "design-patterns", "interview-questions", "observer-pattern" ], "Title": "News reading application version 2" }
201565
<p>So basically I developed this form with HTML, JS and Bootstrap to add contacts to a backend. It simply shows a form so a user can input some data and it's submitted to an API.</p> <p>The thing is it doesn't look very neat to me... but then at the same time, I don't really know how to start tackling the refactor, so any tips and reviews are super welcome! :)</p> <p>The functionality is very straightforward, so I don't think it needs much introduction. And it should be copy-paste-it-works.</p> <pre><code>&lt;html&gt; &lt;meta charset="UTF-8"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="error-message" style="position:fixed; z-index:9999; width: 100%; visibility: hidden;"&gt; &lt;div style="padding: 5px;"&gt; &lt;div id="error-alert" class="alert alert-danger"&gt; &lt;button type="button" class="close" data-dismiss="alert" onclick="hideAlert('error-alert');"&gt;&amp;times;&lt;/button&gt; Error: Could not add contact to the addressbook. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="success-message" style="position:fixed; z-index:9999; width: 100%; visibility: hidden;"&gt; &lt;div style="padding: 5px;"&gt; &lt;div id="success-alert" class="alert alert-success"&gt; &lt;button type="button" class="close" data-dismiss="success-alert" onclick="hideAlert('success-alert');"&gt;&amp;times;&lt;/button&gt; Contact created successfully! &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="jumbotron"&gt; &lt;h1 class="display-4"&gt;Contacts.To&lt;/h1&gt; &lt;p class="lead"&gt;A simple addressbook without butterflies or clouds.&lt;/p&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-4 mx-auto"&gt; &lt;div class="card"&gt; &lt;img class="card-img-top"&gt; &lt;div class="card-body"&gt; &lt;h5 class="card-title"&gt;Add a contact&lt;/h5&gt; &lt;form onsubmit="return createContact();"&gt; &lt;div class="form-group"&gt; &lt;label for="username"&gt;Username:&lt;/label&gt; &lt;input type="username" class="form-control" id="username"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;Name:&lt;/label&gt; &lt;input type="name" class="form-control" id="name"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;Email:&lt;/label&gt; &lt;input type="email" class="form-control" id="email"&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="navbar navbar-fixed-bottom"&gt;Made at night :-) &lt;/div&gt; &lt;/body&gt; &lt;script&gt; function createContact() { var opts = { method: 'POST', body: JSON.stringify(getContactDTO()), headers: { "Content-Type": "application/json" } }; fetch('/api/contacts', opts) .then(function (response) { showAlert('success-alert'); }) .catch(function () { showAlert('error-alert'); }); return false; } function getContactDTO() { return { username: document.getElementById("username").value, name: document.getElementById("name").value, email: document.getElementById("email").value }; } function hideAlert(id) { document.getElementById(id).style.visibility = 'hidden'; } function showAlert(id) { document.getElementById(id).style.visibility = 'visible'; } &lt;/script&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T14:35:03.820", "Id": "388218", "Score": "0", "body": "Put the Meta tag in the head. It is invalid as per HTML4.01. META tags are only allowed within HEAD (just like, say, TITLE). Browser's will likely never reflect that, but it's te...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T12:52:13.637", "Id": "201570", "Score": "1", "Tags": [ "javascript", "html", "twitter-bootstrap" ], "Title": "Small \"Add Contact\" HTML & Vainilla JS form" }
201570
<p>I have a number of these components, but will show just two as an example. They're very similar, but the differences are enough to where splitting them out felt needed. What I really need is some help. Is this the right approach, or would I be better served somehow combining them to reduce duplicate code? I have similar components for toggles like radios and checkboxes, as well as textarea that handle both plain text and markdown fields, etc.</p> <p>Other feedback would also be appreciated :)</p> <h3>Textfield wrapper.</h3> <pre><code>'use strict' import React, { Component } from 'react' import { FieldText, FieldLabel, FieldDescription, FieldErrorMessage } from './' import PropTypes from 'prop-types' class FieldTextWrap extends Component { static propTypes = {} constructor(props) { super(props) this.state = { value: '', isValid: true } } _handleChange = value =&gt; { const { formatter } = this.props const formattedValue = !!formatter ? formatter(value) : value this.setState({ value: formattedValue }) } componentDidMount() { const { required, type, value, initialValue, dispatch, handleBlur, isForm, formId, id } = this.props !!initialValue &amp;&amp; this.setState({ value: initialValue }) !initialValue &amp;&amp; !!value &amp;&amp; this.setState({ value }) const fieldData = { id, value, type, required, formId, valid: true } return isForm &amp;&amp; dispatch(handleBlur(null, dispatch, fieldData)) } componentDidUpdate(prevProps, prevState) { const { validationRule, required } = this.props const { value } = this.state const didUpdate = prevState.value !== value // validate and update const isValid = !!validationRule ? validationRule.func({ field: { required, value }, tests: validationRule.tests, options: validationRule.options }) : true didUpdate &amp;&amp; this.setState({ isValid }) } componentWillUnmount() { const { removeFormField, id, isForm } = this.props isForm &amp;&amp; removeFormField(id) } render() { const { className = '', description, fieldGroup = '', formName, formId, hideDescription, hideLabel, id, label, required, requireDefault, type, validationText: message = '' } = this.props const classes = `form-item ${formName}__${id} ${fieldGroup} ${type}-field ${className} ${type} text-type` const value = this.state.value const isValid = this.state.isValid const fieldData = { id, value, type, required, formId, valid: isValid, message } return ( &lt;div className={classes}&gt; &lt;FieldLabel name={id} label={label} required={required} requireDefault={requireDefault} hidden={hideLabel} /&gt; &lt;div className={`${type}-field__wrapper`}&gt; {isValid ? ( &lt;FieldDescription name={id} description={description} hidden={hideDescription} /&gt; ) : ( &lt;FieldErrorMessage name={id} message={message} /&gt; )} &lt;FieldText {...this.props} value={value} handleChange={this._handleChange} fieldData={fieldData} /&gt; {type === 'date' &amp;&amp; &lt;div className="date-field__icon" /&gt;} &lt;/div&gt; &lt;/div&gt; ) } } export default FieldTextWrap </code></pre> <h3>Select Wrapper</h3> <pre><code>'use strict' import React, { Component } from 'react' import { FieldSelect, FieldLabel, FieldDescription, FieldErrorMessage } from './' import PropTypes from 'prop-types' class FieldSelectWrap extends Component { static propTypes = {} constructor(props) { super(props) this.state = { value: '', isValid: true } } _handleChange = value =&gt; this.setState({ value }) componentDidMount() { const { required, type, value, initialValue, dispatch, handleBlur, isForm, formId, id } = this.props !!initialValue &amp;&amp; this.setState({ value: initialValue }) !initialValue &amp;&amp; !!value &amp;&amp; this.setState({ value }) const fieldData = { id, value, type, required, formId, valid: true } return isForm &amp;&amp; dispatch(handleBlur(null, dispatch, fieldData)) } componentDidUpdate(prevProps, prevState) { const { validationRule, required } = this.props const { value } = this.state const didUpdate = prevState.value !== value // validate and update const isValid = !!validationRule ? validationRule.func({ field: { required, value }, tests: validationRule.tests, options: validationRule.options }) : true didUpdate &amp;&amp; this.setState({ isValid }) } componentWillUnmount() { const { removeFormField, id, isForm } = this.props isForm &amp;&amp; removeFormField(id) } render() { const { className = '', description, fieldGroup = '', formName, formId, hideDescription, hideLabel, id, label, required, requireDefault, type, validationText: message = '' } = this.props const classes = `form-item ${formName}__${id} ${fieldGroup} ${type}-field ${className} ${type}` const value = this.state.value const isValid = this.state.isValid const fieldData = { id, value, type, required, formId, valid: isValid, message } return ( &lt;div className={classes}&gt; &lt;FieldLabel name={id} label={label} required={required} requireDefault={requireDefault} hidden={hideLabel} /&gt; &lt;div className={`${type}-field__wrapper`}&gt; &lt;FieldDescription name={id} description={description} hidden={hideDescription} /&gt; {!isValid &amp;&amp; &lt;FieldErrorMessage name={id} message={message} /&gt;} &lt;FieldSelect {...this.props} value={value} handleChange={this._handleChange} fieldData={fieldData} /&gt; {type === 'date' &amp;&amp; &lt;div className="date-field__icon" /&gt;} &lt;/div&gt; &lt;/div&gt; ) } } export default FieldSelectWrap </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T15:33:55.520", "Id": "388227", "Score": "0", "body": "How would they be used? Is their usage similar as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T15:48:12.187", "Id": "388229", "Sc...
[ { "body": "<p>Combining them to reduce duplicate code is not a good approach. Prefer small composable components over large Swiss army knife components. Think <a href=\"https://stackify.com/solid-design-principles/\" rel=\"nofollow noreferrer\">single responsibility principle</a>.</p>\n\n<p>If your component ta...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T14:00:12.567", "Id": "201576", "Score": "0", "Tags": [ "form", "react.js", "jsx" ], "Title": "React component wrappers for form fields with 90% similar code" }
201576
<p>I am currently writing a C# console application. Part of it is, that the user needs to enter a fairly complex system name. To make it easier I wrote a function that uses a string[] keywords and auto completes the string the user is typing in - on the run (which makes it different to this <a href="https://codereview.stackexchange.com/questions/139172/autocompleting-console-input">post</a> in my opinion)</p> <p>The code is working and acts as expected, but I am curious how the code could be improved (e.g. usability, efficiency). Also, what functionalities are missing, which you'd expect?</p> <p>Thank you for the feedback!</p> <pre><code> class Program { static void Main(string[] args) { string[] Keywords = new string[4] { "aX1223", "aE_334", "L_test1", "L_test2" }; if (Keywords.Length == 0) throw new ArgumentException(nameof(Keywords), "No Keywords set!"); bool searching = true; // true while looking for the keyword Console.CursorVisible = true; // To help users understand where they are typing string userInput = ""; // Initialization of output string suggestion = Keywords[0]; // Initialization of default suggestion int toClear = suggestion.Length; // Get the length of the line that needs to be cleared while (searching) { Console.Write(new String(' ', toClear)); // Clear line Console.CursorLeft = 0; // Relocate cursor to line start Console.Write(userInput); // Write what has been written previously if (suggestion != "") // If there is a suggestion fitting the entered string, { // complete the string in color and reset the cursor int col = Console.CursorLeft; Console.ForegroundColor = ConsoleColor.Magenta; Console.Write(suggestion.Substring(userInput.Length)); Console.ForegroundColor = ConsoleColor.White; Console.CursorLeft = col; } string tempInput = Console.ReadKey().KeyChar.ToString(); if (tempInput.Equals("\r")) // Evaluate input: { // -&gt; Enter if (!suggestion.Equals("")) // Valid entry? { searching = false; userInput = suggestion; // -&gt; use suggestion } } else if (tempInput.Equals("\b")) // Deleting last sign { if (userInput.Length &gt; 0) userInput = userInput.Substring(0, userInput.Length - 1); } else // Any other sign is added to the string userInput += tempInput; // Set length to clear, if suggestion == "", the system string length needs to be cleared toClear = (userInput.Length &gt; suggestion.Length) ? userInput.Length : suggestion.Length; // Reset suggestion. If no match is found, suggestion remains empty suggestion = ""; // Check keywords for suggestion for (int i = 0; i &lt; Keywords.Length; i++) { if (Keywords[i].StartsWith(userInput)) { suggestion = Keywords[i]; break; } } } // reset cursor visibility Console.CursorVisible = false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T14:38:14.443", "Id": "388219", "Score": "1", "body": "[Crosspost on Stack Overflow](https://stackoverflow.com/questions/51823794/c-sharp-console-autocomplete-suggest-input-code-improvement)" } ]
[ { "body": "<p>A few minor comments:</p>\n\n<ul>\n<li><p><strong>Don't mix equality types.</strong></p>\n\n<p>You use <code>suggestion != \"\"</code> in one place, then <code>!suggestion.Equals(\"\")</code>. Don't. Use the same type of equality (either using <code>.Equals</code> or not using <code>.Equals</code>...
{ "AcceptedAnswerId": "201589", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T14:27:48.233", "Id": "201578", "Score": "6", "Tags": [ "c#", "console", "autocomplete" ], "Title": "Console autocomplete for complex names" }
201578
<p>I've written a view to retrieve each product's sold quantity and four week sales average by <code>Branch</code>/<code>Route</code>/<code>Customer</code>.</p> <p><strong>Introduction to Dataset</strong></p> <ul> <li>It might be easiest to start with the innermost query (commented as <code>B: SalesByWeek grouped by Branch.</code>) since it's the base and the outer queries are the same query grouped by Route and Customer instead.</li> <li><code>Branch</code>es contain one or many <code>Route</code>s.</li> <li><code>Route</code>s contain one or many <code>Customer</code>s.</li> <li><code>SAP_VisitPlan</code> is an effectivity table. It defines which customers are on which routes and which routes are on which branches.</li> <li><code>vw_SalesByWeek</code> is two cache tables unioned to obtain all customer sales week totals.</li> </ul> <p><strong>The View</strong></p> <pre><code>CREATE VIEW [dbo].[vw_SalesByWeekSummary] AS SELECT VP.Branch , VP.ROUTE AS Route , VP.SAPCustomerID , S.SalesType , S.CustomerID , S.ProductID , S.Date , SUM(Quantity) AS CustomerQuantity , SUM(FourWeekSalesAvg) AS CustomerFourWeekSalesAvg , R.RouteQuantity , R.RouteFourWeekSalesAvg , R.BranchQuantity , R.BranchFourWeekSalesAvg FROM vw_SalesByWeek AS S WITH (NOLOCK) INNER JOIN SAP_VisitPlan AS VP WITH (NOLOCK) ON VP.CustomerID = S.CustomerID AND VP.DateFrom &lt;= S.Date AND VP.DateTo &gt;= S.Date INNER JOIN ( -- R: SalesByWeek grouped by Route. SELECT VP.Branch , VP.ROUTE AS Route , S.ProductID , S.Date , SUM(Quantity) AS RouteQuantity , SUM(FourWeekSalesAvg) AS RouteFourWeekSalesAvg , B.BranchQuantity , B.BranchFourWeekSalesAvg FROM vw_SalesByWeek AS S WITH (NOLOCK) INNER JOIN SAP_VisitPlan AS VP WITH (NOLOCK) ON VP.CustomerID = S.CustomerID AND VP.DateFrom &lt;= S.Date AND VP.DateTo &gt;= S.Date INNER JOIN ( -- B: SalesByWeek grouped by Branch. SELECT VP.Branch , ProductID , Date , SUM(Quantity) AS BranchQuantity , SUM(FourWeekSalesAvg) AS BranchFourWeekSalesAvg FROM vw_SalesByWeek AS S WITH (NOLOCK) INNER JOIN SAP_VisitPlan AS VP WITH (NOLOCK) ON VP.CustomerID = S.CustomerID AND VP.DateFrom &lt;= S.Date AND VP.DateTo &gt;= S.Date GROUP BY VP.Branch, ProductID, Date ) AS B ON B.Branch = VP.Branch AND B.ProductID = S.ProductID AND B.Date = S.Date GROUP BY VP.Branch, VP.ROUTE, S.ProductID, S.Date, B.BranchQuantity, B.BranchFourWeekSalesAvg ) AS R ON R.Branch = VP.Branch AND R.Route = VP.ROUTE AND R.ProductID = S.ProductID AND R.Date = S.Date GROUP BY VP.Branch, VP.ROUTE, VP.SAPCustomerID, S.SalesType, S.CustomerID, S.ProductID, S.Date, R.BranchQuantity, R.BranchFourWeekSalesAvg, R.RouteQuantity, R.RouteFourWeekSalesAvg GO </code></pre> <p><strong>vw_SalesByWeek Query</strong></p> <pre><code>SELECT 'Conv' AS [SalesType] , [CustomerID] , [ProductID] , [WkStartDate] AS [Date] , [SoldQuantity] AS [Quantity] , [Route] , [FourWeekSalesAvg] , [NumberOfPriorSalesWeeks] FROM Cache_ConvSalesByWeek WITH (NOLOCK) UNION ALL SELECT 'Scan' AS [SalesType] , [CustomerID] , [ProductID] , [WkStartDate] , [SoldQuantity] , [Route] , [FourWeekSalesAvg] , [NumberOfPriorSalesWeeks] FROM Cache_ScanSalesByWeek WITH (NOLOCK) </code></pre> <p><strong>Usage Query</strong></p> <pre><code>SELECT Branch , Route , SAPCustomerID , SalesType , CustomerID , ProductID , Date , CustomerQuantity , CustomerFourWeekSalesAvg , RouteQuantity , RouteFourWeekSalesAvg , BranchQuantity , BranchFourWeekSalesAvg FROM vw_SalesByWeekSummary WHERE Route = '0600' AND Date = '08/06/2018' </code></pre> <p><strong>Concerns</strong></p> <ul> <li>My concern is readability. I don't like that this query is basically the same query 3 times with different groupings for the sums.</li> <li>I originally wrote this as three views that built on one-another. That is, one for the branch sums, one for the route sums, and one for the customer sums where each subsequent view used the prior. My co-workers did not like this as they fear a dependency-hell style scenario.</li> <li>I have two other queries similar to this structurally, so any improvements that could be made will be incredibly helpful and appreciated.</li> </ul> <p><strong>Question</strong></p> <p>Is there a way to write this query in a more concise or conceptually simplistic way, possibly with less repetition?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-15T23:39:10.623", "Id": "388601", "Score": "0", "body": "What version of SQL Server are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-15T23:52:09.937", "Id": "388605", "Score": "0", ...
[ { "body": "<p>I would test using the <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">OVER clause with aggregate functions</a>. This may speed up your results and make it a bit more readable. You may also want to chec...
{ "AcceptedAnswerId": "201765", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T15:06:16.247", "Id": "201581", "Score": "4", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Retrieving a product's sold quantity" }
201581
<p>My server code is currently reading <code>String</code> data over a TCP connection form 2 different client computers. To do this I am duplicating the <code>StreamReader</code> functions for the two separate clients. <strong>How can I simplify my code into just one method without having to duplicate for every client?</strong> (I want to do 4 clients in the future, duplicating a part of the code 4 times is very tedious and clumsy). </p> <pre><code>public class AsynchIOServer { static TcpListener tcpListener = new TcpListener(15); static TcpListener tcpListener2 = new TcpListener(10); static void Listeners() { using (Socket socketForClient = tcpListener.AcceptSocket()) { if (socketForClient.Connected) { Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server."); using (NetworkStream networkStream = new NetworkStream(socketForClient)) //using (NetworkStream networkStream2 = new NetworkStream(socketForClient)) using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream)) using (System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream)) //using (System.IO.StreamReader streamReader2 = new System.IO.StreamReader(networkStream2)) { try { while (true) { string theString = streamReader.ReadLine(); if (string.IsNullOrEmpty(theString) == false) { Console.WriteLine("Kinect1:" + theString); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } } Console.WriteLine("Press any key to exit from server program"); Console.ReadKey(); } //--------------------------------------------------------------------------- static void Listeners2() { using (Socket socketForClient2 = tcpListener2.AcceptSocket()) { if (socketForClient2.Connected) { Console.WriteLine("Client:" + socketForClient2.RemoteEndPoint + " now connected to server."); //using (NetworkStream networkStream = new NetworkStream(socketForClient)) using (NetworkStream networkStream2 = new NetworkStream(socketForClient2)) using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream2)) //using (System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream)) using (System.IO.StreamReader streamReader2 = new System.IO.StreamReader(networkStream2)) { try { while (true) { string theString2 = streamReader2.ReadLine(); if (string.IsNullOrEmpty(theString2) == false) { Console.WriteLine("Kinect2:" + theString2); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } } Console.WriteLine("Press any key to exit from server program"); Console.ReadKey(); } public static void Main() { tcpListener.Start(); tcpListener2.Start(); Console.WriteLine("************This is Server program************"); Console.WriteLine("How many clients are going to connect to this server?:"); int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine()); for (int i = 0; i &lt; numberOfClientsYouNeedToConnect; i++) { Thread newThread = new Thread(new ThreadStart(Listeners)); newThread.Start(); } for (int i = 0; i &lt; numberOfClientsYouNeedToConnect; i++) { Thread newThread2 = new Thread(new ThreadStart(Listeners2)); newThread2.Start(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T18:03:47.837", "Id": "388238", "Score": "2", "body": "What happened to the `Listeners2`? Did you forget to paste it? Please post the complete code, without editing it. Only then we can suggest you how to optimize it." }, { "...
[ { "body": "<p>You can use a <code>ParameterizedThreadStart</code> instead of <code>TheadStart</code> and then provide each <code>TcpListener</code> instance as parameter to each new <code>Thread</code>:</p>\n\n<pre><code> TcpListener[] listeners =\n {\n new TcpListener(15),\n new TcpListener(10)\n };\n...
{ "AcceptedAnswerId": "201612", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T17:06:12.003", "Id": "201587", "Score": "4", "Tags": [ "c#", "strings", "stream", "server", "tcp" ], "Title": "Multiple client TCP stream reader" }
201587
<p>I have implemented my solution and I thought it was pretty efficient and passes most of the cases but seems like it fails some of the test cases when the input size is very large. I basically push every item from the Alice's array to our array and sort it.I'd appreciate if somebody tell me how I could increase the efficiency get rid of the timeout error.</p> <blockquote> <p>Alice is playing an arcade game and wants to climb to the top of the leaderboard. Can you help her track her ranking as she beats each level? The game uses Dense Ranking, so its leaderboard works like this:</p> <p>The player with the highest score is ranked number 1 on the leaderboard. Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number. For example, four players have the scores 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively.</p> <p>When Alice starts playing, there are already n people on the leaderboard. The score of each player i is denoted by si. Alice plays for m levels, and we denote her total score after passing each level j as alicej. After completing each level, Alice wants to know her current rank.</p> <p>You are given an array, scores, of monotonically decreasing leaderboard scores, and another array, alice, of Alice's cumulative scores for each level of the game. You must print m integers. The jth integer should indicate the current rank of alice after passing the jth level.</p> </blockquote> <p>To illustrate;</p> <pre><code>Score is :100 100 50 40 40 20 10 Alice is: 5 25 50 120 </code></pre> <p>The output is going to be;</p> <pre><code>6,4,2,1 </code></pre> <p>My implementation:</p> <pre><code>function ladder(arr1,arr2){ while(arr2.length){ let i=0 let rank=1 let score=arr2.shift() arr1.push(score) arr1.sort(function(a,b){ return b-a }) while(arr1[i]!==score){ if(arr1[i]!==arr1[i+1]){ rank++ } i++ } console.log(rank) } } </code></pre>
[]
[ { "body": "<p>There are some important inefficient elements in the posted implementation.</p>\n\n<h3>Inserting into a sorted array</h3>\n\n<p>To insert Alice's next score into the array of sorted scores,\nthe posted appends Alice's score at the end and then sorts the array.\nWhat's the typical time complexity o...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T17:35:58.530", "Id": "201590", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "Climbing the Leaderboard: HackerranK, Terminated due to timeout" }
201590
<p>I have followed a tutorial that initially was for adding a 'sticky' nav. I adapted this slightly so it adds a background to the Nav when the page scroll reaches the top-third point of the hero area.</p> <p>I then added a similar function that dims the hero area once the scroll gets to the midway point of the hero.</p> <p>Both functions work in terms of displaying the expected results, but I am questioning the need for two almost identical functions and event listeners.</p> <p>Could these be combined into one, complete function?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const hero = document.querySelector("#heroArea"); // Finds the top third of the element by adding the top of the element to the height of the element then divide by 3 const bottomOfNav = hero.offsetHeight / 3; const middleHero = hero.offsetHeight / 2; function fixNav() { // If the window position is greater or equal to the bottom of the nav if (window.scrollY &gt;= bottomOfNav) { // Adds a class to the body tag document.body.classList.add("fixed-nav"); } else { document.body.classList.remove("fixed-nav"); } } window.addEventListener("scroll", fixNav); function dimHero() { if (window.scrollY &gt;= middleHero) { document.body.classList.add("dim-hero"); } else { document.body.classList.remove("dim-hero"); } } window.addEventListener("scroll", dimHero);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; font-family: sans-serif; } nav { position: fixed; width: 100%; left: 0; right: 0; color: #fff; padding: 15px; text-align: center; text-transform: uppercase; font-family: sans-serif; transition: .3s; } .fixed-nav nav { background: #333; } .hero { height: 100vh; background: black; opacity: 1; transition: .3s; } .dim-hero .hero { opacity: 0; } .text-block { height: 50vh; background: #555; color: #fff; font-size: 30px; text-align: center; padding: 40px; } .text-block-two { background: #333; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;nav&gt;Navigation&lt;/nav&gt; &lt;div id="heroArea" class="hero"&gt;&lt;/div&gt; &lt;div class="text-block"&gt;Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eos ipsum et, omnis sit vero ab doloremque quia dolores mollitia. Doloremque maxime dolores quo eius ea. Ad, reiciendis minus. Dolorum, hic.&lt;/div&gt; &lt;div class="text-block text-block-two"&gt;Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eos ipsum et, omnis sit vero ab doloremque quia dolores mollitia. Doloremque maxime dolores quo eius ea. Ad, reiciendis minus. Dolorum, hic.&lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>In answer to my own question, I asked a colleague for their input and they came up with what I believe to be a much cleaner method.</p>\n\n<p>My understanding of this code is that to make the code easier to maintain it is better to create one function that handles the adding and removing of the cl...
{ "AcceptedAnswerId": "205457", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T17:38:52.703", "Id": "201591", "Score": "2", "Tags": [ "javascript", "beginner", "css", "ecmascript-6", "dom" ], "Title": "Dim Hero & Add Background to Nav on scroll" }
201591
<p>I am doing this implementation in JavaScript that I was asked to solve. I would like to get some code review.</p> <pre><code>/** * Binary Search Tree * * TreeNode class * * Create a TreeNode class * The TreeNode class should contain the following properties: * * * * BinarySearchTree class. * * Create a BinarySearchTree class * * The BinarySearchTree class should contain the following * properties: * * root: A pointer to the root node (initially null) * size: The number of nodes in the BinarySearchTree * * The BinarySearchTree class should also contain the following * methods: * * insert: A method that takes takes an integer value, and * creates a node with the given input. The method * will then find the correct place to add the new * node. Values larger than the current node node go * to the right, and smaller values go to the left. * * Input: value * Output: undefined * * search: A method that will search to see if a node with a * specified value exists and returns true or false */ </code></pre> <p>Here's the implementation and unit test:</p> <pre><code>'use strict'; class TreeNode { constructor(value = null) { this.value = value; this.left = this.right = null; } } class BinarySearchTree { constructor() { this.root = null; this.size = 0; } // Time Complexity: O(N) // Auxiliary Space Complexity: O(N) insert(value) { if (!this.root) { this.root = new TreeNode(value); this.size++; return; } else { let currentNode = this.root; let newNode = new TreeNode(value); while (currentNode) { if (value &lt; currentNode.value) { if (currentNode.left) { currentNode = currentNode.left; } else { currentNode.left = newNode; this.size++; break; } } else { if (currentNode.right) { currentNode = currentNode.right; } else { currentNode.right = newNode; this.size++; break; } } } } } // Time Complexity: O(N) // Auxiliary Space Complexity: O(N) search(value) { if (!this.root) { return false; } let currentNode = this.root; if (currentNode.value === value) { return true; } while (currentNode) { if (value &lt; currentNode.value) { if (currentNode.left) { currentNode = currentNode.left; } else { return false; } } else if (value &gt; currentNode.value) { if (currentNode.right) { currentNode = currentNode.right; } else { return false; } } else { return true; } } return false; } } //////////////////////////////////////////////////////////// /////////////// DO NOT TOUCH TEST BELOW!!! /////////////// //////////////////////////////////////////////////////////// console.log('TreeNode Class'); let testCount = [0, 0]; assert(testCount, 'able to create an instance', () =&gt; { let node = new TreeNode(); return typeof node === 'object'; }); assert(testCount, 'has value property', () =&gt; { let node = new TreeNode(); return node.hasOwnProperty('value'); }); assert(testCount, 'has left property', () =&gt; { let node = new TreeNode(); return node.hasOwnProperty('left'); }); assert(testCount, 'has right property', () =&gt; { let node = new TreeNode(); return node.hasOwnProperty('right'); }); assert(testCount, 'has default value set to null', () =&gt; { let node = new TreeNode(); return node.value === null; }); assert(testCount, 'able to assign a value upon instantiation', () =&gt; { let node = new TreeNode(5); return node.value === 5; }); assert(testCount, 'able to reassign a value', () =&gt; { let node = new TreeNode(); node.value = 5; return node.value === 5; }); assert(testCount, 'able to point to left child node', () =&gt; { let node1 = new TreeNode(5); let node2 = new TreeNode(10); node1.left = node2; return node1.left.value === 10; }); assert(testCount, 'able to point to right child node', () =&gt; { let node1 = new TreeNode(5); let node2 = new TreeNode(10); node1.right = node2; return node1.right.value === 10; }); console.log('PASSED: ' + testCount[0] + ' / ' + testCount[1], '\n\n'); console.log('Binary Search Tree Class'); testCount = [0, 0]; assert(testCount, 'able to create an instance', () =&gt; { let bst = new BinarySearchTree(); return typeof bst === 'object'; }); assert(testCount, 'has root property', () =&gt; { let bst = new BinarySearchTree(); return bst.hasOwnProperty('root'); }); assert(testCount, 'has size property', () =&gt; { let bst = new BinarySearchTree(); return bst.hasOwnProperty('size'); }); assert(testCount, 'default root set to null', () =&gt; { let bst = new BinarySearchTree(); return bst.root === null; }); assert(testCount, 'default size set to zero', () =&gt; { let bst = new BinarySearchTree(); return bst.size === 0; }); console.log('PASSED: ' + testCount[0] + ' / ' + testCount[1], '\n\n'); console.log('BinarySearchTree Insert Method'); testCount = [0, 0]; assert(testCount, 'has insert method', () =&gt; { let bst = new BinarySearchTree(); return Object.prototype.toString.apply(bst.insert) === '[object Function]'; }); assert(testCount, 'able to insert a node into empty binary search tree', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); return bst.size === 1 &amp;&amp; bst.root.value === 5; }); assert(testCount, 'able to insert node to left of root node', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); bst.insert(3); return bst.size === 2 &amp;&amp; bst.root.value === 5 &amp;&amp; bst.root.left.value === 3; }); assert(testCount, 'able to insert node to right of node left of root node', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); bst.insert(3); bst.insert(4); return bst.size === 3 &amp;&amp; bst.root.value === 5 &amp;&amp; bst.root.left.value === 3 &amp;&amp; bst.root.left.right.value === 4; }); assert(testCount, 'able to insert node to right of root node', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); bst.insert(8); return bst.size === 2 &amp;&amp; bst.root.value === 5 &amp;&amp; bst.root.right.value === 8; }); assert(testCount, 'able to insert node to left of node right of root node', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); bst.insert(8); bst.insert(7); return bst.size === 3 &amp;&amp; bst.root.value === 5 &amp;&amp; bst.root.right.value === 8 &amp;&amp; bst.root.right.left.value === 7; }); console.log('PASSED: ' + testCount[0] + ' / ' + testCount[1], '\n\n'); console.log('BinarySearchTree Search Method'); testCount = [0, 0]; assert(testCount, 'has search method', () =&gt; { let bst = new BinarySearchTree(); return Object.prototype.toString.apply(bst.search) === '[object Function]'; }); assert(testCount, 'returns true when element exists in binary search tree', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); bst.insert(3); bst.insert(8); bst.insert(4); bst.insert(7); return bst.search(4) === true; }); assert(testCount, 'returns false when element does not exist in binary search tree', () =&gt; { let bst = new BinarySearchTree(); bst.insert(5); bst.insert(3); bst.insert(8); bst.insert(4); bst.insert(7); return bst.search(10) === false; }); console.log('PASSED: ' + testCount[0] + ' / ' + testCount[1], '\n\n'); // custom assert function to handle tests // input: count {Array} - keeps track out how many tests pass and how many total // in the form of a two item array i.e., [0, 0] // input: name {String} - describes the test // input: test {Function} - performs a set of operations and returns a boolean // indicating if test passed // output: {undefined} function assert(count, name, test) { if(!count || !Array.isArray(count) || count.length !== 2) { count = [0, '*']; } else { count[1]++; } let pass = 'false'; let errMsg = null; try { if (test()) { pass = ' true'; count[0]++; } } catch(e) { errMsg = e; } console.log(' ' + (count[1] + ') ').slice(0,5) + pass + ' : ' + name); if (errMsg !== null) { console.log(' ' + errMsg + '\n'); } } </code></pre>
[]
[ { "body": "<p>The <code>search</code> function can be simpler.</p>\n\n<ul>\n<li><p>The special treatment for <code>this.root</code> is unnecessary. If you drop the conditional on <code>this.root</code>, and on <code>currentNode.value === value</code>, the loop will naturally handle it.</p></li>\n<li><p>Inside t...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T17:59:23.090", "Id": "201592", "Score": "1", "Tags": [ "javascript" ], "Title": "BST implementation for insert and search in JavaScript" }
201592
<p>I have written a function that evaluates a contour integral in Python (Poincaré - Hopf index for 2D vector fields). It works, however is really slow if the arg <code>res=N</code> is chosen higher than 50. Input are two arrays of dimension <code>N x N</code>. As the integrals should lead to an integer, (usually -1, 0, or 1) only small accuracy is necessary. I believe that most time is lost doing the interpolation, but I don't know any other method. </p> <p><strong>Update:</strong> I have added a sample vector field \$ \mathbf{M} = (mx, my)^T \$. This produces output -1 if \$ (0, 0) \$ is included in the contour and 0 else. This works as a sample input. Real data is usually less smooth. </p> <pre><code>import numpy as np from scipy.interpolate import interp2d from scipy.integrate import quad from scipy.misc import derivative N = 100 xvec = np.linspace(-5, 5, N) X, Y = np.meshgrid(xvec, xvec) mx = Y / (X**2 + Y**2)**(1/2) my = X / (X**2 + Y**2)**(1/2) def partial_derivative(func, var=0, point=[]): args = point[:] def wraps(x): args[var] = x return func(*args) return derivative(wraps, point[var], dx=1e-6) def poin_int(arr_x, arr_y, alpha=5, res=N, r=1, x0=0, y0=0): xvec = np.linspace(-alpha, alpha, res) X, Y = np.meshgrid(xvec, xvec) # create grid x_func = interp2d(X, Y, arr_x, kind='cubic') # interpolate data y_func = interp2d(X, Y, arr_y, kind='cubic') # interpolate data def _x(t): # x-coordinate of circular contour return np.cos(t) * r + x0 def _dx(t): # derivate of _x(t) return -np.sin(t) * r def _y(t): # y-coordinate of circular contour return np.sin(t) * r + y0 def _dy(t): # derivative of _y(t) return np.cos(t) * r def _integrand1(t): # integrand of first integral return (x_func(_x(t), _y(t)) * (partial_derivative(y_func, 0, [_x(t), _y(t)]) * _dx(t) + partial_derivative(y_func, 1, [_x(t), _y(t)]) * _dy(t)) / (x_func(_x(t), _y(t))**2 + y_func(_x(t), _y(t))**2) * 2 * np.pi) def _integrand2(t): # integrand of second integral return (-y_func(_x(t), _y(t)) * (partial_derivative(x_func, 0, [_x(t), _y(t)]) * _dx(t) + partial_derivative(x_func, 1, [_x(t), _y(t)]) * _dy(t)) / (x_func(_x(t), _y(t))**2 + y_func(_x(t), _y(t))**2 * 2 * np.pi)) _int1 = quad(_integrand1, 0, 2*np.pi, epsabs=1e-2) _int2 = quad(_integrand2, 0, 2*np.pi, epsabs=1e-2) return (_int1[0] + _int2[0]) # should be an integer poin_int(mx, my, res=N, r=1, x0=0, y0=0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T05:56:05.317", "Id": "388302", "Score": "1", "body": "It would be very helpful to include some input to the functions. That way, debugging and optimization is possible." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T18:10:26.513", "Id": "201594", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Numerical evaluation of line integral" }
201594
<p>I want to go more in depth, but this is the 'boilerplate'. </p> <p>Is there any way I can optimize this or use more idiomatic Python code?</p> <pre><code>#Luhn algorithm - distinguish valid numbers from mistyped or incorrect numbers. def checkNumber(cc_number=''): sum_ = 0 parity = len(cc_number) % 2 for i, digit in enumerate([int(x) for x in cc_number]): if i % 2 == parity: digit *= 2 if digit &gt; 9: digit -= 9 sum_ += digit return sum_ % 10 == 0 def main(): number = input('Input credit card number: ') if 12 &lt; len(number) &lt; 17: first_two = number[0:2] first_four = number[0:4] vendor = None if number[0] == 4: vendor = 'Visa' elif number[0] == '5' and '0' &lt; number[1] &lt; '6': vendor = 'Mastercard' elif number[0] == '6' or first_four == '6011': vendor = 'Discover' elif first_two in ('36', '38'): vendor = "Diners Club" elif first_two in ('34', '37'): vendor = 'American Express' if vendor is not None: if checkNumber(number): print(f'This is a valid {vendor} credit card!') else: print(f'This is not a valid {vendor} credit card.') else: print('Unknown vendor.') else: print('Sorry, this is not a valid credit card number!') print(checkNumber('12345')) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T19:11:59.370", "Id": "388246", "Score": "3", "body": "The code looks awfully duplicate of the one on wikipedia: https://en.wikipedia.org/wiki/Luhn_algorithm#Python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": ...
[ { "body": "<p>just sometimes some expressions can be assigned to a variable to prevent recalculation like number[0] can be replaced with first_num</p>\n\n<p>from </p>\n\n<pre><code>if number[0] == 4:\n vendor = 'Visa'\n elif number[0] == '5' and '0' &lt; number[1] &lt; '6':\n vendor = 'Masterca...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T18:30:12.030", "Id": "201597", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Credit card validity check" }
201597
<p>I have a <code>Game</code> model that is "static". Containing game information and such, and users can comment on all games.</p> <p><code>Games</code> model</p> <pre><code>public function comments() { return $this-&gt;morphMany(Comment::class, 'commentable'); } </code></pre> <p>And then I have a <code>Comment</code> model. This has a <code>User</code> relation and a <code>Comments</code> relation.</p> <pre><code>public function commentable() { return $this-&gt;morphTo(); } public function user() { return $this-&gt;belongsTo(User::class); } </code></pre> <p>What I want to do is to fetch the 10 games sorted by the latest comment top, be able to display who made the comment, and when.</p> <p>I have this query that seems to do the job, but it makes an absurd amount of queries. Can I somehow keep the queries to a minimum?</p> <pre><code> $games = Game::join('comments', 'games.id', '=', 'comments.commentable_id') -&gt;where('comments.commentable_type', Game::class) -&gt;latest('comments.created_at') -&gt;groupBy('games.id') -&gt;take(10) -&gt;withCount('comments') -&gt;get()-&gt;each(function($games){ $games-&gt;comment = $games-&gt;comments()-&gt;orderBy('created_at', 'desc')-&gt;first(); $games-&gt;user = User::find($games-&gt;comment-&gt;user_id); return $games; }); </code></pre>
[]
[ { "body": "<p>You didn't specify which version of Laravel is used, so I am going to presume it is 5.x. If that is incorrect, please notify me and update your post with such relevant information</p>\n\n<p>I am not sure exactly how to reduce the queries for comments but the suggestion below should allow remove th...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T18:31:27.507", "Id": "201598", "Score": "2", "Tags": [ "php", "laravel", "iteration", "eloquent" ], "Title": "Retrive relation on a polymorphic model" }
201598
<p>I'm new to Android development and this is my first request for a code review. Constructive criticism is very welcome!</p> <p>I've written a class to wrap interaction with Google's FusedLocationProviderClient. I'm not sure it's a very good idea though as it's not an Activity class and yet there are parts of it that potentially require user interaction - displaying an alert dialog for example. So any suggestions as to the pros and cons on my approach on that front in particular would be appreciated.</p> <p>I'm also quite worried about the inner-class that extends FragmentActivity. It's used by one method to provide additional rationale to the user for a permission request if necessary. Firstly, should I be messing around with a FragmentActivity for this? If not why not, and could you suggest a more suitable alternative?</p> <p>Aside from those specific points any feedback - both good or bad - on how I've gone about this, or how I might better go about it, will be greatly appreciated.</p> <p>Here's the class (sorry it's quite long!)...</p> <pre><code>/** * &lt;h1&gt;Wraps interactions with the Google Play Services FusedLocationProviderClient&lt;/h1&gt; * &lt;p&gt; * Provides an easy way to work with a device's location, including testing for and * requesting the necessary permission(s) as needed. * &lt;/p&gt; * &lt;p&gt; * Provides several methods for retrieving the device's current or last known location. * Also provides methods for obtaining the address details of a location. * &lt;/p&gt; * &lt;p&gt; * Requires &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt; * to be present in the app's Manifest. * &lt;/p&gt; * &lt;p&gt; * The calling Activity should implement ActivityCompat.OnRequestPermissionsResultCallback * to receive and handle the result(s) of a permission request. * &lt;/p&gt; * */ public class UserLocationUtility extends LocationCallback { private static final String TAG = UserLocationUtility.class.getSimpleName(); /** * Inner-class defining int constants for use with location requests */ public static class RequestCodes { static final int CURRENT_LOCATION_ONE_TIME = 0; static final int CURRENT_LOCATION_UPDATES = 1; static final int LAST_KNOWN_LOCATION = 2; static final int SMART_LOCATION = 3; } /** * Inner-class defining int constants for use with reverse Geocoding of address data */ public static class AddressCodes { static final int ADMIN_AREA = 0; static final int CITY_NAME = 1; static final int COUNTRY_CODE = 2; static final int COUNTRY_NAME = 3; static final int FEATURE_NAME = 4; static final int FULL_ADDRESS = 5; static final int PHONE_NUMBER = 6; static final int POST_CODE = 7; static final int PREMISES = 8; static final int STREET_ADDRESS = 9; static final int SUB_ADMIN_AREA = 10; static final int SUB_THOROUGHFARE = 11; } /** * Inner-class to provide alert dialog functionality for use with permissions checking */ public static class RationaleAlertDialog extends FragmentActivity { // Hold a WeakReference to the host activity (allows it to be garbage-collected to prevent possible memory leak) private final WeakReference&lt;Activity&gt; weakActivity; private static final String TAG = RationaleAlertDialog.class.getSimpleName(); /** Constructor */ RationaleAlertDialog(Activity activity){ // assign the activity to the weak reference this.weakActivity = new WeakReference&lt;&gt;(activity); } public void displayAlert(){ // Re-acquire a strong reference to the calling activity and verify that it still exists and is active Activity activity = weakActivity.get(); if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // Activity is no longer valid, don't do anything return; } // Build the alert AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("Location Permission Request") .setMessage("This app requires permission to access device location in order " + "to provide location functionality. If you do not grant permission " + "then this functionality will be switched off.") .setCancelable(true) .setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // Dismiss the dialog dialogInterface.cancel(); } }); // Display the alert AlertDialog alert = builder.create(); alert.show(); } } // Hold a WeakReference to the host activity (allows it to be garbage-collected to prevent possible memory leak) private final WeakReference&lt;Activity&gt; weakActivity; private FusedLocationProviderClient mLocationClient; private Context mContext; private LocationRequest mLocationRequest; private LocationCallback mLocationCallback; private boolean mIsReceivingUpdates; private Geocoder mGeocoder; /** Constructor */ UserLocationUtility(Activity activity){ // assign the activity to the weak reference this.weakActivity = new WeakReference&lt;&gt;(activity); // Hold a reference to the Application Context single object this.mContext = activity.getApplicationContext(); // Instantiate our location client this.mLocationClient = LocationServices.getFusedLocationProviderClient(mContext); // Set the request state flag to false by default mIsReceivingUpdates = false; // Set up the default LocationRequest parameters this.mLocationRequest = new LocationRequest(); setLocationRequestParams(10000, 5000, LocationRequest.PRIORITY_HIGH_ACCURACY); // Sets up the LocationRequest with an update interval of 10 seconds, a fastest // update interval cap of 5 seconds and using high accuracy power priority. } /** * Retrieves and returns the device's cached last known location via an instance of * UserLocationCallback, which must be implemented by the caller. * * Location can be null in certain circumstances, for example on a new or recently * factory-reset device or if location services are turned off in device settings. */ @SuppressLint("MissingPermission") public void getLastKnownLocation(final UserLocationCallback callback){ // Re-acquire a strong reference to the calling activity and verify that it still exists and is active Activity activity = weakActivity.get(); if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // Activity is no longer valid, don't do anything return; } // Request the last known location from the location client mLocationClient.getLastLocation() .addOnSuccessListener(activity, new OnSuccessListener&lt;Location&gt;() { @Override public void onSuccess(Location location){ if (location != null){ // Call back to the main thread with the location result callback.onLocationResult(location); } else { // Call back to the main thread to advise of a null result callback.onFailedRequest("Location request returned null"); } } }); } /** * Returns the device's current location via an instance of UserLocationCallback, * which must be implemented by the caller. * * Turns on location updates, retrieves the current device location then turns * location updates off again. This can be used if last location returns null * but location services are turned on, or if a more recent or accurate location * is needed than the one found in the device's cache. */ @SuppressLint("MissingPermission") public void getCurrentLocationOneTime(final UserLocationCallback callback){ if (mIsReceivingUpdates){ callback.onFailedRequest("Device is already receiving updates"); return; } // Set up the LocationCallback for the request mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult){ if (locationResult != null){ callback.onLocationResult(locationResult.getLastLocation()); // Stop location updates now that we have a location result stopLocationUpdates(); } else { callback.onFailedRequest("Location request returned null"); // Stop location updates on null result stopLocationUpdates(); } } }; // Start the request mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null); // Update the request state flag mIsReceivingUpdates = true; } /** * Starts a location update request with the parameters specified by mLocationRequest and * returns the location result via an instance of UserLocationCallback, which must be * implemented by the caller. * * This is inherently power-intensive so care should be taken to balance the frequency * of requested updates with the need for accuracy. * * Location updates should be disabled using the stopLocationUpdates() method when no * longer needed, such as when the user closes or otherwise navigates away from the app. * * @see UserLocationUtility#stopLocationUpdates() */ @SuppressLint("MissingPermission") public void getCurrentLocationUpdates(final UserLocationCallback callback){ if (mIsReceivingUpdates){ callback.onFailedRequest("Device is already receiving updates"); return; } // Set up the LocationCallback for the request mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult){ if (locationResult != null){ callback.onLocationResult(locationResult.getLastLocation()); } else { callback.onFailedRequest("Location request returned null"); } } }; // Start the request mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null); // Update the request state flag mIsReceivingUpdates = true; } /** * Returns the best available location via an instance of UserLocationCallback, which * must be implemented by the caller. * * Checks if last known location is available. If unavailable (null) then a single * location update is requested instead. * * If current location is also unavailable (due to a disabled service for example) * then an onFailedRequest callback is executed to be handled by the caller. * * This method should be preferred over the getLastKnownLocation() and * getCurrentLocationOneTime() methods in most use cases. * * @param callback An interface which must be implemented by the caller in order to * receive the results of the location request. */ @SuppressLint("MissingPermission") public void getSmartLocation(final UserLocationCallback callback){ // Re-acquire a strong reference to the calling activity and verify that it still exists and is active Activity activity = weakActivity.get(); if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // Activity is no longer valid, don't do anything return; } // Request the last known location from the location client mLocationClient.getLastLocation() .addOnSuccessListener(activity, new OnSuccessListener&lt;Location&gt;() { @Override public void onSuccess(Location location){ if (location != null){ // Call back to the main thread with the location result Log.i("getSmartLocation()", "Location provided by getLastLocation()"); callback.onLocationResult(location); } else { // Location result is null or so request location updates to attempt // to get the device's current location. // Set up the LocationCallback for the request mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult){ if (locationResult != null){ callback.onLocationResult(locationResult.getLastLocation()); Log.i("getSmartLocation()", "Location provided by requestLocationUpdates()"); // Stop location updates now that we have a location result stopLocationUpdates(); } else { callback.onFailedRequest("Location request returned null"); // Stop location updates on null result stopLocationUpdates(); } } }; // Start the request mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null); // Update the request state flag mIsReceivingUpdates = true; } } }); } /** * Simple check to see if the required permission has been granted. * * @return true if permission granted, false if not. */ public boolean checkPermissionGranted(){ int permissionState = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION); return permissionState == PackageManager.PERMISSION_GRANTED; } /** * Explicitly requests permission to access the device's fine location. * * Determines if additional rationale should be provided to the user, displays it if * so then initiates a permission request via a call to startPermissionRequest(). * * @param requestCode A package-defined int constant to identify the request. * It is returned to the onRequestPermissionsResult callback * which must be implemented by the caller. */ public void requestPermission(int requestCode){ // Re-acquire a strong reference to the calling activity and verify that it still exists and is active Activity activity = weakActivity.get(); if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // Activity is no longer valid, don't do anything return; } boolean shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale( activity, Manifest.permission.ACCESS_FINE_LOCATION); if (shouldProvideRationale){ // Provide additional rationale to the user. This would happen if the user denied the request // previously but didn't tick the "Don't ask again" checkbox. RationaleAlertDialog dialog = new RationaleAlertDialog(activity); dialog.displayAlert(); // Request permission startPermissionRequest(requestCode); } else { // Request permission. It's possible this can be auto-answered if the device policy sets // the permission in a given state or the user denied the request previously and ticked // the "Don't ask again" checkbox. startPermissionRequest(requestCode); } } /** * Called by requestPermission() to initiate a permission request * * @param requestCode the request code passed in by requestPermission() * @see UserLocationUtility#requestPermission(int) */ private void startPermissionRequest(int requestCode){ // Re-acquire a strong reference to the calling activity and verify that it still exists and is active Activity activity = weakActivity.get(); if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // Activity is no longer valid, don't do anything return; } ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestCode); // requestCode is an int constant. The onRequestPermissionsResult callback // gets the result of the request. } /** * Checks if all required location settings are satisfied * * If the settings are not satisfied a dialog requesting the user enable the required * settings will be displayed. The result of the request can be checked in * onActivityResult() in the calling Activity if necessary. */ public void checkDeviceSettings(){ // Re-acquire a strong reference to the calling activity and verify that it still exists and is active final Activity activity = weakActivity.get(); if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // Activity is no longer valid, don't do anything return; } // Create a settings request builder and pass it the LocationRequest LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); // Create a settings client SettingsClient client= LocationServices.getSettingsClient(mContext); // Create a Task from the client Task&lt;LocationSettingsResponse&gt; task = client.checkLocationSettings(builder.build()); // Query the result of the Task to determine if the required location settings are satisfied task.addOnSuccessListener(activity, new OnSuccessListener&lt;LocationSettingsResponse&gt;() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { // Location settings are satisfied, no need to take any action Log.i(TAG, "Location settings satisfied"); } }); task.addOnFailureListener(activity, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof ResolvableApiException){ // Location settings are not satisfied, display a dialog to the user // requesting the settings to be enabled Log.e(TAG, "Location settings not satisfied. Attempting to resolve..."); try{ ResolvableApiException resolvable = (ResolvableApiException) e; // Show the dialog resolvable.startResolutionForResult(activity, 1); } catch (IntentSender.SendIntentException sendException){ // Ignore the error. } } } }); } /** * Determines if location updates are currently active or not * * @return true if receiving location updates, false if not. */ public boolean isReceivingUpdates(){ return mIsReceivingUpdates; } /** * Stops location updates from being received. * * This should be called in the calling Activity's onPause() method so * that location updates don't continue in the background when the user * navigates away from the app. */ public void stopLocationUpdates(){ if (mLocationCallback != null) { mLocationClient.removeLocationUpdates(mLocationCallback); mIsReceivingUpdates = false; Log.i(TAG, "Location updates removed"); } } /** * Resumes location updates if they have previously been set up * * This should be called in the calling Activity's onResume() method if * you want your app to continue to receive location updates when it resumes * * @see UserLocationUtility#stopLocationUpdates() */ @SuppressLint("MissingPermission") public void resumeLocationUpdates(){ if (mLocationCallback != null) { mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null); mIsReceivingUpdates = true; Log.i(TAG, "Location updates resumed"); } } /** * Provides a way for a calling Activity to set or change the default parameters of * the LocationRequest object to suit its needs. * * @param interval Set the desired interval for active location updates, in milliseconds. * @param fastestInterval Explicitly set the fastest interval for location updates, in * milliseconds. This controls the fastest rate at which your * application will receive location updates. * @param priority Set the priority of the request. Use with a priority constant such as * LocationRequest.PRIORITY_HIGH_ACCURACY. No other values are accepted. */ public void setLocationRequestParams(long interval, long fastestInterval, int priority){ if (mLocationRequest == null) { mLocationRequest = new LocationRequest(); } mLocationRequest.setInterval(interval); mLocationRequest.setFastestInterval(fastestInterval); mLocationRequest.setPriority(priority); } /** * Returns a List object containing the address information for the supplied * Location object. Will be null if no address found. The caller should * implement a UserLocationCallback to receive and handle the result. * * @param location A Location object containing latitude and longitude. * @param callback An interface which must be implemented by the caller in order to * receive the results of the request. */ public void getAddressList(Location location, UserLocationCallback callback){ mGeocoder = new Geocoder(mContext, Locale.getDefault()); List&lt;Address&gt; addressList = null; try { addressList = mGeocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1); // We only want one address to be returned. } catch (IOException e) { // Catch network or other IO problems callback.onFailedRequest("Geocoder not available"); return; } catch (IllegalArgumentException e) { // Catch invalid latitude or longitude values callback.onFailedRequest("Invalid latitude or longitude"); return; } // Handle case where no address is found if (addressList == null || addressList.size() == 0) { callback.onFailedRequest("No address found"); } else { // Return the address list callback.onAddressResult(addressList); } } /** * Returns a String containing the requested address element or null if not found * * @param elementCode A package-defined int constant representing the specific * address element to return. * @param location A Location object containing a latitude and longitude. * * @return String containing the requested address element if found, a reason for * failure if necessary or null if address element doesn't exist. */ public String getAddressElement(int elementCode, Location location){ mGeocoder = new Geocoder(mContext, Locale.getDefault()); List&lt;Address&gt; addressList; Address address; String elementString = null; try { addressList = mGeocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1); // We only want one address to be returned. } catch (IOException e) { // Catch network or other IO problems return "Geocoder not available. Check network connection."; } catch (IllegalArgumentException e) { // Catch invalid latitude or longitude values return "Invalid latitude or longitude"; } // Handle case where no address is found if (addressList == null || addressList.size() == 0){ return "Sorry, no address found for this location"; } else { // Create the Address object from the address list address = addressList.get(0); } // Get the specific address element requested by the caller switch (elementCode){ case AddressCodes.ADMIN_AREA: elementString = address.getAdminArea(); break; case AddressCodes.CITY_NAME: elementString = address.getLocality(); break; case AddressCodes.COUNTRY_CODE: elementString = address.getCountryCode(); break; case AddressCodes.COUNTRY_NAME: elementString = address.getCountryName(); break; case AddressCodes.FEATURE_NAME: elementString = address.getFeatureName(); break; case AddressCodes.FULL_ADDRESS: elementString = address.toString(); break; case AddressCodes.PHONE_NUMBER: elementString = address.getPhone(); break; case AddressCodes.POST_CODE: elementString = address.getPostalCode(); break; case AddressCodes.PREMISES: elementString = address.getPremises(); break; case AddressCodes.STREET_ADDRESS: elementString = address.getThoroughfare(); break; case AddressCodes.SUB_ADMIN_AREA: elementString = address.getSubAdminArea(); break; case AddressCodes.SUB_THOROUGHFARE: elementString = address.getSubThoroughfare(); break; default: elementString = "Invalid element code"; break; } return elementString; } } </code></pre> <p>And here's the UserLocationCallback interface...</p> <pre><code>public interface UserLocationCallback { void onLocationResult(Location location); void onAddressResult(List&lt;Address&gt; addressList); void onFailedRequest(String result); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T20:47:09.463", "Id": "201615", "Score": "1", "Tags": [ "java", "android" ], "Title": "Utility Class for location functionality on Android using Google Play Services FusedLocationProviderClient API" }
201615
<p>I needed to create a JSON file from a couple of MySQL tables to migrate some recipes from wordpress. This was my first time writing a script in python and would like to get some feedback on what I could have done better. I come from a Javascript background.</p> <pre><code>import mysql.connector import json cnx = mysql.connector.connect( database='somedb', user='root', password='root', host='localhost' ) cnx1 = mysql.connector.connect( database='somedb', user='root', password='root', host='localhost' ) cursor = cnx.cursor(); cursor1 = cnx1.cursor(); query = "SELECT a.recipe_id, a.recipe_item_type, b.meta_key, b.meta_value, b.recipe_item_id FROM wp_simmer_recipe_items a, wp_simmer_recipe_itemmeta b WHERE a.recipe_item_id = b.recipe_item_id GROUP BY a.recipe_item_id" query1 = "SELECT * FROM wp_simmer_recipe_itemmeta WHERE recipe_item_id=(%s)" cursor.execute(query) rs = cursor.fetchall() data = {} for row in rs: if row[1] == 'instruction': cursor1.execute(query1, (row[4],)) insD = cursor1.fetchall() for instruction in insD: if instruction[2] != 'is_heading': data.setdefault(row[0], {'instructions':[], 'ingredients': []})['instructions'].append(instruction[3]); else: cursor1.execute(query1, (row[4],)) rd = cursor1.fetchall() ingredient = {} for itemMeta in rd: ingredient[itemMeta[2]] = itemMeta[3] data.setdefault(row[0], {'ingredients': [], 'instructions': []})['ingredients'].append(ingredient) with open('data.json', 'w') as outfile: json.dump(data, outfile, sort_keys=True, indent=4) cursor1.close() cnx1.close() cursor.close() cnx.close() </code></pre>
[]
[ { "body": "<h2>Preface</h2>\n\n<p>For this review, we shall need to refer to the <a href=\"https://plugins.trac.wordpress.org/browser/simmer/tags/1.3.11/core/class-simmer-installer.php#L176\" rel=\"nofollow noreferrer\">database schema for the WordPress Simmer plugin</a>:</p>\n\n<blockquote>\n<pre><code>if ( $i...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T21:46:31.963", "Id": "201617", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "mysql", "json" ], "Title": "Using Python to create a JSON file of recipes from MySQL" }
201617
<p>I was looking at <a href="https://stackoverflow.com/a/37157558/2036035">this answer</a> on SO to handle units in java. The concept was interesting to me, except I didn't like that it had to be per object that had mass, instead of encapsulating a <code>Mass</code> class on its own so the pattern need not be repeated. This is what I came up with. </p> <pre><code>public class Main { public static void main(String args[]){ Mass x = Mass.from_oz(2.3); System.out.println("x in kg: " + x.get_kg()); System.out.println("x in oz: " + x.get_oz()); Mass y = Mass.from_lb(1.2); System.out.println("y in kg: " + y.get_kg()); System.out.println("y in lb: " + y.get_lb()); Mass z = Mass.add(x, y); System.out.println("x + y in kg: " + z.get_kg()); z.add(Mass.from_kg(2.0)); System.out.println("x + y + 2.0kg in kg: " + z.get_kg()); } } public class Mass{ private double mass; private static double LB_PER_KG = 2.20462; private static double OZ_PER_LB = 16; private static double lb_to_kg(double value){ return value * (1/LB_PER_KG); } private static double kg_to_lb(double value){ return value * (LB_PER_KG); } private static double kg_to_oz(double value){ return value * (LB_PER_KG*OZ_PER_LB); } private static double oz_to_kg(double value){ return value * (1/(LB_PER_KG*OZ_PER_LB)); } public double get_kg(){ return this.mass; } public double get_lb(){ return kg_to_lb(this.mass); } public double get_oz(){ return kg_to_oz(this.mass); } public void set_kg(double value){ this.mass = value; } public void set_lb(double value){ this.mass = lb_to_kg(value); } public void set_oz(double value){ this.mass = oz_to_kg(value); } private Mass(double value){ set_kg(value); } public static Mass from_kg(double value){ return new Mass(value); } public static Mass from_lb(double value){ return new Mass(lb_to_kg(value)); } public static Mass from_oz(double value){ return new Mass(oz_to_kg(value)); } public Mass add(Mass rhs){ this.mass += rhs.mass; return this; } public Mass sub(Mass rhs){ this.mass -= rhs.mass; return this; } public Mass div(Mass rhs){ this.mass *= rhs.mass; return this; } public Mass mul(Mass rhs){ this.mass /= rhs.mass; return this; } public static Mass add(Mass lhs, Mass rhs){ return new Mass(lhs.mass).add(rhs); } public static Mass sub(Mass lhs, Mass rhs){ return new Mass(lhs.mass).sub(rhs); } public static Mass mul(Mass lhs, Mass rhs){ return new Mass(lhs.mass).mul(rhs); } public static Mass div(Mass lhs, Mass rhs){ return new Mass(lhs.mass).div(rhs); } } </code></pre> <p>Looking for any criticism, in addition to answers to these questions:</p> <ul> <li><p>am I doing class arithmetic in java right? It doesn't have overloading of operators, so I'm not sure what the convention is for arithmetic. </p></li> <li><p>I didn't use lower camel case for the unit part of functions and variables, despite lower camel case being the convention, I felt it was harder to see toKg or toKG especially when this theoretically could be used with different units where Nm and nm would be two different things. </p></li> <li><p>is there a better way to manage the conversion functions, seem like I have to add two every time I add a new unit? what about units that are power of 10 convertible like for kg vs g? Is there a special pattern I could employ there (eg kg, g, mg, etc...)? </p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T00:24:55.673", "Id": "388281", "Score": "1", "body": "`Mass/Mass` would be unitless, `Mass*Mass` would be in \\$ kg^2 \\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T02:12:43.847", "Id": "3882...
[ { "body": "<p>For just <code>Mass</code>, I would define some constants.</p>\n\n<pre><code>public final static Mass kg = new Mass(1);\npublic final static Mass lb = new Mass(1/2.2, kg);\npublic final static Mass oz = new Mass(1/16.0, lb);\n</code></pre>\n\n<p>And define your conversions with the “to” (and “from...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T21:50:13.423", "Id": "201618", "Score": "1", "Tags": [ "java", "object-oriented", "unit-conversion" ], "Title": "Unit of measure class for mass in java" }
201618
<p>I am starting to build up my portfolio, so I am starting to build projects whenever an idea pops up in my head. So, I decided to build an app that helps you decide what to do. Basically how it works is that you put some different tasks to do in a textbook and it places each task in an array, after you tap on the add button. Once you tap on the decide button the app uses a random integer value to select a random index in the array, and that is how it picks a random task. I would really appreciate and comments, suggestions, and improvements.</p> <pre><code>import UIKit class ViewController: UIViewController, UITextFieldDelegate { //Array that holds all of the users decisions var listOfDecisions: [String] = [] //Holds what is written in the text field var userText : String = " " //Random number var randomNumber : Int = 0 //UI Elements @IBOutlet weak var textInput: UITextField! @IBOutlet weak var youShouldLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() //Makes keyboard appear when input box is tapped on self.textInput.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Makes keyboard disappear when touched outside of the keyboard override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { self.view.endEditing(true) } //Makes the keyboard disappear when the rerurn key is pressed func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool { textInput.resignFirstResponder() return true } //This is the add button @IBAction func addButton(_ sender: Any) { appendText() } @IBAction func decideButton(_ sender: Any) { //If statement is used to make sure that the user does not proceed without entering anything if (listOfDecisions.isEmpty){ // create the alert let alert = UIAlertController(title: "Error", message: "You did not add anything!", preferredStyle: UIAlertControllerStyle.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) } else { makeDecision() } } //Appends the text to the array func appendText () { userText = textInput.text! listOfDecisions.append(userText) print(userText) textInput.text = " " } //Pick a random index in the array and updates the UI func makeDecision () { randomNumber = Int (arc4random_uniform(UInt32(listOfDecisions.count))) youShouldLabel.text = listOfDecisions[randomNumber] } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T22:13:58.667", "Id": "388273", "Score": "4", "body": "Why don't you use the app to figure out what to do to the app so that you can find more things to do to the app so that it can suggest more things to do?" }, { "ContentLi...
[ { "body": "<p>The instance variables</p>\n\n<pre><code>var userText : String = \" \"\nvar randomNumber : Int = 0\n</code></pre>\n\n<p>are not needed: <code>userText</code> is only used within <code>func appendText()</code>,\nand <code>randomNumber</code> is only used within <code>func makeDecision()</code>.\nBo...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-13T22:12:09.017", "Id": "201622", "Score": "4", "Tags": [ "array", "swift", "ios", "uikit" ], "Title": "\"What To Do\" App" }
201622
<p>I'm running into a large bottleneck in my program that takes hours to perform. </p> <p>I have a Dataframe that is very large. I need to take the columns of the Dataframe and create new columns within same Dataframe. The new columns need to grouped by a specific date once grouped they are ranked. After they are ranked they are divided by the total number of values in that day (this number is stored in counts_date). This gives me a range of 0-1. The dataframe is a mulitindex with date as the level 0 and a unique id is level 1.</p> <p>Is there a way to do this so I don't have to do it column by column and still create new columns?</p> <pre><code>df=pd.read_hdf('data.h5') ranks2=list(df.columns.values) for i in ranks2: df[i+'_rank']=df.groupby('date')[i].rank() for i in ranks2: df[i+'_rank']=df[i+'_rank']/df['counts_date'] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T11:13:24.690", "Id": "388330", "Score": "1", "body": "We can help you with this, but only after you add in sufficient context. Please take a look at the [help/on-topic] and [How to get the best value out of Code Review - Asking Ques...
[ { "body": "<p>I don't know if I fully understand the end goal, it's difficult to tell without some sample data, however there are certainly better ways to make this call.</p>\n\n<p>I noticed the manipulations over each column could be simplified to a Pandas <a href=\"https://pandas.pydata.org/pandas-docs/stable...
{ "AcceptedAnswerId": "201637", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T00:00:11.127", "Id": "201623", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "Create new columns using groupby in pandas" }
201623
<p>I got this program that I am working on and in it, I got a section that has a try statement and two error except statements. </p> <pre><code>try: ... if ...: raise SyntaxError except SyntaxError: ... except ValueError: ... </code></pre> <p>The thing is that the SyntaxErrors are technically ValueErrors, but the errors occur for different reasons, therefore need different code to solve/get around the problem. So in order to prevent the code in all the "excepts" from being executed, I had to separate/make the type of Errors different. Is it okay to do that even though the SyntaxErrors are techincally ValueErrors, that I label them as SyntaxErrors? Or is there a method in solving this problem?</p> <p>Here is the code of the program:</p> <pre><code>from datetime import datetime today = datetime(2019, 1, 1).date() this_year = 2019 last_year = this_year - 1 text = ["Dec 31 ", "@@@@@@@@@@@@@@@@@@@@@Dec 31 "] for line in text: date_str = line try: date = datetime.strptime(date_str + str(this_year), "%b %d %Y").date() if date &gt; today: raise SyntaxError print("+", date) except SyntaxError: date = datetime.strptime(date_str + str(last_year), "%b %d %Y").date() print("-", date) except ValueError: print("abnormality") continue </code></pre>
[]
[ { "body": "<p>Obtaining a date that is in the future is in no way a \"syntax error\", and it would be inappropriate to raise a <code>SyntaxError</code>. Instead of abusing the exception-handling mechanism, you should just use a conditional.</p>\n\n<pre><code>for date_str in text:\n try:\n date = date...
{ "AcceptedAnswerId": "201639", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T00:34:09.603", "Id": "201624", "Score": "2", "Tags": [ "python", "python-3.x", "parsing", "datetime", "error-handling" ], "Title": "Parsing date strings, inferring the year such that the date is not in the future" }
201624
<p>Okay, this will most likely be the last post I make for Singe Linked List unless significant revision is needed. This post following from <a href="https://codereview.stackexchange.com/questions/201340/generic-single-linked-list-with-smart-pointers-follow-up-part-2">here</a>.</p> <p>Shout out to @hoffmale for showing me the ways of the force. </p> <p>Here is the header file:</p> <pre><code>#ifndef SINGLELINKEDLIST_h #define SINGLELINKEDLIST_h template &lt;class T&gt; class SingleLinkedList { private: struct Node { T data; std::unique_ptr&lt;Node&gt; next = nullptr; template&lt;typename... Args, typename = std::enable_if_t&lt;std::is_constructible&lt;T, Args&amp;&amp;...&gt;::value&gt;&gt; explicit Node(std::unique_ptr&lt;Node&gt;&amp;&amp; next, Args&amp;&amp;... args) noexcept(std::is_nothrow_constructible&lt;T, Args&amp;&amp;...&gt;::value) : data{ std::forward&lt;Args&gt;(args)... }, next{ std::move(next) } {} // disable if noncopyable&lt;T&gt; for cleaner error msgs explicit Node(const T&amp; x, std::unique_ptr&lt;Node&gt;&amp;&amp; p = nullptr) : data(x) , next(std::move(p)) {} // disable if nonmovable&lt;T&gt; for cleaner error msgs explicit Node(T&amp;&amp; x, std::unique_ptr&lt;Node&gt;&amp;&amp; p = nullptr) : data(std::move(x)) , next(std::move(p)) {} }; std::unique_ptr&lt;Node&gt; head = nullptr; Node* tail = nullptr; void do_pop_front() { head = std::move(head-&gt;next); } public: // Constructors SingleLinkedList() = default; // empty constructor SingleLinkedList(SingleLinkedList const &amp;source); // copy constructor // Rule of 5 SingleLinkedList(SingleLinkedList &amp;&amp;move) noexcept; // move constructor SingleLinkedList&amp; operator=(SingleLinkedList &amp;&amp;move) noexcept; // move assignment operator ~SingleLinkedList(); // Overload operators SingleLinkedList&amp; operator=(SingleLinkedList const &amp;rhs); // Create an iterator class class iterator; iterator begin(); iterator end(); iterator before_begin(); // Create const iterator class class const_iterator; const_iterator cbegin() const; const_iterator cend() const; const_iterator begin() const; const_iterator end() const; const_iterator before_begin() const; const_iterator cbefore_begin() const; // Memeber functions void swap(SingleLinkedList &amp;other) noexcept; bool empty() const { return head.get() == nullptr; } int size() const; template&lt;typename... Args&gt; void emplace_back(Args&amp;&amp;... args); template&lt;typename... Args&gt; void emplace_front(Args&amp;&amp;... args); template&lt;typename... Args&gt; iterator emplace(const_iterator pos, Args&amp;&amp;... args); void push_front(const T &amp;theData); void push_front(T &amp;&amp;theData); iterator insert_after(const_iterator pos, const T&amp; theData); iterator insert_after(const_iterator pos, T&amp;&amp; theData); void clear(); void pop_front(); void pop_back(); iterator erase_after(const_iterator pos); bool search(const T &amp;x); }; template &lt;class T&gt; class SingleLinkedList&lt;T&gt;::iterator { Node* node = nullptr; bool before_begin = false; public: friend class SingleLinkedList&lt;T&gt;; using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T * ; using reference = T &amp; ; iterator(Node* node = nullptr, bool before = false) : node{ node }, before_begin{ before } {} bool operator!=(iterator other) const noexcept; bool operator==(iterator other) const noexcept; T&amp; operator*() const { return node-&gt;data; } T&amp; operator-&gt;() const { return &amp;node-&gt;data; } iterator&amp; operator++(); iterator operator++(int); }; template &lt;class T&gt; class SingleLinkedList&lt;T&gt;::const_iterator { Node* node = nullptr; bool before_begin = false; public: friend class SingleLinkedList&lt;T&gt;; using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = const T * ; using reference = const T &amp; ; const_iterator() = default; const_iterator(Node* node, bool before = false) : node{ node }, before_begin{ before } {} operator const_iterator() const noexcept { return const_iterator{ node }; } bool operator!=(const_iterator other) const noexcept; bool operator==(const_iterator other) const noexcept; const T&amp; operator*() const { return node-&gt;data; } const T&amp; operator-&gt;() const { return &amp;node-&gt;data; } const_iterator&amp; operator++(); const_iterator operator++(int); }; template &lt;class T&gt; SingleLinkedList&lt;T&gt;::SingleLinkedList(SingleLinkedList&lt;T&gt; const &amp;source) { for (Node* loop = source.head.get(); loop != nullptr; loop = loop-&gt;next.get()) { emplace_back(loop-&gt;data); } } template &lt;class T&gt; SingleLinkedList&lt;T&gt;::SingleLinkedList(SingleLinkedList&lt;T&gt;&amp;&amp; move) noexcept { move.swap(*this); } template &lt;class T&gt; SingleLinkedList&lt;T&gt;&amp; SingleLinkedList&lt;T&gt;::operator=(SingleLinkedList&lt;T&gt; &amp;&amp;move) noexcept { move.swap(*this); return *this; } template &lt;class T&gt; SingleLinkedList&lt;T&gt;::~SingleLinkedList() { clear(); } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::clear() { while (head) { do_pop_front(); } } template &lt;class T&gt; SingleLinkedList&lt;T&gt;&amp; SingleLinkedList&lt;T&gt;::operator=(SingleLinkedList const &amp;rhs) { SingleLinkedList copy{ rhs }; swap(copy); return *this; } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::swap(SingleLinkedList &amp;other) noexcept { using std::swap; swap(head, other.head); swap(tail, other.tail); } template &lt;class T&gt; int SingleLinkedList&lt;T&gt;::size() const { int size = 0; for (auto current = head.get(); current != nullptr; current = current-&gt;next.get()) { size++; } return size; } template &lt;class T&gt; template &lt;typename... Args&gt; void SingleLinkedList&lt;T&gt;::emplace_back(Args&amp;&amp;... args) { std::unique_ptr&lt;Node&gt; newnode = std::make_unique&lt;Node&gt;(std::forward&lt;Args&gt;(args)...); if (!head) { head = std::move(newnode); tail = head.get(); } else { tail-&gt;next = std::move(newnode); tail = tail-&gt;next.get(); } } template &lt;class T&gt; template &lt;typename... Args&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::emplace(const_iterator pos, Args&amp;&amp;... args) { if (pos.before_begin) { emplace_front(std::forward&lt;Args&gt;(args)...); return begin(); } if (pos.node-&gt;next) { pos.node-&gt;next = std::make_unique&lt;Node&gt;(std::move(pos.node-&gt;next), std::forward&lt;Args&gt;(args)...); // Creating a new node that has the old next pointer with the new value and assign it to the next pointer of the current node return { pos.node-&gt;next.get() }; } } template &lt;class T&gt; template &lt;typename... Args&gt; void SingleLinkedList&lt;T&gt;::emplace_front(Args&amp;&amp;... args) { head = std::make_unique&lt;Node&gt;(std::move(head), std::forward&lt;Args&gt;(args)...); if (!tail) tail = head.get(); // update tail if list was empty before } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::push_front(const T &amp;theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(theData); newNode-&gt;next = std::move(head); head = std::move(newNode); if (!tail) { tail = head.get(); } } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::push_front(T &amp;&amp;theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(std::move(theData)); newNode-&gt;next = std::move(head); head = std::move(newNode); if (!tail) { tail = head.get(); } } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::insert_after(const_iterator pos, const T&amp; theData) { return emplace(pos, theData); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::insert_after(const_iterator pos, T&amp;&amp; theData) { return emplace(pos, std::move(theData)); } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::pop_front() { if (empty()) { throw std::out_of_range("List is Empty!!! Deletion is not possible."); } do_pop_front(); } template &lt;class T&gt; void SingleLinkedList&lt;T&gt;::pop_back() { if (!head) return; auto current = head.get(); Node* previous = nullptr; while (current-&gt;next) { previous = current; current = current-&gt;next.get(); } if (previous) { previous-&gt;next = nullptr; } else { head = nullptr; } tail = previous; previous-&gt;next = nullptr; } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::erase_after(const_iterator pos) { if (pos.before_begin) { pop_front(); return begin(); } if (pos.node &amp;&amp; pos.node-&gt;next) { pos.node-&gt;next = std::move(pos.node-&gt;next-&gt;next); return { pos.node-&gt;next.get() }; } return end(); } template &lt;class T&gt; bool SingleLinkedList&lt;T&gt;::search(const T &amp;x) { return std::find(begin(), end(), x) != end(); } template &lt;class T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream &amp;str, SingleLinkedList&lt;T&gt;&amp; list) { for (auto const&amp; item : list) { str &lt;&lt; item &lt;&lt; "\t"; } return str; } // Iterator Implementaion//////////////////////////////////////////////// template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator&amp; SingleLinkedList&lt;T&gt;::iterator::operator++() { if (before_begin) before_begin = false; else node = node-&gt;next.get(); return *this; } template&lt;typename T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template&lt;typename T&gt; bool SingleLinkedList&lt;T&gt;::iterator::operator==(iterator other) const noexcept { return node == other.node &amp;&amp; before_begin == other.before_begin; } template&lt;typename T&gt; bool SingleLinkedList&lt;T&gt;::iterator::operator!=(iterator other) const noexcept { return !(*this == other); } template&lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::begin() { return head.get(); } template&lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::end() { return {}; } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::iterator SingleLinkedList&lt;T&gt;::before_begin() { return { head.get(), true }; } // Const Iterator Implementaion//////////////////////////////////////////////// template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator&amp; SingleLinkedList&lt;T&gt;::const_iterator::operator++() { if (before_begin) before_begin = false; else node = node-&gt;next.get(); return *this; } template&lt;typename T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::const_iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template&lt;typename T&gt; bool SingleLinkedList&lt;T&gt;::const_iterator::operator==(const_iterator other) const noexcept { return node == other.node &amp;&amp; before_begin == other.before_begin; } template&lt;typename T&gt; bool SingleLinkedList&lt;T&gt;::const_iterator::operator!=(const_iterator other) const noexcept { return !(*this == other); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::begin() const { return head.get(); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::end() const { return {}; } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::cbegin() const { return begin(); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::cend() const { return end(); } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::before_begin() const { return { head.get(), true }; } template &lt;class T&gt; typename SingleLinkedList&lt;T&gt;::const_iterator SingleLinkedList&lt;T&gt;::cbefore_begin() const { return before_begin(); } #endif /* SingleLinkedList_h*/ </code></pre> <p>Here is the main.cpp file:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;memory&gt; #include &lt;utility&gt; #include &lt;random&gt; #include &lt;stdexcept&gt; #include &lt;iosfwd&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; #include &lt;ostream&gt; #include "SingleLinkedList.h" #include "DoubleLinkedList.h" int main(int argc, const char * argv[]) { /////////////////////////////////////////////////////////////////////// ///////////////////////////// Single Linked List ////////////////////// /////////////////////////////////////////////////////////////////////// SingleLinkedList&lt;int&gt; obj; obj.emplace_back(2); obj.emplace_back(4); obj.emplace_back(6); obj.emplace_back(8); obj.emplace_back(10); std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------displaying all nodes---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"----------------Inserting At Start----------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.push_front(50); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"-------------inserting at particular--------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.insert_after(obj.cbegin(),60); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout &lt;&lt; "\n--------------------------------------------------\n"; std::cout &lt;&lt; "-------------Get current size ---=--------------------"; std::cout &lt;&lt; "\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.size() &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"----------------deleting at start-----------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop_front(); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"----------------deleting at end-----------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop_back(); std::cout &lt;&lt; obj &lt;&lt; "\n"; std::cout&lt;&lt;"\n----------------------------------------------------------\n"; std::cout&lt;&lt;"--------------Deleting after particular position--------------"; std::cout&lt;&lt;"\n-----------------------------------------------------------\n"; obj.erase_after(obj.cend()); std::cout &lt;&lt; obj &lt;&lt; "\n"; obj.search(8) ? printf("yes"):printf("no"); std::cout &lt;&lt; "\n--------------------------------------------------\n"; std::cout &lt;&lt; "--------------Testing copy----------------------------"; std::cout &lt;&lt; "\n--------------------------------------------------\n"; SingleLinkedList&lt;int&gt; obj1 = obj; std::cout &lt;&lt; obj1 &lt;&lt; "\n"; std::cin.get(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T02:23:54.010", "Id": "388288", "Score": "0", "body": "Nit: You've got your `operator const_iterator()` on the wrong class! I'm rather amazed that the compiler didn't warn about this. ...Ah, it's because the class is a template, so a...
[ { "body": "<p>Some nitpicks:</p>\n\n<ul>\n<li><p>Comments are still confusing/distracting</p></li>\n<li><p><code>const_iterator::operator const_iterator()</code> should be moved to <code>iterator</code> instead (it doesn't make sense to convert a <code>const_iterator</code> to a <code>const_iterator</code>). Al...
{ "AcceptedAnswerId": "201628", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T01:51:59.587", "Id": "201627", "Score": "1", "Tags": [ "c++", "linked-list", "pointers" ], "Title": "Generic Single Linked List with smart pointers follow up part 3" }
201627
<p>I'm going to screw around with visualizing <a href="http://oeis.org/A005132" rel="nofollow noreferrer">Recamán's Sequence</a>, but want to have a good sequence generator to generate the sequence before I start. I want to use a lazy generator for my actual application, but decided to make a strict version first since it will likely be simpler.</p> <p>This is what I ended up with. It works (verified against the OEIS), but is <em>quite</em> verbose. I don't <em>technically</em> require <code>seen</code>, but doing constant linear searching over <code>acc</code> would likely be unacceptable. I'm just looking for broad suggestions on how this can be improved, because while it's fairly fast (it can find the first million numbers in ~2 seconds on my potato), it's rather ugly.</p> <p>I know though that I can make use of transients here, but they're easy enough to add afterwards that that's not a big deal.</p> <p>Any suggestions would be appreciated, because I feel like I'm missing something obvious.</p> <pre><code>(defn strict-recamans-sequence [max-n] (let [c-last #(get % (dec (count %)))] (loop [n 1 seen #{} acc [0]] (if (&gt; n max-n) acc (let [prev (c-last acc) back (- prev n) new-n (if (and (pos? back) (not (seen back))) back (+ prev n))] (recur (inc n) (conj seen new-n) (conj acc new-n))))))) </code></pre>
[]
[ { "body": "<p>If you want a lazy sequence, this may be a good example of <a href=\"https://github.com/cloojure/tupelo#generator-functions-for-lazy-sequences-a-la-python\" rel=\"nofollow noreferrer\">using Python-style generator functions</a>. An example:</p>\n\n<pre><code>(defn concat-gen ; concat a list of...
{ "AcceptedAnswerId": "201651", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T03:48:12.267", "Id": "201633", "Score": "1", "Tags": [ "clojure" ], "Title": "Recamán Sequence (A005132)" }
201633
<p>The following C# code is written to fetch the Categories data from SQL Server Database using Asynchronous Task for <code>HttpGet</code>. The Dapper library is used as ORM.</p> <p>I need help to identify whether the Async Task implementation is correct or any better way to implement.</p> <p><strong>CategoriesController.cs</strong></p> <pre><code>public class CategoriesController : Controller { [HttpGet] public async Task&lt;IActionResult&gt; FindList(CategorySearchModel searchModel) { var results = await new CategoryQueryService().FindList(); return GetHandler(results); } IActionResult GetHandler(object results) { return new OkObjectResult(new { results }); } } </code></pre> <p><strong>CategoryQueryService.cs</strong></p> <pre><code>public class CategoryQueryService : BaseQueryDataStoreAsync&lt;CategoryQueryModel&gt; { public override Task&lt;IEnumerable&lt;CategoryQueryModel&gt;&gt; FindList() { const string dbConnectionString = "-- db connection string here --"; const string sql = "SELECT CategoryId, CategoryName FROM Category ORDER BY CategoryName ASC"; return QueryAsync(dbConnectionString, sql); } } </code></pre> <p><strong>CategoryQueryModel.cs</strong></p> <pre><code>public class CategoryQueryModel { public int CategoryId { get; set; } public int CategoryName { get; set; } } </code></pre> <p><strong>BaseQueryDataStoreAsync.cs</strong></p> <pre><code>using Dapper; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; public abstract class BaseQueryDataStoreAsync&lt;T&gt; where T : class { public abstract Task&lt;IEnumerable&lt;T&gt;&gt; FindList(); public async Task&lt;IEnumerable&lt;T&gt;&gt; QueryAsync(string dbConnectionString, string sql) { using (var connection = new SqlConnection(dbConnectionString)) { return await connection.QueryAsync&lt;T&gt;(sql, conditions: null, transaction: null, commandTimeout: null, commandType: null); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T13:53:07.463", "Id": "388349", "Score": "0", "body": "Does this work? Because I doubt `QueryAsync<T>` returns an `IEnumerable<T>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T13:53:47.493", "I...
[ { "body": "<p>Your <code>async/await</code> usage doesn't look fine because the chain it's incomplete. <code>FindList</code> should be <code>async</code> and named <code>FindListAsync</code> and it should <code>await</code> the result from <code>QueryAsync</code>.</p>\n\n<p>There are also a few other things tha...
{ "AcceptedAnswerId": "201689", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T04:28:21.127", "Id": "201634", "Score": "0", "Tags": [ "c#", "async-await", "asp.net-core", "dapper", "asp.net-core-webapi" ], "Title": "Asynchronously fetching data from the database" }
201634
<h2>Where I stand on Lisp</h2> <p>So, Lisp. It's been on my radar for years and I'm finally getting around to learning it. The syntax is foreign but I find I'm having the most difficulty in the areas of semantics and the standard library. The <em>symbol</em> semantics are giving me tremendous trouble for sure, mainly because I find it hard to tell when a <em>symbol</em> is needed as opposed to a <em>value</em>. It probably sounds silly, but I find C pointers to be more intuitive and straightforward, and this is probably owed to the fact that C is exclusively pass-by-value, whereas Lisp is ostensibly both pass-by-value <em>and</em> pass-by-reference, and the semantics therein--<em>which</em> behavior is chosen and <em>when</em>--is unknown to me. For example, why is <code>(1 2 3)</code> inappropriate in a situation where <code>'(1 2 3)</code> and <code>list</code>--assuming its value is <code>(1 2 3)</code>--are perfectly okay? Ostensibly, this is an ambiguity in the syntax and Lisp thinks I'm trying to call a function called <code>1</code>. This type of situation stresses me out precisely because I start thinking of the <em>unknown</em> unknowns--<em>what other situations</em> like this are going to come along and derail me or cause bugs that remain hidden for extended periods of time? I imagine, perhaps without warrant, disasters on par with Undefined Behavior in C.</p> <h2>The code to be reviewed</h2> <p>Long intro, but since this is a code review, I feel it should probably be made clear where I stand so that reviews can take it into account and use it to more effectively communicate the review. I.e. I am a seasoned programmer, I dabble in "language lawyering", and I'm a complete beginner in Lisp.</p> <p>That said, my first Common Lisp project is <em>FizzBuzz</em>. And what better way to get more comfortable with the language than to put my newbie code out for other people to systematically tear apart?</p> <pre><code>#|| divisible() || I don't usually write functions for something as obvious as || "is X divisible by Y", but in this case, I find || || (divisible 15 5) || || easier to read than || || (= 0 (mod 15 5)) || || feel free to refute if you disagree and think this is a || code smell or you know of a more idiomatic way || || Also feel free to say something if you feel || this C-like multi-line style is in bad taste ||# (defun divisible (a b) (= 0 (mod a b))) #|| range() || Copy/pasted from somewhere else. I don't know what cons does || I do understand that the function is recursive || I do not think I would have thought of this on my own ||# (defun range (min max) (when (&lt;= min max) (cons min (range (+ min 1) max)))) (defun fizzbuzz (n) (setf out (string "")) (unless (or (divisible n 3) (divisible n 5)) (return-from fizzbuzz n)) (when (divisible n 3) (setf out (format nil "~d~d" out "Fizz"))) (when (divisible n 5) (setf out (format nil "~d~d" out "Buzz"))) out) (setf 1to100 (range 1 100)) (setf 1to100fb (map 'list #'fizzbuzz 1to100)) (mapcar #'(lambda (str) (format t "~d~%" str)) 1to100fb) </code></pre> <p>I admit, it's hard to break away from imperative programming.</p> <p>The style isn't completely foreign to me, actually. I've already used (and am very much a fan of) style similar to this in C-like languages...</p> <pre><code>while(condition) if(condition) do_something; </code></pre> <p>And I'm already a fan of functional programming...</p> <pre><code>return list.map(x =&gt; (x * x) % 256).filter(x =&gt; x &gt;= 10); </code></pre> <p>So I believe I'm on the right track. Although Dunning-Kruger is always in effect.</p>
[]
[ { "body": "<p><strong>1. <code>Divisible</code> function</strong></p>\n\n<p>It is perfectly fine to define a function like <code>divisible</code> to improve the reading of a program. In general, when defining a function that could be reused, it is a good practice to comment its meaning (and this is encouraged b...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T04:43:45.497", "Id": "201636", "Score": "4", "Tags": [ "beginner", "fizzbuzz", "common-lisp" ], "Title": "FizzBuzz in Common Lisp" }
201636
<p>As an exercise in multithreaded programming, I am trying to implement a basic FIFO task queue. For this, I also implement simplified version of my <code>lock_guard</code>, from STL. Here is the code:</p> <pre><code>#include &lt;mutex&gt; #include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;chrono&gt; #include &lt;optional&gt; namespace cho { template &lt;typename M&gt; struct lock_guard { lock_guard() noexcept = default; lock_guard(M&amp; m) noexcept { mtx = &amp;m; mtx-&gt;lock(); } lock_guard(lock_guard const&amp; rhs) = delete; lock_guard(lock_guard &amp;&amp; rhs) = delete; lock_guard&amp; operator=(lock_guard const&amp; rhs) = delete; lock_guard&amp; operator=(lock_guard &amp;&amp; rhs) = delete; ~lock_guard() { mtx-&gt;unlock(); } private: M *mtx = nullptr; }; template &lt;typename T&gt; struct queue { queue() noexcept = default; ~queue() { queue_node *cur = head; while(cur) { queue_node *tmp = cur; cur = cur-&gt;next; delete tmp; } } void push(T const&amp; elem) { queue_node *node = new queue_node{}; T *new_elem = new T(elem); node-&gt;data = *new_elem; node-&gt;next = nullptr; if(head == tail) one_elem_mtx.lock(); lock_guard&lt;std::mutex&gt; grd(push_mtx); if(head) { tail-&gt;next = node; } else { head = node; } tail = node; one_elem_mtx.unlock(); } auto pop() { if(!head) { return std::optional&lt;T&gt;{std::nullopt}; } if(head == tail) one_elem_mtx.lock(); lock_guard&lt;std::mutex&gt; grd(pop_mtx); std::optional&lt;T&gt; ret{head-&gt;data}; queue_node *c = head; head = head-&gt;next; delete c; one_elem_mtx.unlock(); return ret; } private: struct queue_node { T data = T{}; queue_node *next = nullptr; }; queue_node *head = nullptr; queue_node *tail = nullptr; std::mutex push_mtx = std::mutex{}; std::mutex pop_mtx = std::mutex{}; std::mutex one_elem_mtx = std::mutex{}; }; } struct log_task { void operator()(char const* msg) { std::cout &lt;&lt; "Log: " &lt;&lt; msg &lt;&lt; "#" &lt;&lt; log_id++&lt;&lt; "\n" &lt;&lt; std::flush; } private: static std::size_t log_id; }; std::size_t log_task::log_id = 0; int main() { cho::queue&lt;log_task&gt; log_queue; std::thread task_creator1([&amp;]() { while(true) { using namespace std::chrono_literals; std::this_thread::sleep_for(300ms); log_queue.push(log_task()); } }); std::thread task_creator2([&amp;]() { while(true) { using namespace std::chrono_literals; std::this_thread::sleep_for(500ms); log_queue.push(log_task()); } }); std::thread task_consumer1([&amp;]() { while(true) { using namespace std::chrono_literals; std::this_thread::sleep_for(300ms); std::optional&lt;log_task&gt; t = log_queue.pop(); if(t) t.value()("log_message"); } }); std::thread task_consumer2([&amp;]() { while(true) { using namespace std::chrono_literals; std::this_thread::sleep_for(500ms); std::optional&lt;log_task&gt; t = log_queue.pop(); if(t) t.value()("log_message"); } }); task_creator1.join(); task_creator2.join(); task_consumer1.join(); task_consumer2.join(); return 0; } </code></pre> <p><code>lock_guard</code> and <code>queue</code> implementation lives in my <code>cho</code> namespace. For queue, I only provide basic <code>push</code> and <code>pop</code>, not a production-ready implementation by any means. Then, I implement a logger to be used as test functor in my task queue, called <code>log_task</code>. My queue push and pop operations are guarded by mutexes to avoid messing queue pointers. I want to be able to push tasks to the queue from multiple threads and consume those tasks from multiple threads as well. For this reason, I hold two different mutexes: <code>push_mtx</code> and <code>pop_mtx</code>. On the other hand, I realized that if there is only one element, they can still mess the values since <code>head</code> and <code>tail</code> points to the same node. I added another <code>one_elem_mtx</code> that needs to be locked just on this occasion. </p> <ol> <li><p>What are code smells you can point? I am, I don't know why, not happy with using three mutexes and feel like there is something wrong there.</p></li> <li><p>I played with delays in <code>sleep_for()</code> to try different values and my tests are working fine. But still, can you see any chance of deadlock or livelock?</p></li> <li><p>I've seen many implementations on other questions that use only one mutex. So when one thread pushes, popping threads need to wait as well and vice versa. This seemed like a performance penalty to me but I am not sure. Does my approach indicate a bad design and should I abandon concurrent push/pop?</p></li> </ol>
[]
[ { "body": "<h1><code>lock_guard</code></h1>\n<ul>\n<li><p>The destructor never checks if <code>mtx == nullptr</code>, which will cause problems if <code>lock_guard</code> got default-constructed.</p>\n</li>\n<li><p>The <code>lock_guard(M&amp;)</code> constructor cannot be <code>noexcept</code>, as <code>lock</c...
{ "AcceptedAnswerId": "201744", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T06:10:20.887", "Id": "201640", "Score": "4", "Tags": [ "c++", "multithreading", "queue" ], "Title": "A thread safe task queue implementation using my own lock_guard in C++" }
201640
<p>Im trying to match the pixel spacing between two folders, here matches has 994 keys and it shows that i may take more than a day to compute this. Is there any way i can speed up this operation.</p> <p>the load series function looks like this </p> <pre><code>import SimpleITK as sitk def load_series(path): reader = sitk.ImageSeriesReader() dicom_names = reader.GetGDCMSeriesFileNames(path) reader.SetFileNames(dicom_names) return reader.Execute() import csv bar = ProgressBar() file = open('BenignTest.csv', 'w') writer = csv.writer(file) for item in bar(matches.keys()): for case in matches[item]: load_case = load_series(case) if load_case.GetSpacing() == load_series(item).GetSpacing(): writer.writerow((item , case)) break </code></pre> <p>The matches dictionary looks like this, </p> <pre><code>{'/mnt/sdd1/DSB2017/stage1/0030a160d58723ff36d73f41b170ec21': ['/mnt/sde1/Cancer/128443/01-02-1999-LSS-59120/2-0OPAGELSPLUSD3602.512060.00.11.5-98506', '/mnt/sde1/Cancer/213485/01-02-1999-ACRIN-13247/3-0OPAGELSPLUSLUNG3502.51204026.71.5-85097', '/mnt/sde1/Cancer/206342/01-02-1999-ACRIN-68321/3-0OPAGELSPLUSLUNG3702.51205033.31.5-72233', '/mnt/sde1/Cancer/200209/01-02-2000-CRIN-10216/3-1OPAGELSPLUSLUNG4002.51204026.71.5-42354']...........} </code></pre> <p>Thanks in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T08:02:19.400", "Id": "388316", "Score": "1", "body": "Cross-posted from [Stack Overflow](https://stackoverflow.com/q/51835981/5069029)" } ]
[ { "body": "<p>The simplest improvement that you can do right now is to avoid recomputing the same reference image over and over for each <code>case</code> of an <code>item</code>: just store <code>load_series(item).GetSpacing()</code> before looping over each <code>case</code>.</p>\n\n<p>You can also use <a hre...
{ "AcceptedAnswerId": "201650", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T07:38:34.193", "Id": "201646", "Score": "5", "Tags": [ "python", "performance" ], "Title": "Check for pixel spacing between two folder images" }
201646
<p>I have a simple event that the client sends to the server, the server can then respond saying if it was successful, or if it failed for some reason. </p> <p>The client has to send a auth code, which is inside their config class. Below I attempt to throttle it, allowing 2 attempts, then reloading the config after the 2nd failed attempt.</p> <p>If it still fails 2 more attempts after reloading the config, I throttle it for 60 seconds. If it fails after reloading the config 3 or more times (12 requests), then I just refuse to resend it.</p> <p>Please note that I understand just leaving it and not warning the user why it failed to connect to the server is wrong, but I haven't finished with that code yet, and will adapt later on.</p> <p>I'm just looking to see if its okay, and if I can improve it in any way.</p> <pre><code>public class HandshakeFailedEvent : IIncomingPacketEvent { private static int ATTEMPTS_BEFORE_CONFIG_RELOAD = 2; private static int ATTEMPTS_BEFORE_THROTTLE = 4; private static int SECONDS_TO_THROTTLE = 60; private int _timesFailed; private int _timesSinceReset; public void Process(ICoreContext coreContext, IIncomingPacket packet) { if (packet.GetInteger("error_code") == 1) // WRONG_PASSWORD { CheckForThrottle(coreContext); } // Other error codes may need fixing, not throttling, handle here. coreContext.SocketHandler.SendPacket(new HandshakeRequestComposer(coreContext.ConfigHandler)); } private void CheckForThrottle(ICoreContext coreContext) { _timesFailed++; _timesSinceReset++; if (_timesFailed &gt;= ATTEMPTS_BEFORE_THROTTLE * 3) { // Application.Restart(); return; } if (_timesSinceReset &gt;= ATTEMPTS_BEFORE_CONFIG_RELOAD &amp;&amp; _timesSinceReset &lt; ATTEMPTS_BEFORE_THROTTLE) { coreContext.ConfigHandler.Download(); } else if (_timesSinceReset &gt;= ATTEMPTS_BEFORE_THROTTLE) { Task.Delay(SECONDS_TO_THROTTLE * 1000).ContinueWith((t) =&gt; { _timesSinceReset = 0; }); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-17T14:04:52.693", "Id": "388953", "Score": "0", "body": "You should use a `TimeSpan` instead of integers for `Task.Delay` etc.: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.delay" }, { "ContentLicense...
[ { "body": "<p>Prefixing field members with <code>_</code> is more of an \"old school\" C# approach. It's a preference, I guess, but I think it's not really used anymore.</p>\n\n<p>If the only thing you do with <code>SECONDS_TO_THROTTLE</code> is <code>Task.Wait(SECONDS_TO_THROTTLE * 1000)</code>, then <code>SEC...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T08:07:30.713", "Id": "201649", "Score": "0", "Tags": [ "c#", ".net", "error-handling" ], "Title": "Mechanism to retry failed requests, with throttling" }
201649
<p>I have two tables in my database, which contains a big list of organisations. They are called <code>orgs_main</code> and <code>orgs_sub</code>. This is the structure:</p> <p><strong>orgs_main</strong>:</p> <pre><code>id | code | name | address | ---------------------------- </code></pre> <p><strong>orgs_sub</strong>:</p> <pre><code>id | code | name | address | merged | ------------------------------------- </code></pre> <p><code>orgs_main</code> contains "main" organisations, which are identified by that they have a <code>code</code> starting with "64"</p> <p><code>orgs_sub</code> contains "sub" organisations, which are identified by they don't have a <code>code</code> starting with "64".</p> <p>I need to find all the <strong>sub</strong> organisations, which have matching address to the <strong>main organisations</strong>, and then list them. </p> <p>Example:</p> <p><strong>Broadway Avenue 110</strong> (<code>orgs_main</code>)</p> <ul> <li>Company 1 (<code>orgs_main</code>)</li> <li>Company 2 (<code>orgs_main</code>)</li> <li><p>Company 3 (<code>orgs_main</code>)</p></li> <li><p>Sub company 1 (<code>orgs_sub</code>)</p></li> <li>Sub company 2 (<code>orgs_sub</code>)</li> </ul> <p>The way I am doing this now, is like this:</p> <p><code>MergerController.php</code>:</p> <pre><code>public function merger() { //Select main organisations, that have matching addresses on sub-organisations and that is not already merged together. $MainOrganisations = DB::table("orgs_main AS j") -&gt;selectRaw("DISTINCT j.address, (SELECT COUNT(*) FROM orgs_sub i WHERE i.address = j.address) AS SubCount") -&gt;whereRaw("(SELECT COUNT(*) FROM orgs_sub i WHERE i.address = j.address AND i.merged=0) &gt; 0") -&gt;simplePaginate(10); //Loop through the main companies, so we get all main companies with the same address. foreach($MainOrganisations as $key =&gt; $SameAddress){ $CompaniesSameAddress = DB::table('orgs_main') -&gt;select('name', 'code') -&gt;where('address', $SameAddress-&gt;address) -&gt;where('code', 'LIKE', '64%') -&gt;get(); $SameAddress-&gt;Companies = $CompaniesSameAddress; } //Foreach found Main Organisation Address, list all the sub companies with this address. foreach($MainOrganisations as $key =&gt; $MainOrganisation){ $SubOrganisations = DB::table('orgs_sub') -&gt;select('name', 'code', 'id') -&gt;where('address', $MainOrganisation-&gt;address) -&gt;get(); $MainOrganisation-&gt;SubOrganisations = $SubOrganisations; } //Return the data to our view. $data = [ 'MainOrganisations' =&gt; $MainOrganisations, ]; return $data; } </code></pre> <p>My view file:</p> <p><code>merger.list.blade.php</code>:</p> <pre><code>&lt;table width="100%" class="merger"&gt; @foreach ($MainOrganisations as $Main) &lt;thead&gt; &lt;th&gt;{{ $Main-&gt;address }} &lt;/th&gt; &lt;th&gt; @foreach($Main-&gt;Companies as $Companies) {{$Companies-&gt;name}} (Code: {{ $Companies-&gt;code }}) &lt;br /&gt; @endforeach &lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach($Main-&gt;SubOrganisations as $Sub) &lt;tr&gt; &lt;td&gt;{{ $Sub-&gt;name }}&lt;/td&gt; &lt;td&gt;{{ $Sub-&gt;code }}&lt;/td&gt; &lt;/tr&gt; @endforeach &lt;/tbody&gt; @endforeach &lt;/table&gt; </code></pre> <p>Which shows something like this:</p> <p><a href="https://i.stack.imgur.com/NWGo0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NWGo0.png" alt="enter image description here"></a></p> <p>Any comments or alternatives methods is highly appreciated, as above code does function as intended, but it's quite slow and feel a bit "hackish" to me.</p> <p>Thank you in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-13T09:10:27.397", "Id": "392609", "Score": "0", "body": "Have you seen Eloquent documentation? Do you have relationships defined in the model(s)? What is `merged` field? How are you getting the company lists, do you have power to chang...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T10:50:49.177", "Id": "201658", "Score": "2", "Tags": [ "php", "sql", "laravel" ], "Title": "SQL/PHP Laravel - Looping through records to find relationships" }
201658
<p>What my code do: </p> <ol> <li>Connecting to 30 DB (consistently)</li> <li>Copying DB file to temp.dat</li> <li>Reading temp.dat</li> <li>Writing read data to file</li> </ol> <p>So, it connects 30 times with different databases. This take 6-7 second (on a powerful notebook), but if I run this code on notebook / PC with low hardware specifications these take more than 20 seconds. How can I speed this up?</p> <pre><code>func fileCopyProcedure(ptSource string, ptDest string) { sourceFile, err := os.Open(ptSource) if err != nil { fmt.Println(err) } defer sourceFile.Close() destFile, err := os.Create(ptDest) if err != nil { fmt.Println(err) } defer destFile.Close() _, err = io.Copy(destFile, sourceFile) if err != nil { fmt.Println(err) } err = destFile.Sync() if err != nil { fmt.Println(err) } sourceFileInfo, err := sourceFile.Stat() if err != nil { fmt.Println(err) } destFileInfo, err := destFile.Stat() if err != nil { fmt.Println(err) } if sourceFileInfo.Size() == destFileInfo.Size() { } else { fmt.Println(err) } } func DB_Handler(path string) { var db *sql.DB err := fileCopyProcedure(path, "tmp.dat") if err != nil { fmt.Println(err) } db, err = sql.Open("sqlite3", "tmp.dat") if err != nil { fmt.Println(err) } defer db.Close() rows, err := db.Query("select cr_value, fx_value, orm_value, speend_value, sc_source_value, datainfo, secure_only from cookies") if err != nil { fmt.Println(err) } defer rows.Close() for rows.Next() { var sql_cr_value string var sql_fx_value string var sql_orm_value string var sql_speend_value string var sql_sc_source_value string var sql_datainfo string var sql_secure_only string err = rows.Scan( &amp;sql_cr_value, &amp;sql_fx_value, &amp;sql_orm_value, &amp;sql_speend_value, &amp;sql_sc_source_value, &amp;sql_datainfo, &amp;sql_secure_only, ) if err != nil { fmt.Println(err) } if sql_cr_value != "" &amp;&amp; sql_orm_value != "" &amp;&amp; sql_datainfo != "" { var cprInfo = fmt.Sprintf("%s %s %s %s %s %s\r\n", sql_cr_value, sql_fx_value, sql_orm_value, sql_speend_value, sql_sc_source_value, sql_datainfo, sql_secure_only, ) var hkInfo = fmt.Sprintf("%s\r\n", sql_datainfo, ) wfile, err := os.OpenFile( "data.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600, ) if err != nil { fmt.Println(err) } defer wfile.Close() if _, err = wfile.WriteString(cprInfo); err != nil { fmt.Println(err) } wfile, err = os.OpenFile( "opx.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600, ) if err != nil { fmt.Println(err) } defer wfile.Close() if _, err = wfile.WriteString(hkInfo); err != nil { fmt.Println(err) } } } err = rows.Err() if err != nil { fmt.Println(err) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T13:00:50.077", "Id": "388336", "Score": "0", "body": "Have a question, why you're never return the error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T13:09:53.060", "Id": "388338", "Score"...
[]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T12:37:51.340", "Id": "201660", "Score": "3", "Tags": [ "performance", "mysql", "go" ], "Title": "Exporting tables from 30 databases" }
201660
<p>I am sub-classing an object in python and I need to overload a bunch of the methods with very similar logic, essentially a call to super() and then some additional operations. I want to avoid explicitly writing out each of those overloaded methods in that way, so I implemented a decorator.</p> <p>Is there anything wrong with doing the following:</p> <pre><code>def decorator(function): def wrapper(*args, **kwargs): # Logic + operations here function() # Logic and operations here return wrapper class SubClass(SuperClass): method1 = decorator(SuperClass.method1) method2 = decorator(SuperClass.method2) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Extra logic here </code></pre> <p>Here is my actual implementation:</p> <pre><code>def updates_file(function): """ Decorator to call update file method after super call. """ def wrapper(*args, **kargs): function(*args, **kargs) args[0]._update_file() return wrapper class FileMirroredDeque(deque): __delitem__ = updates_file(deque.__delitem__) __iadd__ = updates_file(deque.__iadd__) __imul__ = updates_file(deque.__imul__) __setitem__ = updates_file(deque.__setitem__) append = updates_file(deque.append) appendleft = updates_file(deque.appendleft) extend = updates_file(deque.extend) extendleft = updates_file(deque.extendleft) insert = updates_file(deque.insert) pop = updates_file(deque.pop) popleft = updates_file(deque.popleft) remove = updates_file(deque.remove) reverse = updates_file(deque.reverse) rotate = updates_file(deque.rotate) def __init__(self, cache_path, maxlen=None, clean=False, file_indent=None): super().__init__((), maxlen) # Initializes the deque as well TODO: Check the implication of this calling __setitem__ self.path = cache_path self._indent = file_indent self._bak_file = None if clean: self._update_file() # Overwrite contents of file. return # Don't import data from file. with open(self.path, 'a+') as f: # Creates file if it doesn't exist f.seek(0, 0) # Seek back to beginning of file for json decode. contents = f.read() try: self.extend(json.loads(contents or "[]")) # initializes internal list with persistent data or empty list. except json.decoder.JSONDecodeError: new_file = os.path.basename(self.path) \ + datetime.datetime.utcnow().strftime("_%Y_%m_%d_%H_%M_%S") + ".bak" new_path = os.path.join(os.path.dirname(self.path), new_file) logger.warning(f"File: {self.path} was not valid JSON. It will be copied to {new_path} and a new " f"file will be created.") shutil.copyfile(self.path, new_path) self._bak_file = new_path def _update_file(self): with open(self.path, 'w') as f: json.dump(list(self), f, indent=self._indent) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T13:04:46.083", "Id": "388337", "Score": "1", "body": "Your decorator is __not__ equivalent to calling `super`. In your case you always refer to the parent class, which is [not the only behaviour of `super`](https://docs.python.org/3...
[ { "body": "<p>I don't think that what you're doing is good style. I think you're adding a lot of extra complexity and places for things to go wrong, or become hard to understand, or whatever. I don't think you lose anything by just making very small methods that call <code>super</code> and your special method. ...
{ "AcceptedAnswerId": "229118", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T12:49:23.933", "Id": "201661", "Score": "12", "Tags": [ "python", "object-oriented", "json", "queue", "meta-programming" ], "Title": "Using decorated methods in a subclass of deque to dump its state to a JSON file" }
201661
<p>I have been playing around in hacker rank with Python these days, and now pulling my hair out on this <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler001" rel="nofollow noreferrer">question</a> to solve the Euler's problem in the least time required.</p> <blockquote> <p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Find the sum of all the multiples of 3 or 5 below N.</p> </blockquote> <p>Without that in mind, I initially wrote the below code:</p> <blockquote> <pre><code>t = int(input()) for a in range(t): n = int(input()) temp=0 for i in range(n): if(i%3==0 or i%5==0): temp+=i print(temp) </code></pre> </blockquote> <p>The above solves most of the test cases except #2 and #3 in HackerRank. On checking the discussion tab, I found out that we have to reduce the time required to avoid timeout as the #2 and #3 test cases inputs big numbers.</p> <p>Can anyone help me to optimize my code further?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T14:58:10.520", "Id": "388367", "Score": "1", "body": "**Code not implemented or not working as intended**: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainabilit...
[ { "body": "<p><code>temp</code> isn't a great name for your accumulator. Call it something like <code>total</code>, which gives a much clearer indication of what role it plays.</p>\n\n<p>First, let's separate the logic from the I/O, to make it easier to test:</p>\n\n<pre><code>def sum_3s_and_5s(n):\n total ...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T14:52:06.453", "Id": "201666", "Score": "-1", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Project Euler Problem 1 with Python 3 ideal solution" }
201666
<h2>Where it shines</h2> <p>FreezeFlame shines in readibility while still maintaining most of the C-like syntax. It also implements a few (Planning on several) operators that are still in testing for other languages.</p> <h2>Reason / TL;DR</h2> <p>I decided to write a new language, partially for the challenge and for the following reasons:</p> <ul> <li>I wanted to implement the pipe operator: <code>|&gt;</code>, the lambda operator: <code>::</code> and the hash operator: <code>#</code>.</li> <li>JavaScript comments were rather jagged, so I replaced <code>/*</code> with <code>@@@</code></li> <li>Accessing prototypes was a pain to type if you used it commonly, so <code>.prototype.</code> got replaced with <code>::</code>. <code>.prototype.</code> will still work. I named it FreezeFlame because it implements two languages and styles.</li> </ul> <h2>Explanation</h2> <p>The language takes after both JavaScript and CoffeeScript in its syntax. A few other things have also been added. The following examples are before and after:</p> <h2>Live demo</h2> <p>Go to <a href="https://nolanlawson.github.io/jison-debugger/" rel="nofollow noreferrer">https://nolanlawson.github.io/jison-debugger/</a> and put the below grammar in the grammar section. Then, put in any of the tests. I chose that tester over <a href="https://zaa.ch/jison/try/" rel="nofollow noreferrer">https://zaa.ch/jison/try/</a> because it showed me the node output. </p> <h3>Array</h3> <p>Before:</p> <pre><code>[1,2,3] </code></pre> <p>After:</p> <pre><code>[1,2,3] </code></pre> <h3>Switch</h3> <p>Before:</p> <pre><code>switch day { when 'tuesday' then { 'tuesday' |&gt; console.log; 1; } else { return 2; } } </code></pre> <p>After:</p> <pre><code>switch(day) { case 'tuesday': console.log('tuesday'); return 1; default: return 2; } </code></pre> <h3>Object</h3> <p>Objects remain untouched from JS syntax.</p> <h3>String</h3> <p>Strings can be both multi line and single line. Before:</p> <pre><code>""" #{ false } """ </code></pre> <p>After:</p> <pre><code>` ${ false } ` </code></pre> <p>Before: " #{ true } " After: <code>${ true }</code></p> <h3>Pipe</h3> <p>Increase readability for a nested function calls. Before:</p> <pre><code>a |&gt; a |&gt; #a </code></pre> <p>After:</p> <pre><code>this.a(a(a)); </code></pre> <h3>Function definition and call</h3> <p>Before:</p> <pre><code>() ~&gt; { console.log(1) } </code></pre> <p>After:</p> <pre><code>function() { return console.log(1); }; </code></pre> <h3>Lambda</h3> <p>Access the prototype quickly. Before:</p> <pre><code>() -&gt; { return String::split; } </code></pre> <p>After:</p> <pre><code>()=&gt; { return String.prototype.split; }; </code></pre> <h3><code>#</code></h3> <p><code>#</code> is equivalent to <code>this</code> or <code>this.</code> Before:</p> <pre><code>() -&gt; { #; } </code></pre> <p>After:</p> <pre><code>()=&gt; { return this; }; </code></pre> <p>Any requests can be put in comments. The following are proposed features:</p> <ul> <li><code>&lt;=&gt;</code>: Spaceship operator. Alias: <code>⇔</code></li> <li><code>↔</code>: Alias for the swap operator</li> <li><code>→</code>: Alias for the function operator (Bound).</li> <li><code>↝</code>: Alias for the function operator (Un-bound).</li> </ul> <p>The following have been implemented:</p> <ul> <li><code>&lt;-&gt;</code>: Swap operator.</li> </ul> <h2>The code (grammar.jison):</h2> <pre><code>%lex %% '@@@'(\s*(?:(?!\@){3,}.)*\s*)'@@@' { return 'COMMENT2' } '@'([^\n]*) { return 'COMMENT1' } '"""'(\s*(?:[^\\]|(\\.)|(?!\'){3,})*\s*)'"""' { s = this.matches[1]; yytext = s return 'STRING2' } "'''"(\s*(?:[^\\]|(\\.)|(?!\'){3,})*\s*)"'''" { s = this.matches[1]; yytext = s return 'STRING2' } '"'((\\.)|(\\\n)|[^\"\n])*'"' { s = this.matches[1]; yytext = s; return 'STRING1'; } "'"((\\.)|(\\\n)|[^\'\n]*)*"'" { s = this.matches[1]; yytext = s; return 'STRING1' } \n+ return 'NL' ([^\S\n]{3})+ return 'INDENT' \t+ return 'INDENT' [^\S\n]+ /* skip whitespace */ [0-9]+ return 'number' 'on' return 'true' 'off' return 'false' 'yes' return 'true' 'class' return 'class' 'no' return 'false' 'true' return 'true' 'false' return 'false' (return\s+) return 'return1' 'null' return 'null' (return) return 'return2' 'finally' return 'finally' 'switch' return 'switch' 'catch' return 'catch' 'when' return 'when' 'else' return 'else' 'then' return 'then' 'for' return 'for' 'var' return 'var' 'try' return 'try' 'if' return 'if' 'isnt' return '!==' 'this' return 'THIS' ([a-zA-Z_][a-zA-Z_0-9]*) return 'name' "|&gt;" return '|&gt;' [-~]\&gt; return 'Glyph' '@@@' return '@@@' '...' return '...' '&gt;&gt;&gt;=' return '&gt;&gt;&gt;=' '&lt;&lt;&lt;=' return '&lt;&lt;&lt;=' '&gt;&gt;&gt;' return '&gt;&gt;&gt;' '&lt;&lt;&lt;' return '&lt;&lt;&lt;' '===' return '===' '!==' return '!==' '&lt;-&gt;' return '&lt;-&gt;' '||' return '||' '!=' return '!=' '==' return '==' '&gt;&gt;' return '&gt;&gt;' '&lt;&lt;' return '&lt;&lt;' '&amp;&amp;' return '&amp;&amp;' '**' return '**' '::' return '::' '|=' return '|=' '+=' return '+=' '/=' return '/=' '-=' return '-=' '&amp;=' return '&amp;=' '++' return '++' '%=' return '%=' '#{' return '#{' '#' return '#' "'" return "'" '"' return '"' ';' return ';' '&gt;' return '&gt;' '&lt;' return '&lt;' '^' return '^' ',' return ',' '(' return '(' ')' return ')' '[' return '[' ']' return ']' '.' return '.' '`' return '`' '%' return '%' ':' return ':' '&amp;' return '&amp;' '@' return '@' '=' return '=' '|' return '|' '+' return '+' '-' return '-' '/' return '/' '*' return '*' '{' return '{' '}' return '}' '?' return '?' &lt;&lt;EOF&gt;&gt; return 'EOF' /lex %right '=' %left '+' '-' %left '*' '/' %start root %% root : Body EOF %{ return $1 }% ; Body : Switch NL "Body" { <span class="math-container">$$ = $1 + $2 + $3 } | Switch | Expression NL OptIndent Body { $$ = $1 + ';' + $2 + $3 + $4 } | Expression | Try NL "Body" { $$ = $1 + $2 + $3 } | Try | For NL Body { $$ = $1 + $2 + $3 } | For | Function OptNewLine Body { $$ = $1 + $2 + $3 } | Function | Object NL Body { $$ = $1 + $2 + $3 } | Object | Class NL Body { $$ = $1 + $2 + $3 } | Class | MultiLineString NL Body { $$ = $1 + $2 + $3 } | MultiLineString | Line NL OptIndent Body { $$ = $1 + $2 + $3 + $4 } | BodyEnd OptNewLine -&gt; $1 + $2 | BodyEnd | { $$ = '' } ; Return : OptIndent return1 Expression OptSemiColon { $$ = $1 + $2 + ' ' + $3 + ';' } | OptIndent return2 OptSemiColon { $$ = $1 + $2 + ';' } | OptIndent Expression OptSemiColon { $$ = $1 + 'return ' + $2 + ';' } ; Class : class Name OptIndent '{' NL INDENT ClassBody OptIndent '}' OptSemiColon { $$</span> = 'class ' + $2 + ' {\n' + $6 + $7 + $8 + '\n};' } ; ClassBody : name ParamDef OptIndent '{' NL INDENT Body OptIndent '}' NL INDENT ClassBody { <span class="math-container">$$ = $1 + $2.split('this.').join`` + ' {' + $2.replace(/^\(/,'').replace(/\)$/,'').split(',').filter(a=&gt;a.includes('this.')).map(a=&gt;a.split(/\s*=\s*/)[0]).map(a=&gt;a+ ' = ' + a.replace(/\s*this\./,'') + ';').join`\n` + $6 + $Body + $8 + '}\n' + $11 + $12 } | name ParamDef OptIndent '{' NL INDENT Body OptIndent '}' NL { $$ = $1 + $2.split('this.').join`` + ' {' + $2.replace(/^\(/,'').replace(/\)$/,'').split(',').filter(a=&gt;a.includes('this.')).map(a=&gt;a.split(/\s*=\s*/)[0]).map(a=&gt;a+ ' = ' + a.replace(/\s*this\./,'') + ';').join`\n` + $6 + $Body + $8 + '}\n' } ; Line : OptIndent Expression OptSemiColon { $$ = $1 + $2 + ';' } ; BodyEnd : Return | INDENT Expression OptSemiColon { $$ = $1 + $2 + ';' } | Expression OptSemiColon -&gt; $1 + ';' ; OptSemiColon : OptSemiColon OptSemiColon | ';' | { $$ = '' } ; Ternary : 'if' Expression 'then' Expression 'else' Expression { $$ = $2 + ' ? ' + $4 + ' : ' + $6 } ; OptNewLine : NL | { $$ = '' } ; OptIndent : INDENT | { $$ = '' } ; OptComma : ',' | { $$ = '' } ; Function : FunctionStart '{' OptNewLine Body OptNewLine OptIndent '}' OptSemiColon { $$ = $1 + ' {\n' + $Body + '\n}' } | FunctionStart '{ OptNewLine }' OptSemiColon { $$ = $1 + '{' + $3 + '}' } ; FunctionStart : ParamDef Glyph %{ switch($2) { case '~&gt;': $$ = 'function' + $1; break; case '-&gt;': $$ = $1 + ' =&gt;'; break; } }% ; Boolean : 'true' -&gt; 'true' | 'false' -&gt; 'false' ; Param : '( )' -&gt; '()' | '(' List ')' -&gt; '(' + $List + ')' ; List : Value ',' List { $$ = $1 + ',' + $3 } | Name ',' List { $$ = $1 + ',' + $3 } | '...' Value ',' List {$$ = '...' + $Value + ',' + $List } | '...' Value { $$ = '...' + $3 } | '...' Name { $$ = '...' + $2 } | Value | Name | Expression {$$ = $1} ; ParamDef : '( )' -&gt; '()' | '(' ParamDefList ')' -&gt; $1 + $2 + $3 ; ParamDefList : Name '... ,' ParamDefList { $$ = $1 + $2 + $3 + $4 } | Name '=' Expression ',' ParamDefList { $$ = $1 + ' = ' + $3 + ', ' + $5 } | '(' Expression ')' | Name ',' ParamDefList { $$ = $1 + $2 + $3 } | Name '...' { $$ = $1 + $2 } | Name '=' Expression { $$ = $1 + ' = ' + $3 } | Name { $$ = $1 } ; Expression : ERRORS | Name '&lt;-&gt;' Name { $$ = `[${$1}, ${$3}] = [${$3}, ${$1}]` } | Name '=' Switch { $$ = $1 + $2 + '(function(){\n ' + $3 + '\n' + '})()' } | OptVar Name '=' Expression {$$ = `${$1.length?$1+' ':''}${$2} = ${$4}` } | Name '=' Expression { $$ = $1 + $2 + $3 } | Name ComboMath Expression { $$ = $1 + $2 + $3 } | Expression Math Expression { $$ = $1 + $2 + $3 } | Expression Math Expression { $$ = $1 + $2 + $3 } | Expression Operator Expression { $$ = $1 + $2 + $3 } | Name '++' { $$ = $1 + $2 } | Name List {$$ = `${$1}(${$2})`} | Name Param {$$ = $1 + $2} | Value 'is' Name {$$ = `${$1} instanceof ${$3}`} | Ternary | Function | '(' Expression ')' { $$ = $1 + $2 + $3 } | For | Switch | Value | Name | Comment | Pipe ; Comment : COMMENT1 { $$ = $1.replace(/^@/, '//') } | COMMENT2 { $$ = $1.replace(/^@@@/, '/*').replace(/@@@/g, '*/'); }- ; Operator : '&amp;&amp;' | '||' | '!==' -&gt; '!==' | '===' -&gt; '===' | '==' | '&gt;=' | '&lt;=' | '!=' ; ComboMath : '|=' | '*=' | '/=' | '%=' | '+=' | '-=' | '&amp;=' | '&gt;&gt;&gt;=' | '&gt;&gt;=' | '&lt;&lt;=' ; Math : '&gt;&gt;&gt;' | '**' | '&lt;&lt;' | '&gt;&gt;' | '&amp;' | '^' | '|' | '+' | '*' | '+' | '-' | '/' | '&lt;' | '&gt;' | '%' ; OptVar : 'var' | { $$ = '' } ; Value : Function | Boolean | Number | Pipe | String | Array | Null ; For : for '(' Expression ';' Expression ';' Expression ')' '{' OptNewLine Body OptNewLine OptIndent '}' OptSemiColon { $$ = $1 + '(' + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10 + $11 + $12 + $13 + $14 } ; LineList : OptIndent Expression ',' OptNewLine LineList { $$ = $1 + $2 + ',\n' + $LineList } | OptIndent Expression { $$ = $1 + $2 } ; Array : '[' OptNewLine ArrList OptNewLine ']' { $$ = $1 + '\n' + $3 + '\n' + $5 } | '[' NL LineList NL ']' { $$ = $1 + '\n' + $3 + '\n' + $5 } | '[ ]' { $$ = '[]' } ; KeyList : Key { $$ = $1 + ': ' + $1 } | Value { $$ = "'" + $1 + "'" + ': ' + $1 } ; Switch : switch Value OptIndent '{' OptIndent NL WhenList OptNewLine OptIndent '}' OptIndent OptSemiColon { $$ = $switch + '(' + $Value + ') {\n' + $WhenList + '};' } | switch Name '{' NL WhenList OptNewLine OptIndent '}' OptSemiColon { $$ = $switch + '(' + $Name + ') {\n' + $WhenList + '};' } ; WhenList : OptIndent when WhenArr then '{' OptNewLine Body OptNewLine OptIndent '}' OptNewLine WhenList { $$ = $OptIndent + ' ' + $WhenArr + ' ' + $Body + '\n' + $WhenList } | OptIndent when WhenArr then '{' OptNewLine Body OptNewLine OptIndent '}' OptNewLine { $$ = $OptIndent + ' ' + $WhenArr + ' ' + $Body + '\n' + $OptIndent + ' break;' } | OptIndent else '{' OptNewLine Body OptNewLine OptIndent '}' { $$ = $OptIndent + 'default: \n' + $Body } ; WhenArr : Expression ',' WhenArr { $$ = 'case ' + $1 + ': \n' + $3 } | Expression { $$</span> = 'case ' + $1 + ': \n' } ; Object : '{' OptNewLine OptIndent AssignList OptNewLine '}' { <span class="math-container">$$ = $1 + '\n' + $3 + $4 + '\n' + $6 } | '{' KeyList '}' { $$ = $1 + '\n' + $2 + '\n}' } | NL NL AssignList NL { $$ = '{\n' + $3 + '\n}' } | NL AssignList { $$ = '{\n' + $2 + '\n}' } | AssignList { $$ = '{\n' + $1 + '\n}' } | '{ }' { $$ = '{}' } ; AssignList : OptNewLine OptIndent Key ':' Expression ',' AssignList { $$ = $1 + $2 + $3 + ': ' + $5 + ',' + $7 } | OptNewLine OptIndent Key ':' Expression { $$ = '\n' + $2 + $3 + ': ' + $5 } ; Try : OptIndent try '{' OptNewLine Body OptNewLine OptIndent '}' catch ParamDef '{' OptNewLine Body OptNewLine OptIndent '}' finally '{' OptNewLine Body OptNewLine OptIndent '}' OptSemiColon { $$ = $1 + $try + ' {\n' + $1 + ' ' + $5 + '\n' + $1 + '} catch' + $ParamDef + ' {\n' + $1 + ' ' + $31 + '\n' + $1 + '} finally {\n' + $1 + ' ' + $20 + '\n' + $1 + '}' } | OptIndent try '{' OptNewLine Body OptNewLine OptIndent '}' catch ParamDef '{' OptNewLine Body OptNewLine OptIndent '}' OptSemiColon { $$ = $1 + $try + ' {\n' + $1 + ' ' + $6 + '\n' + $1 + '} catch' + $ParamDef + ' {\n' + $1 + ' ' + $13 + $1 + '\n};' } ; MultiLineString : STRING2 { function interpolate(str) { let current = str; str = str.replace(/\#\{(.*)\}/, function(_,match2) { return '${' + match2 + '}'}); while(str != current) { current = str; str = str.replace(/\#\{(.*)\}/, function(_,match2) { return '${' + match2 + '}'}); } return str; } $$ = "`" + interpolate($1.replace(/((^''')(\s*(?:(\\.)|(?!\'){3,}.)+\s*)('''$)|(^""")(\s*(?:(?!\'){3,}.)+\s*)("""$))/, function(_,Match1, Match2) { return Match1||Match2 })) + "`" } ; String : STRING1 { function interpolate(str) { let current = str; str = str.replace(/\#\{(.*)\}/, function(_,match2) { return '${' + match2 + '}'}); while(str != current) { current = str; str = str.replace(/\#\{(.*)\}/, function(_,match2) { return '${' + match2 + '}'}); } return str; } $$ = "'" + interpolate($1) + "'" } ; Key : String | Name | Number | '[' Name ']' { $$ = $1 + $2 + $3 } | '[' Primitive ']' { $$ = $1 + $2 + $3 } ; Primitive : Number | String | Boolean ; Access : '[' String ']' { $$ = $1 + $2 + $3 } | '[' Name ']' { $$ = $1 + $2 + $3 } | '.' Name { $$ = $1 + $2 } ; Name : name Access -&gt; $1 + $2 | name | '#' name -&gt; 'this.' + $2 | '#' { $$ = 'this' } | Name '::' name {$$ = $1 + '.prototype.' + $3} | Name '::' { $$ = $1 + '.prototype' } ; Number : number ; Pipe : Expression '|&gt;' Name {$$ = $Name + '(' + $Expression + ')' } | Expression '|&gt;' '#' Name {$$ = 'this.' + $Name + '(' + $Expression + ')' } | Pipe '|&gt;' Name {$$ = $3 + '(' + $1 + ')' } | Pipe '|&gt;' '#' Name {$$</span> = 'this.' + $4 + '(' + $1 + ')' } ; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T15:56:57.907", "Id": "388378", "Score": "0", "body": "Do you consider using ragel?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T16:02:35.690", "Id": "388380", "Score": "1", "body": "Is ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T15:44:20.670", "Id": "201668", "Score": "6", "Tags": [ "compiler", "language-design", "lex", "freezeflame", "jison" ], "Title": "Creating a new language: FreezeFlame" }
201668
<p>Attached is some code I have written for my application. It is an OWIN based web server which connects an Alexa Custom Skill, my security camera feed, and Microsoft Azure Face API.</p> <p>The number one thing to remember when creating an Alexa custom skill is that the bot times-out after about ten seconds. Because my service is collecting Security Camera Feeds for analysis from Microsoft Face API, it has to move fast. Really Fast!</p> <p>I've been able to utilize Tasks, and other TPL methods to make the service quickly gather the results I've been looking for.</p> <p>Originally, my <code>SecurityCameraApi</code> Class Library would try and collect proper data within each request to the service. </p> <p>This involved making several requests to the Cameras on-board web server to narrow down each URL to sort out saved static images, and recorded video data.</p> <p>This took time. Time Alexa is unforgiving about giving you time.</p> <p>Using the TPL to send off multiple images to the Face API at once saved some time, however, sorting Data from the Security Camera is still a problem.</p> <p><em>Note: With all the different Cameras on the market, there are so many ways they save data. One thing you can count on when building a generic way of reading data from Security Camera is that they will most likely save information in a <code>DateTime</code> format... of some kind.</em></p> <p>I have finally decided that the fastest way to collect the camera data cannot happen when an Alexa Request is made. </p> <p>Instead, I have opted to collect and organize data in a constant fashion using a <code>Threading.Timer</code>, and keeping the results in a prefabricated list of images (in <code>byte[]</code>, which is how I need the information stored).</p> <p>This means that an HTTP request for the camera's data is made more often (much more often).</p> <p>I have attempted to keep my code clean (as I can) so other people are able to follow it.</p> <p>Is it a good idea to poll data like that, and pre-process it?</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using SecurityConfiguration; namespace SecurityCameraApi { // ReSharper disable InconsistentNaming public class SecurityCamera //, IDisposable { private static Timer ImageCollectionUpdater { get; set; } private static Link CurrentDateDirectoryLink { get; set; } private static SecurityCamera camera { get; set; } private static List&lt;byte[]&gt; savedImageCollection; public List&lt;byte[]&gt; SaveImageCollection { get { return savedImageCollection; } private set { savedImageCollection = value; } } public SecurityCamera() { camera = this; } public void StartImageCollection() { ImageCollectionUpdater = new Timer(UpdateImageCollectionData); ImageCollectionUpdater.Change(0, 500); } private static readonly ConfigurationDto config = Configuration.GetSettings(); //public static Func&lt;byte[], string&gt; ConvertByteToBase64 = b =&gt; Convert.ToBase64String(b); private static List&lt;byte[]&gt; GetListOfSavedImagesAsByte() { var list = new List&lt;byte[]&gt;(); Func&lt;List&lt;Link&gt;, List&lt;Link&gt;&gt; lastTwelveListEntities = e =&gt; e.Reverse&lt;Link&gt;().Take(15).Reverse().Take(12).ToList(); try { string dateDirectoryData = GetUrlData(config.SecurityCameraSdUrl + CurrentDateDirectoryLink.Text); string currentImagesDirectoryHref = ""; Link currentImagesDirectoryLink; if (IsCurrentImageLinkDirectory(dateDirectoryData, out currentImagesDirectoryLink)) currentImagesDirectoryHref = currentImagesDirectoryLink.Href; List&lt;Link&gt; links = ParseLinkData( GetUrlData(config.SecurityCameraUrl + currentImagesDirectoryHref)).ToList(); Parallel.ForEach(links.Count() &gt;= 10 ? lastTwelveListEntities(links) : links, link =&gt; list.Add(camera.GetImageAsByte(config.SecurityCameraUrl + currentImagesDirectoryHref + link.Text))); } catch { } list.RemoveAll(item =&gt; item == (null)); return list; } public byte[] GetImageAsByte(string url) { try { using (var wc = new WebClient { Credentials = new NetworkCredential( config.SecurityCameraCredentialsUserName, config.SecurityCameraCredentialsPassword ) }) { byte[] imgByteData = wc.DownloadData(url); return imgByteData; } } catch { } return null; } //----------------------------------------------------------------// private struct Link { public string Href { get; set; } public string Text { get; set; } } private static IEnumerable&lt;Link&gt; ParseLinkData(string linkData) { var list = new List&lt;Link&gt;(); IEnumerable matches = Regex.Matches(linkData, @"(&lt;a.*?&gt;.*?&lt;/a&gt;)", RegexOptions.Singleline); Parallel.ForEach(matches.Cast&lt;Match&gt;(), match =&gt; { string value = match.Groups[1].Value; var link = new Link(); Match href = Regex.Match(value, @"href=\""(.*?)\""", RegexOptions.Singleline); if (href.Success) link.Href = href.Groups[1].Value; link.Text = Regex.Replace(value, @"\s*&lt;.*?&gt;\s*", "", RegexOptions.Singleline); try { list.Add(link); } catch { } }); return list; } private static Int64 FindOnlyNumericCharatersInString(string T) { try { return Int64.Parse(Regex.Replace(T, "[^0-9.]", String.Empty).Replace(".", String.Empty)); } catch { } return 0; } private static string GetUrlData(string sdCardDataUrl) { try { // Log into the security camera using (var wc = new WebClient { Credentials = new NetworkCredential( config.SecurityCameraCredentialsUserName, config.SecurityCameraCredentialsPassword ) }) { return wc.DownloadString(sdCardDataUrl); } } catch { } return null; } private static Link GetCurrentDateDirectoryLink() { Func&lt;DateTime, bool&gt; isCurrentDate = dt =&gt; dt.Year.Equals(DateTime.Now.Year) &amp;&amp; dt.Month.Equals(DateTime.Now.Month) &amp;&amp; dt.Day.Equals(DateTime.Now.Day); string rootDirectoryData = GetUrlData(config.SecurityCameraSdUrl); var l = new Link(); try { Parallel.ForEach(ParseLinkData(rootDirectoryData), link =&gt; { DateTime linkDate = DateSerializer.ParseFormatFromString( FindOnlyNumericCharatersInString(link.Text).ToString(CultureInfo.InvariantCulture)); if (isCurrentDate(linkDate)) { l = link; } }); } catch { } return l; } //----------------------------------------------------------------// private static void UpdateImageCollectionData(object args) { ImageCollectionUpdater.Change(Timeout.Infinite, Timeout.Infinite); CurrentDateDirectoryLink = GetCurrentDateDirectoryLink(); camera.SaveImageCollection = GetListOfSavedImagesAsByte(); ImageCollectionUpdater.Change(400, 500); } private static bool IsCurrentImageLinkDirectory(string urlData, out Link currentImagesLinkDirectory) { //There has to be a better way of splitting a string and sending back the best option! var dict = new Dictionary&lt;int, Link&gt;(); Parallel.ForEach(ParseLinkData(urlData), link =&gt; { int i = Int32.MaxValue; try { i = Convert.ToInt32(FindOnlyNumericCharatersInString(link.Text)); } catch { } if (!i.Equals(Int32.MaxValue) &amp;&amp; link.Text.Contains("image")) { dict.Add(i, link); } }); //var dict = ParseLinkData(urlData).ToDictionary(link =&gt; Convert.ToInt32(FindOnlyNumericCharatersInString(link.Text))); currentImagesLinkDirectory = dict[dict.Keys.Max()]; dict.Clear(); return true; } //--------------------------------------------------------------// } } </code></pre> <p>I haven't quite finished refactoring some of the methods. I realize that there are areas where I could use Generics to tighten up the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T20:16:59.177", "Id": "388417", "Score": "0", "body": "What happened to the `IDisposable` interface? Could you clean this up a little bit? The _dead_ code here and there is a little bit confusing." }, { "ContentLicense": "CC ...
[ { "body": "<p>If the data source can't give you new data fast enough to allow you to meet your time constraints, then you have to be able to run without calling the data source. In your case, that means having camera data already available, and that's going to require a solution similar to the one you describe...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T16:14:20.367", "Id": "201669", "Score": "4", "Tags": [ "c#", "timer" ], "Title": "Using Threading.Timer to update a list of data" }
201669
<p>I am trying to learn OOP by refactoring my existing code (functions only). This example works but I am not sure whether it is pythonic and good practice.</p> <p>I have a shared library which consist of several file with functions:</p> <p>color_spaces.py</p> <pre><code>import cv2 def rgb_to_hsv(image): print ('hsv') hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) hue, sat, val = hsv_image[:, :, 0], hsv_image[:, :, 1], hsv_image[:, :, 2] return hsv_image, hue, sat, val def rgb_to_lab(image): lab_image = cv2.cvtColor(image, cv2.COLOR_RGB2LAB) l_chan, a_chan, b_chan = lab_image[:, :, 0], lab_image[:, :, 1], lab_image[:, :, 2] return lab_image, l_chan, a_chan, b_chan </code></pre> <p>thresholding.py</p> <pre><code>import cv2 def treshold_otsu(gray_image): ret, thresholded_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) return thresholded_image def global_threshold(gray_image): ret, thresholded_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY) return thresholded_image </code></pre> <p>My class which uses functions of the shared library:</p> <p>pipline01.py</p> <pre><code>import cv2 from color_spaces import rgb_to_hsv, rgb_to_lab from thresholding import treshold_otsu, global_threshold class Segmentation1(object): def __init__(self, filename, path, procedure): self.filename = filename self.path = path self.procedure = procedure def start_pipline(self): # Read image image = cv2.imread(self.path + self.filename) # Do segmentation procedure depending on procedure if self.procedure == 'test01': source = rgb_to_hsv(image)[1] binary = treshold_otsu(source) elif self.procedure == 'test02': source = rgb_to_lab(image)[1] binary = global_threshold(source) # Save image cv2.imwrite(self.path + self.filename.split('.')[0] + '_' + self.procedure + '.png', binary) </code></pre> <p>Then I call the class in a batch mode by looping over a folder with images:</p> <p>batch_pipline01.py</p> <pre><code>import os import argparse from pipline01 import Segmentation1 parser = argparse.ArgumentParser(description = 'Test.') parser.add_argument('-d', '--img_dir', required = True, help = 'directory containing images to segment.') parser.add_argument('-p', '--procedure', required = True, help = 'procedure to run.') args = parser.parse_args() print(args) img_dir = args.img_dir procedure = args.procedure images = os.listdir(img_dir) #images = [img[2:] for img in args.images] # Start segmentation for each image for img in images: os.chdir(img_dir) print('SEGMENTING ' + img) segmenter = Segmentation1(img, img_dir, procedure) obj = segmenter.start_pipline() del obj </code></pre> <p>Can I improve my code and design?</p>
[]
[ { "body": "<p>This scenario is not best case for doing an OOP conversion: In this example you're not getting real assistance from the <code>Segmentation1</code> class over what you'd get by using static functions. The code looks like it does what you need done; it's simply not a great application for OOP as wr...
{ "AcceptedAnswerId": "201695", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T17:07:43.443", "Id": "201672", "Score": "2", "Tags": [ "python", "object-oriented", "image", "opencv" ], "Title": "Image processing using Python OOP library" }
201672
<p>Jison is a format of language grammar description, based upon Yacc and Bison. Jison is commonly used to convert a grammar to a JavaScript module that parses and tokenizes the text put in, and optionally returns the parsed text, with optional replacements made. It uses mode based parsing to do the job. Learn more: <a href="http://zaa.ch/jison/" rel="nofollow noreferrer">http://zaa.ch/jison/</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T18:05:05.333", "Id": "201674", "Score": "0", "Tags": null, "Title": null }
201674